Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/registry.js

raw
1 // Copyright 2021-2026 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 { ScalarType, } from "./descriptors.js";
15 import { parseTextFormatEnumValue, parseTextFormatScalarValue, } from "./wire/text-format.js";
16 import { nestedTypes } from "./reflect/nested-types.js";
17 import { unsafeIsSetExplicit } from "./reflect/unsafe.js";
18 import { protoCamelCase, safeObjectProperty } from "./reflect/names.js";
19 /**
20 * Create a registry from the given inputs.
21 *
22 * An input can be:
23 * - Any message, enum, service, or extension descriptor, which adds just the
24 * descriptor for this type.
25 * - A file descriptor, which adds all typed defined in this file.
26 * - A registry, which adds all types from the registry.
27 *
28 * For duplicate descriptors (same type name), the one given last wins.
29 */
30 export function createRegistry(...input) {
31 return initBaseRegistry(input);
32 }
33 /**
34 * Create a registry that allows adding and removing descriptors.
35 */
36 export function createMutableRegistry(...input) {
37 const reg = initBaseRegistry(input);
38 return Object.assign(Object.assign({}, reg), { remove(desc) {
39 var _a;
40 if (desc.kind == "extension") {
41 (_a = reg.extendees.get(desc.extendee.typeName)) === null || _a === void 0 ? void 0 : _a.delete(desc.number);
42 }
43 reg.types.delete(desc.typeName);
44 } });
45 }
46 export function createFileRegistry(...args) {
47 const registry = createBaseRegistry();
48 if (!args.length) {
49 return registry;
50 }
51 if ("$typeName" in args[0] &&
52 args[0].$typeName == "google.protobuf.FileDescriptorSet") {
53 for (const file of args[0].file) {
54 addFile(file, registry);
55 }
56 return registry;
57 }
58 if ("$typeName" in args[0]) {
59 const input = args[0];
60 const resolve = args[1];
61 const seen = new Set();
62 function recurseDeps(file) {
63 const deps = [];
64 for (const protoFileName of file.dependency) {
65 if (registry.getFile(protoFileName) != undefined) {
66 continue;
67 }
68 if (seen.has(protoFileName)) {
69 continue;
70 }
71 const dep = resolve(protoFileName);
72 if (!dep) {
73 throw new Error(`Unable to resolve ${protoFileName}, imported by ${file.name}`);
74 }
75 if ("kind" in dep) {
76 registry.addFile(dep, false, true);
77 }
78 else {
79 seen.add(dep.name);
80 deps.push(dep);
81 }
82 }
83 return deps.concat(...deps.map(recurseDeps));
84 }
85 for (const file of [input, ...recurseDeps(input)].reverse()) {
86 addFile(file, registry);
87 }
88 }
89 else {
90 for (const fileReg of args) {
91 for (const file of fileReg.files) {
92 registry.addFile(file);
93 }
94 }
95 }
96 return registry;
97 }
98 /**
99 * @private
100 */
101 function createBaseRegistry() {
102 const types = new Map();
103 const extendees = new Map();
104 const files = new Map();
105 return {
106 kind: "registry",
107 types,
108 extendees,
109 [Symbol.iterator]() {
110 return types.values();
111 },
112 get files() {
113 return files.values();
114 },
115 addFile(file, skipTypes, withDeps) {
116 files.set(file.proto.name, file);
117 if (!skipTypes) {
118 for (const type of nestedTypes(file)) {
119 this.add(type);
120 }
121 }
122 if (withDeps) {
123 for (const f of file.dependencies) {
124 this.addFile(f, skipTypes, withDeps);
125 }
126 }
127 },
128 add(desc) {
129 if (desc.kind == "extension") {
130 let numberToExt = extendees.get(desc.extendee.typeName);
131 if (!numberToExt) {
132 extendees.set(desc.extendee.typeName,
133 // biome-ignore lint/suspicious/noAssignInExpressions: no
134 (numberToExt = new Map()));
135 }
136 numberToExt.set(desc.number, desc);
137 }
138 types.set(desc.typeName, desc);
139 },
140 get(typeName) {
141 return types.get(typeName);
142 },
143 getFile(fileName) {
144 return files.get(fileName);
145 },
146 getMessage(typeName) {
147 const t = types.get(typeName);
148 return (t === null || t === void 0 ? void 0 : t.kind) == "message" ? t : undefined;
149 },
150 getEnum(typeName) {
151 const t = types.get(typeName);
152 return (t === null || t === void 0 ? void 0 : t.kind) == "enum" ? t : undefined;
153 },
154 getExtension(typeName) {
155 const t = types.get(typeName);
156 return (t === null || t === void 0 ? void 0 : t.kind) == "extension" ? t : undefined;
157 },
158 getExtensionFor(extendee, no) {
159 var _a;
160 return (_a = extendees.get(extendee.typeName)) === null || _a === void 0 ? void 0 : _a.get(no);
161 },
162 getService(typeName) {
163 const t = types.get(typeName);
164 return (t === null || t === void 0 ? void 0 : t.kind) == "service" ? t : undefined;
165 },
166 };
167 }
168 /**
169 * @private
170 */
171 function initBaseRegistry(inputs) {
172 const registry = createBaseRegistry();
173 for (const input of inputs) {
174 switch (input.kind) {
175 case "registry":
176 for (const n of input) {
177 registry.add(n);
178 }
179 break;
180 case "file":
181 registry.addFile(input);
182 break;
183 default:
184 registry.add(input);
185 break;
186 }
187 }
188 return registry;
189 }
190 // bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name = $number;
191 const EDITION_PROTO2 = 998;
192 // bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name = $number;
193 const EDITION_PROTO3 = 999;
194 // bootstrap-inject google.protobuf.Edition.EDITION_UNSTABLE: const $name = $number;
195 const EDITION_UNSTABLE = 9999;
196 // bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_STRING: const $name = $number;
197 const TYPE_STRING = 9;
198 // bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_GROUP: const $name = $number;
199 const TYPE_GROUP = 10;
200 // bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE: const $name = $number;
201 const TYPE_MESSAGE = 11;
202 // bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_BYTES: const $name = $number;
203 const TYPE_BYTES = 12;
204 // bootstrap-inject google.protobuf.FieldDescriptorProto.Type.TYPE_ENUM: const $name = $number;
205 const TYPE_ENUM = 14;
206 // bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED: const $name = $number;
207 const LABEL_REPEATED = 3;
208 // bootstrap-inject google.protobuf.FieldDescriptorProto.Label.LABEL_REQUIRED: const $name = $number;
209 const LABEL_REQUIRED = 2;
210 // bootstrap-inject google.protobuf.FieldOptions.JSType.JS_STRING: const $name = $number;
211 const JS_STRING = 1;
212 // bootstrap-inject google.protobuf.MethodOptions.IdempotencyLevel.IDEMPOTENCY_UNKNOWN: const $name = $number;
213 const IDEMPOTENCY_UNKNOWN = 0;
214 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.EXPLICIT: const $name = $number;
215 const EXPLICIT = 1;
216 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name = $number;
217 const IMPLICIT = 2;
218 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name = $number;
219 const LEGACY_REQUIRED = 3;
220 // bootstrap-inject google.protobuf.FeatureSet.RepeatedFieldEncoding.PACKED: const $name = $number;
221 const PACKED = 1;
222 // bootstrap-inject google.protobuf.FeatureSet.MessageEncoding.DELIMITED: const $name = $number;
223 const DELIMITED = 2;
224 // bootstrap-inject google.protobuf.FeatureSet.EnumType.OPEN: const $name = $number;
225 const OPEN = 1;
226 // bootstrap-inject google.protobuf.FeatureSet.Utf8Validation.VERIFY: const $name = $number;
227 const VERIFY = 2;
228 // biome-ignore format: want this to read well
229 // bootstrap-inject defaults: EDITION_PROTO2 to EDITION_2024: export const minimumEdition: SupportedEdition = $minimumEdition, maximumEdition: SupportedEdition = $maximumEdition;
230 // generated from protoc v34.1
231 export const minimumEdition = 998, maximumEdition = 1001;
232 const featureDefaults = {
233 // EDITION_PROTO2
234 998: {
235 fieldPresence: 1, // EXPLICIT,
236 enumType: 2, // CLOSED,
237 repeatedFieldEncoding: 2, // EXPANDED,
238 utf8Validation: 3, // NONE,
239 messageEncoding: 1, // LENGTH_PREFIXED,
240 jsonFormat: 2, // LEGACY_BEST_EFFORT,
241 enforceNamingStyle: 2, // STYLE_LEGACY,
242 defaultSymbolVisibility: 1, // EXPORT_ALL,
243 },
244 // EDITION_PROTO3
245 999: {
246 fieldPresence: 2, // IMPLICIT,
247 enumType: 1, // OPEN,
248 repeatedFieldEncoding: 1, // PACKED,
249 utf8Validation: 2, // VERIFY,
250 messageEncoding: 1, // LENGTH_PREFIXED,
251 jsonFormat: 1, // ALLOW,
252 enforceNamingStyle: 2, // STYLE_LEGACY,
253 defaultSymbolVisibility: 1, // EXPORT_ALL,
254 },
255 // EDITION_2023
256 1000: {
257 fieldPresence: 1, // EXPLICIT,
258 enumType: 1, // OPEN,
259 repeatedFieldEncoding: 1, // PACKED,
260 utf8Validation: 2, // VERIFY,
261 messageEncoding: 1, // LENGTH_PREFIXED,
262 jsonFormat: 1, // ALLOW,
263 enforceNamingStyle: 2, // STYLE_LEGACY,
264 defaultSymbolVisibility: 1, // EXPORT_ALL,
265 },
266 // EDITION_2024
267 1001: {
268 fieldPresence: 1, // EXPLICIT,
269 enumType: 1, // OPEN,
270 repeatedFieldEncoding: 1, // PACKED,
271 utf8Validation: 2, // VERIFY,
272 messageEncoding: 1, // LENGTH_PREFIXED,
273 jsonFormat: 1, // ALLOW,
274 enforceNamingStyle: 1, // STYLE2024,
275 defaultSymbolVisibility: 2, // EXPORT_TOP_LEVEL,
276 },
277 };
278 /**
279 * Create a descriptor for a file, add it to the registry.
280 */
281 function addFile(proto, reg) {
282 var _a, _b;
283 const file = {
284 kind: "file",
285 proto,
286 deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
287 edition: getFileEdition(proto),
288 name: proto.name.replace(/\.proto$/, ""),
289 dependencies: findFileDependencies(proto, reg),
290 enums: [],
291 messages: [],
292 extensions: [],
293 services: [],
294 toString() {
295 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- we asserted above
296 return `file ${proto.name}`;
297 },
298 };
299 const mapEntriesStore = new Map();
300 const mapEntries = {
301 get(typeName) {
302 return mapEntriesStore.get(typeName);
303 },
304 add(desc) {
305 var _a;
306 assert(((_a = desc.proto.options) === null || _a === void 0 ? void 0 : _a.mapEntry) === true);
307 mapEntriesStore.set(desc.typeName, desc);
308 },
309 };
310 for (const enumProto of proto.enumType) {
311 addEnum(enumProto, file, undefined, reg);
312 }
313 for (const messageProto of proto.messageType) {
314 addMessage(messageProto, file, undefined, reg, mapEntries);
315 }
316 for (const serviceProto of proto.service) {
317 addService(serviceProto, file, reg);
318 }
319 addExtensions(file, reg);
320 for (const mapEntry of mapEntriesStore.values()) {
321 // to create a map field, we need access to the map entry's fields
322 addFields(mapEntry, reg, mapEntries);
323 }
324 for (const message of file.messages) {
325 addFields(message, reg, mapEntries);
326 addExtensions(message, reg);
327 }
328 reg.addFile(file, true);
329 }
330 /**
331 * Create descriptors for extensions, and add them to the message / file,
332 * and to our cart.
333 * Recurses into nested types.
334 */
335 function addExtensions(desc, reg) {
336 switch (desc.kind) {
337 case "file":
338 for (const proto of desc.proto.extension) {
339 const ext = newField(proto, desc, reg);
340 desc.extensions.push(ext);
341 reg.add(ext);
342 }
343 break;
344 case "message":
345 for (const proto of desc.proto.extension) {
346 const ext = newField(proto, desc, reg);
347 desc.nestedExtensions.push(ext);
348 reg.add(ext);
349 }
350 for (const message of desc.nestedMessages) {
351 addExtensions(message, reg);
352 }
353 break;
354 }
355 }
356 /**
357 * Create descriptors for fields and oneof groups, and add them to the message.
358 * Recurses into nested types.
359 */
360 function addFields(message, reg, mapEntries) {
361 const allOneofs = message.proto.oneofDecl.map((proto) => newOneof(proto, message));
362 const oneofsSeen = new Set();
363 for (const proto of message.proto.field) {
364 const oneof = findOneof(proto, allOneofs);
365 const field = newField(proto, message, reg, oneof, mapEntries);
366 message.fields.push(field);
367 message.field[field.localName] = field;
368 if (oneof === undefined) {
369 message.members.push(field);
370 }
371 else {
372 oneof.fields.push(field);
373 if (!oneofsSeen.has(oneof)) {
374 oneofsSeen.add(oneof);
375 message.members.push(oneof);
376 }
377 }
378 }
379 for (const oneof of allOneofs.filter((o) => oneofsSeen.has(o))) {
380 message.oneofs.push(oneof);
381 }
382 for (const child of message.nestedMessages) {
383 addFields(child, reg, mapEntries);
384 }
385 }
386 /**
387 * Create a descriptor for an enumeration, and add it our cart and to the
388 * parent type, if any.
389 */
390 function addEnum(proto, file, parent, reg) {
391 var _a, _b, _c, _d, _e;
392 const sharedPrefix = findEnumSharedPrefix(proto.name, proto.value);
393 const desc = {
394 kind: "enum",
395 proto,
396 deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
397 file,
398 parent,
399 open: true,
400 name: proto.name,
401 typeName: makeTypeName(proto, parent, file),
402 value: {},
403 values: [],
404 sharedPrefix,
405 toString() {
406 return `enum ${this.typeName}`;
407 },
408 };
409 desc.open = isEnumOpen(desc);
410 reg.add(desc);
411 for (const p of proto.value) {
412 const name = p.name;
413 desc.values.push(
414 // biome-ignore lint/suspicious/noAssignInExpressions: no
415 (desc.value[p.number] = {
416 kind: "enum_value",
417 proto: p,
418 deprecated: (_d = (_c = p.options) === null || _c === void 0 ? void 0 : _c.deprecated) !== null && _d !== void 0 ? _d : false,
419 parent: desc,
420 name,
421 localName: safeObjectProperty(sharedPrefix == undefined
422 ? name
423 : name.substring(sharedPrefix.length)),
424 number: p.number,
425 toString() {
426 return `enum value ${desc.typeName}.${name}`;
427 },
428 }));
429 }
430 ((_e = parent === null || parent === void 0 ? void 0 : parent.nestedEnums) !== null && _e !== void 0 ? _e : file.enums).push(desc);
431 }
432 /**
433 * Create a descriptor for a message, including nested types, and add it to our
434 * cart. Note that this does not create descriptors fields.
435 */
436 function addMessage(proto, file, parent, reg, mapEntries) {
437 var _a, _b, _c, _d;
438 const desc = {
439 kind: "message",
440 proto,
441 deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
442 file,
443 parent,
444 name: proto.name,
445 typeName: makeTypeName(proto, parent, file),
446 fields: [],
447 field: {},
448 oneofs: [],
449 members: [],
450 nestedEnums: [],
451 nestedMessages: [],
452 nestedExtensions: [],
453 toString() {
454 return `message ${this.typeName}`;
455 },
456 };
457 if (((_c = proto.options) === null || _c === void 0 ? void 0 : _c.mapEntry) === true) {
458 mapEntries.add(desc);
459 }
460 else {
461 ((_d = parent === null || parent === void 0 ? void 0 : parent.nestedMessages) !== null && _d !== void 0 ? _d : file.messages).push(desc);
462 reg.add(desc);
463 }
464 for (const enumProto of proto.enumType) {
465 addEnum(enumProto, file, desc, reg);
466 }
467 for (const messageProto of proto.nestedType) {
468 addMessage(messageProto, file, desc, reg, mapEntries);
469 }
470 }
471 /**
472 * Create a descriptor for a service, including methods, and add it to our
473 * cart.
474 */
475 function addService(proto, file, reg) {
476 var _a, _b;
477 const desc = {
478 kind: "service",
479 proto,
480 deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
481 file,
482 name: proto.name,
483 typeName: makeTypeName(proto, undefined, file),
484 methods: [],
485 method: {},
486 toString() {
487 return `service ${this.typeName}`;
488 },
489 };
490 file.services.push(desc);
491 reg.add(desc);
492 for (const methodProto of proto.method) {
493 const method = newMethod(methodProto, desc, reg);
494 desc.methods.push(method);
495 desc.method[method.localName] = method;
496 }
497 }
498 /**
499 * Create a descriptor for a method.
500 */
501 function newMethod(proto, parent, reg) {
502 var _a, _b, _c, _d;
503 let methodKind;
504 if (proto.clientStreaming && proto.serverStreaming) {
505 methodKind = "bidi_streaming";
506 }
507 else if (proto.clientStreaming) {
508 methodKind = "client_streaming";
509 }
510 else if (proto.serverStreaming) {
511 methodKind = "server_streaming";
512 }
513 else {
514 methodKind = "unary";
515 }
516 const input = reg.getMessage(trimLeadingDot(proto.inputType));
517 const output = reg.getMessage(trimLeadingDot(proto.outputType));
518 assert(input, `invalid MethodDescriptorProto: input_type ${proto.inputType} not found`);
519 assert(output, `invalid MethodDescriptorProto: output_type ${proto.inputType} not found`);
520 const name = proto.name;
521 return {
522 kind: "rpc",
523 proto,
524 deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
525 parent,
526 name,
527 localName: safeObjectProperty(name.length
528 ? safeObjectProperty(name[0].toLowerCase() + name.substring(1))
529 : name),
530 methodKind,
531 input,
532 output,
533 idempotency: (_d = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.idempotencyLevel) !== null && _d !== void 0 ? _d : IDEMPOTENCY_UNKNOWN,
534 toString() {
535 return `rpc ${parent.typeName}.${name}`;
536 },
537 };
538 }
539 /**
540 * Create a descriptor for a oneof group.
541 */
542 function newOneof(proto, parent) {
543 return {
544 kind: "oneof",
545 proto,
546 deprecated: false,
547 parent,
548 fields: [],
549 name: proto.name,
550 localName: safeObjectProperty(protoCamelCase(proto.name)),
551 toString() {
552 return `oneof ${parent.typeName}.${this.name}`;
553 },
554 };
555 }
556 function newField(proto, parentOrFile, reg, oneof, mapEntries) {
557 var _a, _b, _c;
558 const isExtension = mapEntries === undefined;
559 const field = {
560 kind: "field",
561 proto,
562 deprecated: (_b = (_a = proto.options) === null || _a === void 0 ? void 0 : _a.deprecated) !== null && _b !== void 0 ? _b : false,
563 name: proto.name,
564 number: proto.number,
565 scalar: undefined,
566 message: undefined,
567 enum: undefined,
568 presence: getFieldPresence(proto, oneof, isExtension, parentOrFile),
569 utf8Validation: isUtf8Validated(proto, parentOrFile),
570 listKind: undefined,
571 mapKind: undefined,
572 mapKey: undefined,
573 delimitedEncoding: undefined,
574 packed: undefined,
575 longAsString: false,
576 getDefaultValue: undefined,
577 };
578 let toStr;
579 if (isExtension) {
580 // extension field
581 const file = parentOrFile.kind == "file" ? parentOrFile : parentOrFile.file;
582 const parent = parentOrFile.kind == "file" ? undefined : parentOrFile;
583 const typeName = makeTypeName(proto, parent, file);
584 field.kind = "extension";
585 field.file = file;
586 field.parent = parent;
587 field.oneof = undefined;
588 field.typeName = typeName;
589 field.jsonName = `[${typeName}]`; // option json_name is not allowed on extension fields
590 toStr = () => `extension ${typeName}`;
591 const extendee = reg.getMessage(trimLeadingDot(proto.extendee));
592 assert(extendee, `invalid FieldDescriptorProto: extendee ${proto.extendee} not found`);
593 field.extendee = extendee;
594 }
595 else {
596 // regular field
597 const parent = parentOrFile;
598 assert(parent.kind == "message");
599 field.parent = parent;
600 field.oneof = oneof;
601 field.localName = oneof
602 ? protoCamelCase(proto.name)
603 : safeObjectProperty(protoCamelCase(proto.name));
604 field.jsonName = proto.jsonName;
605 toStr = () => `field ${parent.typeName}.${proto.name}`;
606 }
607 // A plain assignment throws where built-in prototypes are frozen. The
608 // attributes match what an assignment produces.
609 Object.defineProperty(field, "toString", {
610 value: toStr,
611 writable: true,
612 enumerable: true,
613 configurable: true,
614 });
615 const label = proto.label;
616 const type = proto.type;
617 const jstype = (_c = proto.options) === null || _c === void 0 ? void 0 : _c.jstype;
618 if (label === LABEL_REPEATED) {
619 // list or map field
620 const mapEntry = type == TYPE_MESSAGE
621 ? mapEntries === null || mapEntries === void 0 ? void 0 : mapEntries.get(trimLeadingDot(proto.typeName))
622 : undefined;
623 if (mapEntry) {
624 // map field
625 field.fieldKind = "map";
626 const { key, value } = findMapEntryFields(mapEntry);
627 field.mapKey = key.scalar;
628 field.mapKind = value.fieldKind;
629 field.message = value.message;
630 field.delimitedEncoding = false; // map fields are always LENGTH_PREFIXED
631 field.enum = value.enum;
632 field.scalar = value.scalar;
633 return field;
634 }
635 // list field
636 field.fieldKind = "list";
637 switch (type) {
638 case TYPE_MESSAGE:
639 case TYPE_GROUP:
640 field.listKind = "message";
641 field.message = reg.getMessage(trimLeadingDot(proto.typeName));
642 assert(field.message);
643 field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);
644 break;
645 case TYPE_ENUM:
646 field.listKind = "enum";
647 field.enum = reg.getEnum(trimLeadingDot(proto.typeName));
648 assert(field.enum);
649 break;
650 default:
651 field.listKind = "scalar";
652 field.scalar = type;
653 field.longAsString = jstype == JS_STRING;
654 break;
655 }
656 field.packed = isPackedField(proto, parentOrFile);
657 return field;
658 }
659 // singular
660 switch (type) {
661 case TYPE_MESSAGE:
662 case TYPE_GROUP:
663 field.fieldKind = "message";
664 field.message = reg.getMessage(trimLeadingDot(proto.typeName));
665 assert(field.message, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
666 field.delimitedEncoding = isDelimitedEncoding(proto, parentOrFile);
667 field.getDefaultValue = () => undefined;
668 break;
669 case TYPE_ENUM: {
670 const enumeration = reg.getEnum(trimLeadingDot(proto.typeName));
671 assert(enumeration !== undefined, `invalid FieldDescriptorProto: type_name ${proto.typeName} not found`);
672 field.fieldKind = "enum";
673 field.enum = reg.getEnum(trimLeadingDot(proto.typeName));
674 field.getDefaultValue = () => {
675 return unsafeIsSetExplicit(proto, "defaultValue")
676 ? parseTextFormatEnumValue(enumeration, proto.defaultValue)
677 : undefined;
678 };
679 break;
680 }
681 default: {
682 field.fieldKind = "scalar";
683 field.scalar = type;
684 field.longAsString = jstype == JS_STRING;
685 field.getDefaultValue = () => {
686 return unsafeIsSetExplicit(proto, "defaultValue")
687 ? parseTextFormatScalarValue(type, proto.defaultValue)
688 : undefined;
689 };
690 break;
691 }
692 }
693 return field;
694 }
695 /**
696 * Parse the "syntax" and "edition" fields, returning one of the supported
697 * editions.
698 */
699 function getFileEdition(proto) {
700 switch (proto.syntax) {
701 case "":
702 case "proto2":
703 return EDITION_PROTO2;
704 case "proto3":
705 return EDITION_PROTO3;
706 case "editions":
707 // EDITION_UNSTABLE is a sandbox for in-development features. Collapse
708 // it to maximumEdition so SupportedEdition and feature resolution do
709 // not leak the test-only edition to users.
710 if (proto.edition === EDITION_UNSTABLE) {
711 return maximumEdition;
712 }
713 if (proto.edition in featureDefaults) {
714 return proto.edition;
715 }
716 throw new Error(`${proto.name}: unsupported edition`);
717 default:
718 throw new Error(`${proto.name}: unsupported syntax "${proto.syntax}"`);
719 }
720 }
721 /**
722 * Resolve dependencies of FileDescriptorProto to DescFile.
723 */
724 function findFileDependencies(proto, reg) {
725 return proto.dependency.map((wantName) => {
726 const dep = reg.getFile(wantName);
727 if (!dep) {
728 throw new Error(`Cannot find ${wantName}, imported by ${proto.name}`);
729 }
730 return dep;
731 });
732 }
733 /**
734 * Finds a prefix shared by enum values, for example `my_enum_` for
735 * `enum MyEnum {MY_ENUM_A=0; MY_ENUM_B=1;}`.
736 */
737 function findEnumSharedPrefix(enumName, values) {
738 const prefix = camelToSnakeCase(enumName) + "_";
739 for (const value of values) {
740 if (!value.name.toLowerCase().startsWith(prefix)) {
741 return undefined;
742 }
743 const shortName = value.name.substring(prefix.length);
744 if (shortName.length == 0) {
745 return undefined;
746 }
747 if (/^\d/.test(shortName)) {
748 // identifiers must not start with numbers
749 return undefined;
750 }
751 }
752 return prefix;
753 }
754 /**
755 * Converts lowerCamelCase or UpperCamelCase into lower_snake_case.
756 * This is used to find shared prefixes in an enum.
757 */
758 function camelToSnakeCase(camel) {
759 return (camel.substring(0, 1) + camel.substring(1).replace(/[A-Z]/g, (c) => "_" + c)).toLowerCase();
760 }
761 /**
762 * Create a fully qualified name for a protobuf type or extension field.
763 *
764 * The fully qualified name for messages, enumerations, and services is
765 * constructed by concatenating the package name (if present), parent
766 * message names (for nested types), and the type name. We omit the leading
767 * dot added by protobuf compilers. Examples:
768 * - mypackage.MyMessage
769 * - mypackage.MyMessage.NestedMessage
770 *
771 * The fully qualified name for extension fields is constructed by
772 * concatenating the package name (if present), parent message names (for
773 * extensions declared within a message), and the field name. Examples:
774 * - mypackage.extfield
775 * - mypackage.MyMessage.extfield
776 */
777 function makeTypeName(proto, parent, file) {
778 let typeName;
779 if (parent) {
780 typeName = `${parent.typeName}.${proto.name}`;
781 }
782 else if (file.proto.package.length > 0) {
783 typeName = `${file.proto.package}.${proto.name}`;
784 }
785 else {
786 typeName = `${proto.name}`;
787 }
788 return typeName;
789 }
790 /**
791 * Remove the leading dot from a fully qualified type name.
792 */
793 function trimLeadingDot(typeName) {
794 return typeName.startsWith(".") ? typeName.substring(1) : typeName;
795 }
796 /**
797 * Did the user put the field in a oneof group?
798 * Synthetic oneofs for proto3 optionals are ignored.
799 */
800 function findOneof(proto, allOneofs) {
801 if (!unsafeIsSetExplicit(proto, "oneofIndex")) {
802 return undefined;
803 }
804 if (proto.proto3Optional) {
805 return undefined;
806 }
807 const oneof = allOneofs[proto.oneofIndex];
808 assert(oneof, `invalid FieldDescriptorProto: oneof #${proto.oneofIndex} for field #${proto.number} not found`);
809 return oneof;
810 }
811 /**
812 * Presence of the field.
813 * See https://protobuf.dev/programming-guides/field_presence/
814 */
815 function getFieldPresence(proto, oneof, isExtension, parent) {
816 if (proto.label == LABEL_REQUIRED) {
817 // proto2 required is LEGACY_REQUIRED
818 return LEGACY_REQUIRED;
819 }
820 if (proto.label == LABEL_REPEATED) {
821 // repeated fields (including maps) do not track presence
822 return IMPLICIT;
823 }
824 if (!!oneof || proto.proto3Optional) {
825 // oneof is always explicit
826 return EXPLICIT;
827 }
828 if (isExtension) {
829 // extensions always track presence
830 return EXPLICIT;
831 }
832 const resolved = resolveFeature("fieldPresence", { proto, parent });
833 if (resolved == IMPLICIT &&
834 (proto.type == TYPE_MESSAGE || proto.type == TYPE_GROUP)) {
835 // singular message field cannot be implicit
836 return EXPLICIT;
837 }
838 return resolved;
839 }
840 /**
841 * Pack this repeated field?
842 */
843 function isPackedField(proto, parent) {
844 if (proto.label != LABEL_REPEATED) {
845 return false;
846 }
847 switch (proto.type) {
848 case TYPE_STRING:
849 case TYPE_BYTES:
850 case TYPE_GROUP:
851 case TYPE_MESSAGE:
852 // length-delimited types cannot be packed
853 return false;
854 }
855 const o = proto.options;
856 if (o && unsafeIsSetExplicit(o, "packed")) {
857 // prefer the field option over edition features
858 return o.packed;
859 }
860 return (PACKED ==
861 resolveFeature("repeatedFieldEncoding", {
862 proto,
863 parent,
864 }));
865 }
866 /**
867 * Find the key and value fields of a synthetic map entry message.
868 */
869 function findMapEntryFields(mapEntry) {
870 const key = mapEntry.fields.find((f) => f.number === 1);
871 const value = mapEntry.fields.find((f) => f.number === 2);
872 assert(key &&
873 key.fieldKind == "scalar" &&
874 key.scalar != ScalarType.BYTES &&
875 key.scalar != ScalarType.FLOAT &&
876 key.scalar != ScalarType.DOUBLE &&
877 value &&
878 value.fieldKind != "list" &&
879 value.fieldKind != "map");
880 return { key, value };
881 }
882 /**
883 * Enumerations can be open or closed.
884 * See https://protobuf.dev/programming-guides/enum/
885 */
886 function isEnumOpen(desc) {
887 var _a;
888 return (OPEN ==
889 resolveFeature("enumType", {
890 proto: desc.proto,
891 parent: (_a = desc.parent) !== null && _a !== void 0 ? _a : desc.file,
892 }));
893 }
894 /**
895 * Encode the message delimited (a.k.a. proto2 group encoding), or
896 * length-prefixed?
897 */
898 function isDelimitedEncoding(proto, parent) {
899 if (proto.type == TYPE_GROUP) {
900 return true;
901 }
902 return (DELIMITED ==
903 resolveFeature("messageEncoding", {
904 proto,
905 parent,
906 }));
907 }
908 /**
909 * Reject invalid UTF-8 when reading string fields from the binary wire format?
910 * Driven by the resolved `utf8_validation` feature: VERIFY (proto3 / editions
911 * 2023+ default) enforces; NONE (proto2 default) does not.
912 */
913 function isUtf8Validated(proto, parent) {
914 return (VERIFY ==
915 resolveFeature("utf8Validation", {
916 proto,
917 parent,
918 }));
919 }
920 function resolveFeature(name, ref) {
921 var _a, _b;
922 const featureSet = (_a = ref.proto.options) === null || _a === void 0 ? void 0 : _a.features;
923 if (featureSet) {
924 const val = featureSet[name];
925 if (val != 0) {
926 return val;
927 }
928 }
929 if ("kind" in ref) {
930 if (ref.kind == "message") {
931 return resolveFeature(name, (_b = ref.parent) !== null && _b !== void 0 ? _b : ref.file);
932 }
933 const editionDefaults = featureDefaults[ref.edition];
934 if (!editionDefaults) {
935 throw new Error(`feature default for edition ${ref.edition} not found`);
936 }
937 return editionDefaults[name];
938 }
939 return resolveFeature(name, ref.parent);
940 }
941 /**
942 * Assert that condition is truthy or throw error (with message)
943 */
944 function assert(condition, msg) {
945 if (!condition) {
946 throw new Error(msg);
947 }
948 }