@bufbuild/protobuf 0.0.8 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +34 -4
  2. package/dist/cjs/codegen-info.js +60 -0
  3. package/dist/cjs/create-descriptor-set.js +952 -0
  4. package/dist/cjs/create-registry-from-desc.js +376 -0
  5. package/dist/cjs/create-registry.js +75 -0
  6. package/dist/cjs/descriptor-set.js +0 -436
  7. package/dist/cjs/google/protobuf/struct_pb.js +1 -1
  8. package/dist/cjs/google/protobuf/type_pb.js +1 -1
  9. package/dist/cjs/index.js +17 -7
  10. package/dist/cjs/{descriptor-registry.js → legacy-descriptor-registry.js} +18 -10
  11. package/dist/cjs/legacy-descriptor-set.js +453 -0
  12. package/dist/cjs/legacy-type-registry.js +104 -0
  13. package/dist/cjs/private/enum.js +22 -31
  14. package/dist/cjs/private/field-wrapper.js +30 -1
  15. package/dist/cjs/private/field.js +1 -1
  16. package/dist/cjs/private/names.js +168 -29
  17. package/dist/cjs/proto2.js +2 -2
  18. package/dist/cjs/proto3.js +2 -2
  19. package/dist/cjs/type-registry.js +0 -87
  20. package/dist/esm/codegen-info.js +57 -0
  21. package/dist/esm/create-descriptor-set.js +947 -0
  22. package/dist/esm/create-registry-from-desc.js +371 -0
  23. package/dist/esm/create-registry.js +71 -0
  24. package/dist/esm/descriptor-set.js +1 -434
  25. package/dist/esm/google/protobuf/struct_pb.js +1 -1
  26. package/dist/esm/google/protobuf/type_pb.js +1 -1
  27. package/dist/esm/index.js +9 -3
  28. package/dist/esm/{descriptor-registry.js → legacy-descriptor-registry.js} +16 -8
  29. package/dist/esm/legacy-descriptor-set.js +449 -0
  30. package/dist/esm/legacy-type-registry.js +100 -0
  31. package/dist/esm/private/enum.js +22 -31
  32. package/dist/esm/private/field-wrapper.js +28 -0
  33. package/dist/esm/private/field.js +2 -2
  34. package/dist/esm/private/names.js +163 -24
  35. package/dist/esm/proto2.js +3 -3
  36. package/dist/esm/proto3.js +3 -3
  37. package/dist/esm/type-registry.js +1 -85
  38. package/dist/types/codegen-info.d.ts +19 -0
  39. package/dist/types/create-descriptor-set.d.ts +16 -0
  40. package/dist/types/create-registry-from-desc.d.ts +49 -0
  41. package/dist/types/create-registry.d.ts +8 -0
  42. package/dist/types/descriptor-set.d.ts +554 -108
  43. package/dist/types/enum.d.ts +9 -5
  44. package/dist/types/index.d.ts +9 -3
  45. package/dist/types/{descriptor-registry.d.ts → legacy-descriptor-registry.d.ts} +8 -6
  46. package/dist/types/legacy-descriptor-set.d.ts +152 -0
  47. package/dist/types/legacy-type-registry.d.ts +44 -0
  48. package/dist/types/private/enum.d.ts +4 -8
  49. package/dist/types/private/field-wrapper.d.ts +7 -0
  50. package/dist/types/private/message-type.d.ts +1 -4
  51. package/dist/types/private/names.d.ts +26 -8
  52. package/dist/types/private/proto-runtime.d.ts +2 -2
  53. package/dist/types/private/util.d.ts +1 -6
  54. package/dist/types/type-registry.d.ts +0 -38
  55. package/package.json +2 -2
  56. package/dist/protobuf.cjs +0 -2
  57. package/dist/protobuf.cjs.map +0 -1
  58. package/dist/protobuf.esm.js +0 -2
  59. package/dist/protobuf.esm.js.map +0 -1
  60. package/dist/protobuf.modern.js +0 -2
  61. package/dist/protobuf.modern.js.map +0 -1
@@ -0,0 +1,947 @@
1
+ // Copyright 2021-2022 Buf Technologies, Inc.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ import { FieldDescriptorProto_Label, FieldDescriptorProto_Type, FileDescriptorSet, MethodOptions_IdempotencyLevel, } from "./google/protobuf/descriptor_pb.js";
15
+ import { assert } from "./private/assert.js";
16
+ import { ScalarType } from "./field.js";
17
+ import { MethodIdempotency, MethodKind } from "./service-type.js";
18
+ import { findEnumSharedPrefix, fieldJsonName } from "./private/names.js";
19
+ import { protoInt64 } from "./proto-int64.js";
20
+ /**
21
+ * Create a DescriptorSet, a convenient interface for working with a set of
22
+ * google.protobuf.FileDescriptorProto.
23
+ *
24
+ * Note that files must be given in topological order, so each file appears
25
+ * before any file that imports it. Protocol buffer compilers always produce
26
+ * files in topological order.
27
+ */
28
+ export function createDescriptorSet(input) {
29
+ const cart = {
30
+ enums: new Map(),
31
+ messages: new Map(),
32
+ services: new Map(),
33
+ extensions: new Map(),
34
+ mapEntries: new Map(),
35
+ };
36
+ const fileDescriptors = input instanceof FileDescriptorSet
37
+ ? input.file
38
+ : input instanceof Uint8Array
39
+ ? FileDescriptorSet.fromBinary(input).file
40
+ : input;
41
+ const files = fileDescriptors.map((proto) => newFile(proto, cart));
42
+ return Object.assign({ files }, cart);
43
+ }
44
+ /**
45
+ * Create a descriptor for a file.
46
+ */
47
+ function newFile(proto, cart) {
48
+ var _a, _b, _c;
49
+ assert(proto.name, `invalid FileDescriptorProto: missing name`);
50
+ assert(proto.syntax === undefined || proto.syntax === "proto3", `invalid FileDescriptorProto: unsupported syntax: ${(_a = proto.syntax) !== null && _a !== void 0 ? _a : "undefined"}`);
51
+ const file = {
52
+ kind: "file",
53
+ proto,
54
+ deprecated: (_c = (_b = proto.options) === null || _b === void 0 ? void 0 : _b.deprecated) !== null && _c !== void 0 ? _c : false,
55
+ syntax: proto.syntax === "proto3" ? "proto3" : "proto2",
56
+ name: proto.name.replace(/\.proto/, ""),
57
+ enums: [],
58
+ messages: [],
59
+ extensions: [],
60
+ services: [],
61
+ toString() {
62
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- we asserted above
63
+ return `file ${this.proto.name}`;
64
+ },
65
+ getSyntaxComments() {
66
+ return findComments(this.proto.sourceCodeInfo, [
67
+ FieldNumber.FileDescriptorProto_Syntax,
68
+ ]);
69
+ },
70
+ getPackageComments() {
71
+ return findComments(this.proto.sourceCodeInfo, [
72
+ FieldNumber.FileDescriptorProto_Package,
73
+ ]);
74
+ },
75
+ };
76
+ cart.mapEntries.clear(); // map entries are local to the file, we can safely discard
77
+ for (const enumProto of proto.enumType) {
78
+ addEnum(enumProto, file, undefined, cart);
79
+ }
80
+ for (const messageProto of proto.messageType) {
81
+ addMessage(messageProto, file, undefined, cart);
82
+ }
83
+ for (const serviceProto of proto.service) {
84
+ addService(serviceProto, file, cart);
85
+ }
86
+ addExtensions(file, cart);
87
+ for (const mapEntry of cart.mapEntries.values()) {
88
+ addFields(mapEntry, cart);
89
+ }
90
+ for (const message of file.messages) {
91
+ addFields(message, cart);
92
+ addExtensions(message, cart);
93
+ }
94
+ cart.mapEntries.clear(); // map entries are local to the file, we can safely discard
95
+ return file;
96
+ }
97
+ /**
98
+ * Create descriptors for extensions, and add them to the message / file,
99
+ * and to our cart.
100
+ * Recurses into nested types.
101
+ */
102
+ function addExtensions(desc, cart) {
103
+ switch (desc.kind) {
104
+ case "file":
105
+ for (const proto of desc.proto.extension) {
106
+ const ext = newExtension(proto, desc, undefined, cart);
107
+ desc.extensions.push(ext);
108
+ cart.extensions.set(ext.typeName, ext);
109
+ }
110
+ break;
111
+ case "message":
112
+ for (const proto of desc.proto.extension) {
113
+ const ext = newExtension(proto, desc.file, desc, cart);
114
+ desc.nestedExtensions.push(ext);
115
+ cart.extensions.set(ext.typeName, ext);
116
+ }
117
+ for (const message of desc.nestedMessages) {
118
+ addExtensions(message, cart);
119
+ }
120
+ break;
121
+ }
122
+ }
123
+ /**
124
+ * Create descriptors for fields and oneof groups, and add them to the message.
125
+ * Recurses into nested types.
126
+ */
127
+ function addFields(message, cart) {
128
+ const allOneofs = message.proto.oneofDecl.map((proto) => newOneof(proto, message));
129
+ const oneofsSeen = new Set();
130
+ for (const proto of message.proto.field) {
131
+ const oneof = findOneof(proto, allOneofs);
132
+ const field = newField(proto, message.file, message, oneof, cart);
133
+ message.fields.push(field);
134
+ if (oneof === undefined) {
135
+ message.members.push(field);
136
+ }
137
+ else {
138
+ oneof.fields.push(field);
139
+ if (!oneofsSeen.has(oneof)) {
140
+ oneofsSeen.add(oneof);
141
+ message.members.push(oneof);
142
+ }
143
+ }
144
+ }
145
+ for (const oneof of allOneofs.filter((o) => oneofsSeen.has(o))) {
146
+ message.oneofs.push(oneof);
147
+ }
148
+ for (const child of message.nestedMessages) {
149
+ addFields(child, cart);
150
+ }
151
+ }
152
+ /**
153
+ * Create a descriptor for an enumeration, and add it our cart and to the
154
+ * parent type, if any.
155
+ */
156
+ function addEnum(proto, file, parent, cart) {
157
+ var _a, _b, _c;
158
+ assert(proto.name, `invalid EnumDescriptorProto: missing name`);
159
+ const desc = {
160
+ kind: "enum",
161
+ proto,
162
+ deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
163
+ file,
164
+ parent,
165
+ name: proto.name,
166
+ typeName: makeTypeName(proto, parent, file),
167
+ values: [],
168
+ sharedPrefix: findEnumSharedPrefix(proto.name, proto.value.map((v) => { var _a; return (_a = v.name) !== null && _a !== void 0 ? _a : ""; })),
169
+ toString() {
170
+ return `enum ${this.typeName}`;
171
+ },
172
+ getComments() {
173
+ const path = this.parent
174
+ ? [
175
+ ...this.parent.getComments().sourcePath,
176
+ FieldNumber.DescriptorProto_EnumType,
177
+ this.parent.proto.enumType.indexOf(this.proto),
178
+ ]
179
+ : [
180
+ FieldNumber.FileDescriptorProto_EnumType,
181
+ this.file.proto.enumType.indexOf(this.proto),
182
+ ];
183
+ return findComments(file.proto.sourceCodeInfo, path);
184
+ },
185
+ };
186
+ cart.enums.set(desc.typeName, desc);
187
+ proto.value.forEach((proto) => {
188
+ var _a, _b;
189
+ assert(proto.name, `invalid EnumValueDescriptorProto: missing name`);
190
+ assert(proto.number !== undefined, `invalid EnumValueDescriptorProto: missing number`);
191
+ desc.values.push({
192
+ kind: "enum_value",
193
+ proto,
194
+ deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
195
+ parent: desc,
196
+ name: proto.name,
197
+ number: proto.number,
198
+ toString() {
199
+ return `enum value ${desc.typeName}.${this.name}`;
200
+ },
201
+ declarationString() {
202
+ var _a;
203
+ let str = `${this.name} = ${this.number}`;
204
+ if (((_a = this.proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) === true) {
205
+ str += " [deprecated = true]";
206
+ }
207
+ return str;
208
+ },
209
+ getComments() {
210
+ const path = [
211
+ ...this.parent.getComments().sourcePath,
212
+ FieldNumber.EnumDescriptorProto_Value,
213
+ this.parent.proto.value.indexOf(this.proto),
214
+ ];
215
+ return findComments(file.proto.sourceCodeInfo, path);
216
+ },
217
+ });
218
+ });
219
+ ((_c = parent === null || parent === void 0 ? void 0 : parent.nestedEnums) !== null && _c !== void 0 ? _c : file.enums).push(desc);
220
+ }
221
+ /**
222
+ * Create a descriptor for a message, including nested types, and add it to our
223
+ * cart. Note that this does not create descriptors fields.
224
+ */
225
+ function addMessage(proto, file, parent, cart) {
226
+ var _a, _b, _c, _d;
227
+ assert(proto.name, `invalid DescriptorProto: missing name`);
228
+ const desc = {
229
+ kind: "message",
230
+ proto,
231
+ deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
232
+ file,
233
+ parent,
234
+ name: proto.name,
235
+ typeName: makeTypeName(proto, parent, file),
236
+ fields: [],
237
+ oneofs: [],
238
+ members: [],
239
+ nestedEnums: [],
240
+ nestedMessages: [],
241
+ nestedExtensions: [],
242
+ toString() {
243
+ return `message ${this.typeName}`;
244
+ },
245
+ getComments() {
246
+ const path = this.parent
247
+ ? [
248
+ ...this.parent.getComments().sourcePath,
249
+ FieldNumber.DescriptorProto_NestedType,
250
+ this.parent.proto.nestedType.indexOf(this.proto),
251
+ ]
252
+ : [
253
+ FieldNumber.FileDescriptorProto_MessageType,
254
+ this.file.proto.messageType.indexOf(this.proto),
255
+ ];
256
+ return findComments(file.proto.sourceCodeInfo, path);
257
+ },
258
+ };
259
+ if (((_c = proto.options) === null || _c === void 0 ? void 0 : _c.mapEntry) === true) {
260
+ cart.mapEntries.set(desc.typeName, desc);
261
+ }
262
+ else {
263
+ ((_d = parent === null || parent === void 0 ? void 0 : parent.nestedMessages) !== null && _d !== void 0 ? _d : file.messages).push(desc);
264
+ cart.messages.set(desc.typeName, desc);
265
+ }
266
+ for (const enumProto of proto.enumType) {
267
+ addEnum(enumProto, file, desc, cart);
268
+ }
269
+ for (const messageProto of proto.nestedType) {
270
+ addMessage(messageProto, file, desc, cart);
271
+ }
272
+ }
273
+ /**
274
+ * Create a descriptor for a service, including methods, and add it to our
275
+ * cart.
276
+ */
277
+ function addService(proto, file, cart) {
278
+ var _a, _b;
279
+ assert(proto.name, `invalid ServiceDescriptorProto: missing name`);
280
+ const desc = {
281
+ kind: "service",
282
+ proto,
283
+ deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
284
+ file,
285
+ name: proto.name,
286
+ typeName: makeTypeName(proto, undefined, file),
287
+ methods: [],
288
+ toString() {
289
+ return `service ${this.typeName}`;
290
+ },
291
+ getComments() {
292
+ const path = [
293
+ FieldNumber.FileDescriptorProto_Service,
294
+ this.file.proto.service.indexOf(this.proto),
295
+ ];
296
+ return findComments(file.proto.sourceCodeInfo, path);
297
+ },
298
+ };
299
+ file.services.push(desc);
300
+ cart.services.set(desc.typeName, desc);
301
+ for (const methodProto of proto.method) {
302
+ desc.methods.push(newMethod(methodProto, desc, cart));
303
+ }
304
+ }
305
+ /**
306
+ * Create a descriptor for a method.
307
+ */
308
+ function newMethod(proto, parent, cart) {
309
+ var _a, _b, _c;
310
+ assert(proto.name, `invalid MethodDescriptorProto: missing name`);
311
+ assert(proto.inputType, `invalid MethodDescriptorProto: missing input_type`);
312
+ assert(proto.outputType, `invalid MethodDescriptorProto: missing output_type`);
313
+ let methodKind;
314
+ if (proto.clientStreaming === true && proto.serverStreaming === true) {
315
+ methodKind = MethodKind.BiDiStreaming;
316
+ }
317
+ else if (proto.clientStreaming === true) {
318
+ methodKind = MethodKind.ClientStreaming;
319
+ }
320
+ else if (proto.serverStreaming === true) {
321
+ methodKind = MethodKind.ServerStreaming;
322
+ }
323
+ else {
324
+ methodKind = MethodKind.Unary;
325
+ }
326
+ let idempotency;
327
+ switch ((_a = proto.options) === null || _a === void 0 ? void 0 : _a.idempotencyLevel) {
328
+ case MethodOptions_IdempotencyLevel.IDEMPOTENT:
329
+ idempotency = MethodIdempotency.Idempotent;
330
+ break;
331
+ case MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS:
332
+ idempotency = MethodIdempotency.NoSideEffects;
333
+ break;
334
+ case MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN:
335
+ case undefined:
336
+ idempotency = undefined;
337
+ break;
338
+ }
339
+ const input = cart.messages.get(trimLeadingDot(proto.inputType));
340
+ const output = cart.messages.get(trimLeadingDot(proto.outputType));
341
+ assert(input, `invalid MethodDescriptorProto: input_type ${proto.inputType} not found`);
342
+ assert(output, `invalid MethodDescriptorProto: output_type ${proto.inputType} not found`);
343
+ const name = proto.name;
344
+ return {
345
+ kind: "rpc",
346
+ proto,
347
+ deprecated: (_c = (_b = proto.options) === null || _b === void 0 ? void 0 : _b.deprecated) !== null && _c !== void 0 ? _c : false,
348
+ parent,
349
+ name,
350
+ methodKind,
351
+ input,
352
+ output,
353
+ idempotency,
354
+ toString() {
355
+ return `rpc ${parent.typeName}.${name}`;
356
+ },
357
+ getComments() {
358
+ const path = [
359
+ ...this.parent.getComments().sourcePath,
360
+ FieldNumber.ServiceDescriptorProto_Method,
361
+ this.parent.proto.method.indexOf(this.proto),
362
+ ];
363
+ return findComments(parent.file.proto.sourceCodeInfo, path);
364
+ },
365
+ };
366
+ }
367
+ /**
368
+ * Create a descriptor for a oneof group.
369
+ */
370
+ function newOneof(proto, parent) {
371
+ assert(proto.name, `invalid OneofDescriptorProto: missing name`);
372
+ return {
373
+ kind: "oneof",
374
+ proto,
375
+ deprecated: false,
376
+ parent,
377
+ fields: [],
378
+ name: proto.name,
379
+ toString() {
380
+ return `oneof ${parent.typeName}.${this.name}`;
381
+ },
382
+ getComments() {
383
+ const path = [
384
+ ...this.parent.getComments().sourcePath,
385
+ FieldNumber.DescriptorProto_OneofDecl,
386
+ this.parent.proto.oneofDecl.indexOf(this.proto),
387
+ ];
388
+ return findComments(parent.file.proto.sourceCodeInfo, path);
389
+ },
390
+ };
391
+ }
392
+ /**
393
+ * Create a descriptor for a field.
394
+ */
395
+ function newField(proto, file, parent, oneof, cart) {
396
+ var _a, _b, _c, _d;
397
+ assert(proto.name, `invalid FieldDescriptorProto: missing name`);
398
+ assert(proto.number, `invalid FieldDescriptorProto: missing number`);
399
+ assert(proto.type, `invalid FieldDescriptorProto: missing type`);
400
+ const packedByDefault = isPackedFieldByDefault(proto, file.syntax);
401
+ const common = {
402
+ proto,
403
+ deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
404
+ name: proto.name,
405
+ number: proto.number,
406
+ parent,
407
+ oneof,
408
+ optional: isOptionalField(proto, file.syntax),
409
+ packed: (_d = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.packed) !== null && _d !== void 0 ? _d : packedByDefault,
410
+ packedByDefault,
411
+ jsonName: proto.jsonName === fieldJsonName(proto.name) ? undefined : proto.jsonName,
412
+ scalar: undefined,
413
+ message: undefined,
414
+ enum: undefined,
415
+ mapKey: undefined,
416
+ mapValue: undefined,
417
+ toString() {
418
+ // note that newExtension() calls us with parent = null
419
+ return `field ${this.parent.typeName}.${this.name}`;
420
+ },
421
+ declarationString,
422
+ getComments() {
423
+ const path = [
424
+ ...this.parent.getComments().sourcePath,
425
+ FieldNumber.DescriptorProto_Field,
426
+ this.parent.proto.field.indexOf(this.proto),
427
+ ];
428
+ return findComments(file.proto.sourceCodeInfo, path);
429
+ },
430
+ };
431
+ const repeated = proto.label === FieldDescriptorProto_Label.REPEATED;
432
+ switch (proto.type) {
433
+ case FieldDescriptorProto_Type.MESSAGE:
434
+ case FieldDescriptorProto_Type.GROUP: {
435
+ assert(proto.typeName, `invalid FieldDescriptorProto: missing type_name`);
436
+ const mapEntry = cart.mapEntries.get(trimLeadingDot(proto.typeName));
437
+ if (mapEntry !== undefined) {
438
+ assert(repeated, `invalid FieldDescriptorProto: expected map entry to be repeated`);
439
+ return Object.assign(Object.assign(Object.assign({}, common), { kind: "map_field", repeated: false }), getMapFieldTypes(mapEntry));
440
+ }
441
+ const message = cart.messages.get(trimLeadingDot(proto.typeName));
442
+ assert(message !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
443
+ return Object.assign(Object.assign({}, common), { kind: "message_field", repeated,
444
+ message });
445
+ }
446
+ case FieldDescriptorProto_Type.ENUM: {
447
+ assert(proto.typeName, `invalid FieldDescriptorProto: missing type_name`);
448
+ const e = cart.enums.get(trimLeadingDot(proto.typeName));
449
+ assert(e !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
450
+ return Object.assign(Object.assign({}, common), { kind: "enum_field", getDefaultValue,
451
+ repeated, enum: e });
452
+ }
453
+ default: {
454
+ const scalar = fieldTypeToScalarType[proto.type];
455
+ assert(scalar, `invalid FieldDescriptorProto: unknown type ${proto.type}`);
456
+ return Object.assign(Object.assign({}, common), { kind: "scalar_field", getDefaultValue,
457
+ repeated,
458
+ scalar });
459
+ }
460
+ }
461
+ }
462
+ /**
463
+ * Create a descriptor for an extension field.
464
+ */
465
+ function newExtension(proto, file, parent, cart) {
466
+ assert(proto.extendee, `invalid FieldDescriptorProto: missing extendee`);
467
+ const field = newField(proto, file, null, // to safe us many lines of duplicated code, we trick the type system
468
+ undefined, cart);
469
+ const extendee = cart.messages.get(trimLeadingDot(proto.extendee));
470
+ assert(extendee, `invalid FieldDescriptorProto: extendee ${proto.extendee} not found`);
471
+ return Object.assign(Object.assign({}, field), { typeName: makeTypeName(proto, parent, file), parent,
472
+ file,
473
+ extendee,
474
+ toString() {
475
+ return `extension ${this.typeName}`;
476
+ },
477
+ getComments() {
478
+ const path = this.parent
479
+ ? [
480
+ ...this.parent.getComments().sourcePath,
481
+ FieldNumber.DescriptorProto_Extension,
482
+ this.parent.proto.extension.indexOf(proto),
483
+ ]
484
+ : [
485
+ FieldNumber.FileDescriptorProto_Extension,
486
+ this.file.proto.extension.indexOf(proto),
487
+ ];
488
+ return findComments(file.proto.sourceCodeInfo, path);
489
+ } });
490
+ }
491
+ /**
492
+ * Create a fully qualified name for a protobuf type or extension field.
493
+ *
494
+ * The fully qualified name for messages, enumerations, and services is
495
+ * constructed by concatenating the package name (if present), parent
496
+ * message names (for nested types), and the type name. We omit the leading
497
+ * dot added by protobuf compilers. Examples:
498
+ * - mypackage.MyMessage
499
+ * - mypackage.MyMessage.NestedMessage
500
+ *
501
+ * The fully qualified name for extension fields is constructed by
502
+ * concatenating the package name (if present), parent message names (for
503
+ * extensions declared within a message), and the field name. Examples:
504
+ * - mypackage.extfield
505
+ * - mypackage.MyMessage.extfield
506
+ */
507
+ function makeTypeName(proto, parent, file) {
508
+ assert(proto.name, `invalid ${proto.getType().typeName}: missing name`);
509
+ let typeName;
510
+ if (parent) {
511
+ typeName = `${parent.typeName}.${proto.name}`;
512
+ }
513
+ else if (file.proto.package !== undefined) {
514
+ typeName = `${file.proto.package}.${proto.name}`;
515
+ }
516
+ else {
517
+ typeName = `${proto.name}`;
518
+ }
519
+ return typeName;
520
+ }
521
+ /**
522
+ * Remove the leading dot from a fully qualified type name.
523
+ */
524
+ function trimLeadingDot(typeName) {
525
+ return typeName.startsWith(".") ? typeName.substring(1) : typeName;
526
+ }
527
+ function getMapFieldTypes(mapEntry) {
528
+ var _a, _b;
529
+ assert((_a = mapEntry.proto.options) === null || _a === void 0 ? void 0 : _a.mapEntry, `invalid DescriptorProto: expected ${mapEntry.toString()} to be a map entry`);
530
+ assert(mapEntry.fields.length === 2, `invalid DescriptorProto: map entry ${mapEntry.toString()} has ${mapEntry.fields.length} fields`);
531
+ const keyField = mapEntry.fields.find((f) => f.proto.number === 1);
532
+ assert(keyField, `invalid DescriptorProto: map entry ${mapEntry.toString()} is missing key field`);
533
+ const mapKey = keyField.scalar;
534
+ assert(mapKey !== undefined &&
535
+ mapKey !== ScalarType.BYTES &&
536
+ mapKey !== ScalarType.FLOAT &&
537
+ mapKey !== ScalarType.DOUBLE, `invalid DescriptorProto: map entry ${mapEntry.toString()} has unexpected key type ${(_b = keyField.proto.type) !== null && _b !== void 0 ? _b : -1}`);
538
+ const valueField = mapEntry.fields.find((f) => f.proto.number === 2);
539
+ assert(valueField, `invalid DescriptorProto: map entry ${mapEntry.toString()} is missing value field`);
540
+ switch (valueField.kind) {
541
+ case "scalar_field":
542
+ return {
543
+ mapKey,
544
+ mapValue: Object.assign(Object.assign({}, valueField), { kind: "scalar" }),
545
+ };
546
+ case "message_field":
547
+ return {
548
+ mapKey,
549
+ mapValue: Object.assign(Object.assign({}, valueField), { kind: "message" }),
550
+ };
551
+ case "enum_field":
552
+ return {
553
+ mapKey,
554
+ mapValue: Object.assign(Object.assign({}, valueField), { kind: "enum" }),
555
+ };
556
+ default:
557
+ throw new Error("invalid DescriptorProto: unsupported map entry value field");
558
+ }
559
+ }
560
+ /**
561
+ * Did the user put the field in a oneof group?
562
+ * This handles proto3 optionals.
563
+ */
564
+ function findOneof(proto, allOneofs) {
565
+ var _a;
566
+ const oneofIndex = proto.oneofIndex;
567
+ if (oneofIndex === undefined) {
568
+ return undefined;
569
+ }
570
+ let oneof;
571
+ if (proto.proto3Optional !== true) {
572
+ oneof = allOneofs[oneofIndex];
573
+ assert(oneof, `invalid FieldDescriptorProto: oneof #${oneofIndex} for field #${(_a = proto.number) !== null && _a !== void 0 ? _a : -1} not found`);
574
+ }
575
+ return oneof;
576
+ }
577
+ /**
578
+ * Did the user use the `optional` keyword?
579
+ * This handles proto3 optionals.
580
+ */
581
+ function isOptionalField(proto, syntax) {
582
+ switch (syntax) {
583
+ case "proto2":
584
+ return (proto.oneofIndex === undefined &&
585
+ proto.label === FieldDescriptorProto_Label.OPTIONAL);
586
+ case "proto3":
587
+ return proto.proto3Optional === true;
588
+ }
589
+ }
590
+ /**
591
+ * Get the default `packed` state of a repeated field.
592
+ */
593
+ export function isPackedFieldByDefault(proto, syntax) {
594
+ assert(proto.type, `invalid FieldDescriptorProto: missing type`);
595
+ if (syntax === "proto3") {
596
+ switch (proto.type) {
597
+ case FieldDescriptorProto_Type.DOUBLE:
598
+ case FieldDescriptorProto_Type.FLOAT:
599
+ case FieldDescriptorProto_Type.INT64:
600
+ case FieldDescriptorProto_Type.UINT64:
601
+ case FieldDescriptorProto_Type.INT32:
602
+ case FieldDescriptorProto_Type.FIXED64:
603
+ case FieldDescriptorProto_Type.FIXED32:
604
+ case FieldDescriptorProto_Type.UINT32:
605
+ case FieldDescriptorProto_Type.SFIXED32:
606
+ case FieldDescriptorProto_Type.SFIXED64:
607
+ case FieldDescriptorProto_Type.SINT32:
608
+ case FieldDescriptorProto_Type.SINT64:
609
+ case FieldDescriptorProto_Type.BOOL:
610
+ case FieldDescriptorProto_Type.ENUM:
611
+ // From the proto3 language guide:
612
+ // > In proto3, repeated fields of scalar numeric types are packed by default.
613
+ // This information is incomplete - according to the conformance tests, BOOL
614
+ // and ENUM are packed by default as well. This means only STRING and BYTES
615
+ // are not packed by default, which makes sense because they are length-delimited.
616
+ return true;
617
+ default:
618
+ return false;
619
+ }
620
+ }
621
+ return false;
622
+ }
623
+ /**
624
+ * Map from a compiler-generated field type to our ScalarType, which is a
625
+ * subset of field types declared by protobuf enum google.protobuf.FieldDescriptorProto.
626
+ */
627
+ const fieldTypeToScalarType = {
628
+ [FieldDescriptorProto_Type.DOUBLE]: ScalarType.DOUBLE,
629
+ [FieldDescriptorProto_Type.FLOAT]: ScalarType.FLOAT,
630
+ [FieldDescriptorProto_Type.INT64]: ScalarType.INT64,
631
+ [FieldDescriptorProto_Type.UINT64]: ScalarType.UINT64,
632
+ [FieldDescriptorProto_Type.INT32]: ScalarType.INT32,
633
+ [FieldDescriptorProto_Type.FIXED64]: ScalarType.FIXED64,
634
+ [FieldDescriptorProto_Type.FIXED32]: ScalarType.FIXED32,
635
+ [FieldDescriptorProto_Type.BOOL]: ScalarType.BOOL,
636
+ [FieldDescriptorProto_Type.STRING]: ScalarType.STRING,
637
+ [FieldDescriptorProto_Type.GROUP]: undefined,
638
+ [FieldDescriptorProto_Type.MESSAGE]: undefined,
639
+ [FieldDescriptorProto_Type.BYTES]: ScalarType.BYTES,
640
+ [FieldDescriptorProto_Type.UINT32]: ScalarType.UINT32,
641
+ [FieldDescriptorProto_Type.ENUM]: undefined,
642
+ [FieldDescriptorProto_Type.SFIXED32]: ScalarType.SFIXED32,
643
+ [FieldDescriptorProto_Type.SFIXED64]: ScalarType.SFIXED64,
644
+ [FieldDescriptorProto_Type.SINT32]: ScalarType.SINT32,
645
+ [FieldDescriptorProto_Type.SINT64]: ScalarType.SINT64,
646
+ };
647
+ /**
648
+ * Find comments.
649
+ */
650
+ function findComments(sourceCodeInfo, sourcePath) {
651
+ if (!sourceCodeInfo) {
652
+ return {
653
+ leadingDetached: [],
654
+ sourcePath,
655
+ };
656
+ }
657
+ for (const location of sourceCodeInfo.location) {
658
+ if (location.path.length !== sourcePath.length) {
659
+ continue;
660
+ }
661
+ if (location.path.some((value, index) => sourcePath[index] !== value)) {
662
+ continue;
663
+ }
664
+ return {
665
+ leadingDetached: location.leadingDetachedComments,
666
+ leading: location.leadingComments,
667
+ trailing: location.trailingComments,
668
+ sourcePath,
669
+ };
670
+ }
671
+ return {
672
+ leadingDetached: [],
673
+ sourcePath,
674
+ };
675
+ }
676
+ /**
677
+ * The following field numbers are used to find comments in
678
+ * google.protobuf.SourceCodeInfo.
679
+ */
680
+ var FieldNumber;
681
+ (function (FieldNumber) {
682
+ FieldNumber[FieldNumber["FileDescriptorProto_Package"] = 2] = "FileDescriptorProto_Package";
683
+ FieldNumber[FieldNumber["FileDescriptorProto_MessageType"] = 4] = "FileDescriptorProto_MessageType";
684
+ FieldNumber[FieldNumber["FileDescriptorProto_EnumType"] = 5] = "FileDescriptorProto_EnumType";
685
+ FieldNumber[FieldNumber["FileDescriptorProto_Service"] = 6] = "FileDescriptorProto_Service";
686
+ FieldNumber[FieldNumber["FileDescriptorProto_Extension"] = 7] = "FileDescriptorProto_Extension";
687
+ FieldNumber[FieldNumber["FileDescriptorProto_Syntax"] = 12] = "FileDescriptorProto_Syntax";
688
+ FieldNumber[FieldNumber["DescriptorProto_Field"] = 2] = "DescriptorProto_Field";
689
+ FieldNumber[FieldNumber["DescriptorProto_NestedType"] = 3] = "DescriptorProto_NestedType";
690
+ FieldNumber[FieldNumber["DescriptorProto_EnumType"] = 4] = "DescriptorProto_EnumType";
691
+ FieldNumber[FieldNumber["DescriptorProto_Extension"] = 6] = "DescriptorProto_Extension";
692
+ FieldNumber[FieldNumber["DescriptorProto_OneofDecl"] = 8] = "DescriptorProto_OneofDecl";
693
+ FieldNumber[FieldNumber["EnumDescriptorProto_Value"] = 2] = "EnumDescriptorProto_Value";
694
+ FieldNumber[FieldNumber["ServiceDescriptorProto_Method"] = 2] = "ServiceDescriptorProto_Method";
695
+ })(FieldNumber || (FieldNumber = {}));
696
+ /**
697
+ * Return a string that matches the definition of a field in the protobuf
698
+ * source. Does not take custom options into account.
699
+ */
700
+ function declarationString() {
701
+ var _a, _b;
702
+ const parts = [];
703
+ if (this.repeated) {
704
+ parts.push("repeated");
705
+ }
706
+ if (this.optional) {
707
+ parts.push("optional");
708
+ }
709
+ const file = "extendee" in this ? this.file : this.parent.file;
710
+ if (file.syntax == "proto2" &&
711
+ this.proto.label === FieldDescriptorProto_Label.REQUIRED) {
712
+ parts.push("required");
713
+ }
714
+ let type;
715
+ switch (this.kind) {
716
+ case "scalar_field":
717
+ type = ScalarType[this.scalar].toLowerCase();
718
+ break;
719
+ case "enum_field":
720
+ type = this.enum.typeName;
721
+ break;
722
+ case "message_field":
723
+ type = this.message.typeName;
724
+ break;
725
+ case "map_field": {
726
+ const k = ScalarType[this.mapKey].toLowerCase();
727
+ let v;
728
+ switch (this.mapValue.kind) {
729
+ case "scalar":
730
+ v = ScalarType[this.mapValue.scalar].toLowerCase();
731
+ break;
732
+ case "enum":
733
+ v = this.mapValue.enum.typeName;
734
+ break;
735
+ case "message":
736
+ v = this.mapValue.message.typeName;
737
+ break;
738
+ }
739
+ type = `map<${k}, ${v}>`;
740
+ break;
741
+ }
742
+ }
743
+ parts.push(`${type} ${this.name} = ${this.number}`);
744
+ const options = [];
745
+ if (((_a = this.proto.options) === null || _a === void 0 ? void 0 : _a.packed) !== undefined) {
746
+ options.push(`packed = ${this.proto.options.packed.toString()}`);
747
+ }
748
+ let defaultValue = this.proto.defaultValue;
749
+ if (defaultValue !== undefined) {
750
+ if (this.proto.type == FieldDescriptorProto_Type.BYTES ||
751
+ this.proto.type == FieldDescriptorProto_Type.STRING) {
752
+ defaultValue = '"' + defaultValue.replace('"', '\\"') + '"';
753
+ }
754
+ options.push(`default = ${defaultValue}`);
755
+ }
756
+ if (this.jsonName !== undefined) {
757
+ options.push(`json_name = "${this.jsonName}"`);
758
+ }
759
+ if (((_b = this.proto.options) === null || _b === void 0 ? void 0 : _b.deprecated) === true) {
760
+ options.push(`deprecated = true`);
761
+ }
762
+ if (options.length > 0) {
763
+ parts.push("[" + options.join(", ") + "]");
764
+ }
765
+ return parts.join(" ");
766
+ }
767
+ /**
768
+ * Parses a text-encoded default value (proto2) of a scalar or enum field.
769
+ */
770
+ function getDefaultValue() {
771
+ const d = this.proto.defaultValue;
772
+ if (d === undefined) {
773
+ return undefined;
774
+ }
775
+ switch (this.kind) {
776
+ case "enum_field": {
777
+ const enumValue = this.enum.values.find((v) => v.name === d);
778
+ assert(enumValue, `cannot parse ${this.toString()} default value: ${d}`);
779
+ return enumValue.number;
780
+ }
781
+ case "scalar_field":
782
+ switch (this.scalar) {
783
+ case ScalarType.STRING:
784
+ return d;
785
+ case ScalarType.BYTES: {
786
+ const u = unescapeBytesDefaultValue(d);
787
+ if (u === false) {
788
+ throw new Error(`cannot parse ${this.toString()} default value: ${d}`);
789
+ }
790
+ return u;
791
+ }
792
+ case ScalarType.INT64:
793
+ case ScalarType.SFIXED64:
794
+ case ScalarType.SINT64:
795
+ return protoInt64.parse(d);
796
+ case ScalarType.UINT64:
797
+ case ScalarType.FIXED64:
798
+ return protoInt64.uParse(d);
799
+ case ScalarType.DOUBLE:
800
+ case ScalarType.FLOAT:
801
+ switch (d) {
802
+ case "inf":
803
+ return Number.POSITIVE_INFINITY;
804
+ case "-inf":
805
+ return Number.NEGATIVE_INFINITY;
806
+ case "nan":
807
+ return Number.NaN;
808
+ default:
809
+ return parseFloat(d);
810
+ }
811
+ case ScalarType.BOOL:
812
+ return d === "true";
813
+ case ScalarType.INT32:
814
+ case ScalarType.UINT32:
815
+ case ScalarType.SINT32:
816
+ case ScalarType.FIXED32:
817
+ case ScalarType.SFIXED32:
818
+ return parseInt(d, 10);
819
+ }
820
+ break;
821
+ default:
822
+ return undefined;
823
+ }
824
+ }
825
+ /**
826
+ * Parses a text-encoded default value (proto2) of a BYTES field.
827
+ */
828
+ function unescapeBytesDefaultValue(str) {
829
+ const b = [];
830
+ const input = {
831
+ tail: str,
832
+ c: "",
833
+ next() {
834
+ if (this.tail.length == 0) {
835
+ return false;
836
+ }
837
+ this.c = this.tail[0];
838
+ this.tail = this.tail.substring(1);
839
+ return true;
840
+ },
841
+ take(n) {
842
+ if (this.tail.length >= n) {
843
+ const r = this.tail.substring(0, n);
844
+ this.tail = this.tail.substring(n);
845
+ return r;
846
+ }
847
+ return false;
848
+ },
849
+ };
850
+ while (input.next()) {
851
+ switch (input.c) {
852
+ case "\\":
853
+ if (input.next()) {
854
+ switch (input.c) {
855
+ case "\\":
856
+ b.push(input.c.charCodeAt(0));
857
+ break;
858
+ case "b":
859
+ b.push(0x08);
860
+ break;
861
+ case "f":
862
+ b.push(0x0c);
863
+ break;
864
+ case "n":
865
+ b.push(0x0a);
866
+ break;
867
+ case "r":
868
+ b.push(0x0d);
869
+ break;
870
+ case "t":
871
+ b.push(0x09);
872
+ break;
873
+ case "v":
874
+ b.push(0x0b);
875
+ break;
876
+ case "0":
877
+ case "1":
878
+ case "2":
879
+ case "3":
880
+ case "4":
881
+ case "5":
882
+ case "6":
883
+ case "7": {
884
+ const s = input.c;
885
+ const t = input.take(2);
886
+ if (t === false) {
887
+ return false;
888
+ }
889
+ const n = parseInt(s + t, 8);
890
+ if (isNaN(n)) {
891
+ return false;
892
+ }
893
+ b.push(n);
894
+ break;
895
+ }
896
+ case "x": {
897
+ const s = input.c;
898
+ const t = input.take(2);
899
+ if (t === false) {
900
+ return false;
901
+ }
902
+ const n = parseInt(s + t, 16);
903
+ if (isNaN(n)) {
904
+ return false;
905
+ }
906
+ b.push(n);
907
+ break;
908
+ }
909
+ case "u": {
910
+ const s = input.c;
911
+ const t = input.take(4);
912
+ if (t === false) {
913
+ return false;
914
+ }
915
+ const n = parseInt(s + t, 16);
916
+ if (isNaN(n)) {
917
+ return false;
918
+ }
919
+ const chunk = new Uint8Array(4);
920
+ const view = new DataView(chunk.buffer);
921
+ view.setInt32(0, n, true);
922
+ b.push(chunk[0], chunk[1], chunk[2], chunk[3]);
923
+ break;
924
+ }
925
+ case "U": {
926
+ const s = input.c;
927
+ const t = input.take(8);
928
+ if (t === false) {
929
+ return false;
930
+ }
931
+ const tc = protoInt64.uEnc(s + t);
932
+ const chunk = new Uint8Array(8);
933
+ const view = new DataView(chunk.buffer);
934
+ view.setInt32(0, tc.lo, true);
935
+ view.setInt32(4, tc.hi, true);
936
+ b.push(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7]);
937
+ break;
938
+ }
939
+ }
940
+ }
941
+ break;
942
+ default:
943
+ b.push(input.c.charCodeAt(0));
944
+ }
945
+ }
946
+ return new Uint8Array(b);
947
+ }