-
Notifications
You must be signed in to change notification settings - Fork 349
/
types.ts
920 lines (841 loc) · 34.6 KB
/
types.ts
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
import { Code, Import, code, imp } from "ts-poet";
import {
CodeGeneratorRequest,
DescriptorProto,
EnumDescriptorProto,
FieldDescriptorProto,
FieldDescriptorProto_Label,
FieldDescriptorProto_Type,
FieldOptions_JSType,
FileDescriptorProto,
MessageOptions,
MethodDescriptorProto,
ServiceDescriptorProto,
} from "ts-proto-descriptors";
import { uncapitalize } from "./case";
import { Context } from "./context";
import { getMemberName as getEnumMemberName } from "./enums";
import { DateOption, EnvOption, LongOption, OneofOption, Options } from "./options";
import SourceInfo from "./sourceInfo";
import {
FormattedMethodDescriptor,
fail,
impProto,
maybePrefixPackage,
nullOrUndefined,
withAndMaybeCheckIsNotNull,
} from "./utils";
import { visit } from "./visit";
/** Based on https://github.com/dcodeIO/protobuf.js/blob/master/src/types.js#L37. */
export function basicWireType(type: FieldDescriptorProto_Type): number {
switch (type) {
case FieldDescriptorProto_Type.TYPE_DOUBLE:
return 1;
case FieldDescriptorProto_Type.TYPE_FLOAT:
return 5;
case FieldDescriptorProto_Type.TYPE_INT32:
case FieldDescriptorProto_Type.TYPE_ENUM:
case FieldDescriptorProto_Type.TYPE_UINT32:
case FieldDescriptorProto_Type.TYPE_SINT32:
return 0;
case FieldDescriptorProto_Type.TYPE_FIXED32:
case FieldDescriptorProto_Type.TYPE_SFIXED32:
return 5;
case FieldDescriptorProto_Type.TYPE_INT64:
case FieldDescriptorProto_Type.TYPE_UINT64:
case FieldDescriptorProto_Type.TYPE_SINT64:
return 0;
case FieldDescriptorProto_Type.TYPE_FIXED64:
case FieldDescriptorProto_Type.TYPE_SFIXED64:
return 1;
case FieldDescriptorProto_Type.TYPE_BOOL:
return 0;
case FieldDescriptorProto_Type.TYPE_STRING:
case FieldDescriptorProto_Type.TYPE_BYTES:
case FieldDescriptorProto_Type.TYPE_MESSAGE:
return 2;
case FieldDescriptorProto_Type.TYPE_GROUP:
return 3;
default:
throw new Error("Invalid type " + type);
}
}
export function basicLongWireType(type: FieldDescriptorProto_Type): number | undefined {
switch (type) {
case FieldDescriptorProto_Type.TYPE_INT64:
case FieldDescriptorProto_Type.TYPE_UINT64:
case FieldDescriptorProto_Type.TYPE_SINT64:
return 0;
case FieldDescriptorProto_Type.TYPE_FIXED64:
case FieldDescriptorProto_Type.TYPE_SFIXED64:
return 1;
default:
return undefined;
}
}
/** Returns the type name without any repeated/required/etc. labels. */
export function basicTypeName(
ctx: Context,
field: FieldDescriptorProto,
typeOptions: { keepValueType?: boolean } = {},
): Code {
const { options } = ctx;
const fieldType = getFieldOptionsJsType(field, ctx.options) ?? field.type;
switch (fieldType) {
case FieldDescriptorProto_Type.TYPE_DOUBLE:
case FieldDescriptorProto_Type.TYPE_FLOAT:
case FieldDescriptorProto_Type.TYPE_INT32:
case FieldDescriptorProto_Type.TYPE_UINT32:
case FieldDescriptorProto_Type.TYPE_SINT32:
case FieldDescriptorProto_Type.TYPE_FIXED32:
case FieldDescriptorProto_Type.TYPE_SFIXED32:
return code`number`;
case FieldDescriptorProto_Type.TYPE_INT64:
case FieldDescriptorProto_Type.TYPE_UINT64:
case FieldDescriptorProto_Type.TYPE_SINT64:
case FieldDescriptorProto_Type.TYPE_FIXED64:
case FieldDescriptorProto_Type.TYPE_SFIXED64:
return isJsTypeFieldOption(options, field)
? jsTypeName(field) ?? longTypeName(ctx)
: // this handles 2^53, Long is only needed for 2^64; this is effectively pbjs's forceNumber
longTypeName(ctx);
case FieldDescriptorProto_Type.TYPE_BOOL:
return code`boolean`;
case FieldDescriptorProto_Type.TYPE_STRING:
return code`string`;
case FieldDescriptorProto_Type.TYPE_BYTES:
if (options.env === EnvOption.NODE) {
return code`Buffer`;
} else {
return code`Uint8Array`;
}
case FieldDescriptorProto_Type.TYPE_MESSAGE:
case FieldDescriptorProto_Type.TYPE_GROUP:
case FieldDescriptorProto_Type.TYPE_ENUM:
return messageToTypeName(ctx, field.typeName, { ...typeOptions, repeated: isRepeated(field) });
default:
return code`${field.typeName}`;
}
}
/** Returns the Reader method for the primitive's read/write call. */
export function toReaderCall(field: FieldDescriptorProto): string {
switch (field.type) {
case FieldDescriptorProto_Type.TYPE_DOUBLE:
return "double";
case FieldDescriptorProto_Type.TYPE_FLOAT:
return "float";
case FieldDescriptorProto_Type.TYPE_INT32:
case FieldDescriptorProto_Type.TYPE_ENUM:
return "int32";
case FieldDescriptorProto_Type.TYPE_UINT32:
return "uint32";
case FieldDescriptorProto_Type.TYPE_SINT32:
return "sint32";
case FieldDescriptorProto_Type.TYPE_FIXED32:
return "fixed32";
case FieldDescriptorProto_Type.TYPE_SFIXED32:
return "sfixed32";
case FieldDescriptorProto_Type.TYPE_INT64:
return "int64";
case FieldDescriptorProto_Type.TYPE_UINT64:
return "uint64";
case FieldDescriptorProto_Type.TYPE_SINT64:
return "sint64";
case FieldDescriptorProto_Type.TYPE_FIXED64:
return "fixed64";
case FieldDescriptorProto_Type.TYPE_SFIXED64:
return "sfixed64";
case FieldDescriptorProto_Type.TYPE_BOOL:
return "bool";
case FieldDescriptorProto_Type.TYPE_STRING:
return "string";
case FieldDescriptorProto_Type.TYPE_BYTES:
return "bytes";
default:
throw new Error(`Not a primitive field ${field}`);
}
}
export function packedType(type: FieldDescriptorProto_Type): number | undefined {
switch (type) {
case FieldDescriptorProto_Type.TYPE_DOUBLE:
return 1;
case FieldDescriptorProto_Type.TYPE_FLOAT:
return 5;
case FieldDescriptorProto_Type.TYPE_INT32:
case FieldDescriptorProto_Type.TYPE_ENUM:
case FieldDescriptorProto_Type.TYPE_UINT32:
case FieldDescriptorProto_Type.TYPE_SINT32:
return 0;
case FieldDescriptorProto_Type.TYPE_FIXED32:
case FieldDescriptorProto_Type.TYPE_SFIXED32:
return 5;
case FieldDescriptorProto_Type.TYPE_INT64:
case FieldDescriptorProto_Type.TYPE_UINT64:
case FieldDescriptorProto_Type.TYPE_SINT64:
return 0;
case FieldDescriptorProto_Type.TYPE_FIXED64:
case FieldDescriptorProto_Type.TYPE_SFIXED64:
return 1;
case FieldDescriptorProto_Type.TYPE_BOOL:
return 0;
default:
return undefined;
}
}
export function getFieldOptionsJsType(
field: FieldDescriptorProto,
options: Options,
): FieldDescriptorProto_Type | undefined {
if (!options.useJsTypeOverride || field.options?.jstype === undefined) {
return;
}
switch (field.options.jstype) {
case FieldOptions_JSType.JS_STRING:
return FieldDescriptorProto_Type.TYPE_STRING;
case FieldOptions_JSType.JS_NUMBER:
return FieldDescriptorProto_Type.TYPE_INT64;
// In the case of JS_NORMAL, we don't want to override the type, so we return
case FieldOptions_JSType.JS_NORMAL:
// In the case of UNRECOGNIZED, we assume default behavior and we don't want to override the type, so we return
case FieldOptions_JSType.UNRECOGNIZED:
return;
}
}
export function defaultValue(ctx: Context, field: FieldDescriptorProto): any {
const { typeMap, options, utils, currentFile } = ctx;
if (options.noDefaultsForOptionals) {
return options.useNullAsOptional ? null : undefined;
}
const useDefaultValue = !currentFile.isProto3Syntax && !options.disableProto2DefaultValues && field.defaultValue;
const numericDefaultVal = useDefaultValue ? field.defaultValue : 0;
switch (field.type) {
case FieldDescriptorProto_Type.TYPE_DOUBLE:
case FieldDescriptorProto_Type.TYPE_FLOAT:
case FieldDescriptorProto_Type.TYPE_INT32:
case FieldDescriptorProto_Type.TYPE_UINT32:
case FieldDescriptorProto_Type.TYPE_SINT32:
case FieldDescriptorProto_Type.TYPE_FIXED32:
case FieldDescriptorProto_Type.TYPE_SFIXED32:
return numericDefaultVal;
case FieldDescriptorProto_Type.TYPE_ENUM:
// proto3 enforces enums starting at 0, however proto2 does not, so we have
// to probe and see if zero is an allowed value. If it's not, pick the first one.
// This is probably not great, but it's only used in fromJSON and fromPartial,
// and I believe the semantics of those in the proto2 world are generally undefined.
const typeInfo = typeMap.get(field.typeName)!;
const enumProto = typeInfo[2] as EnumDescriptorProto;
const defaultEnum =
enumProto.value.find((v) => (useDefaultValue ? v.name === field.defaultValue : v.number === 0)) ||
enumProto.value[0];
if (options.stringEnums) {
const enumType = messageToTypeName(ctx, field.typeName);
return code`${enumType}.${getEnumMemberName(ctx, enumProto, defaultEnum)}`;
} else {
return defaultEnum.number;
}
case FieldDescriptorProto_Type.TYPE_INT64:
case FieldDescriptorProto_Type.TYPE_UINT64:
case FieldDescriptorProto_Type.TYPE_FIXED64:
case FieldDescriptorProto_Type.TYPE_SINT64:
case FieldDescriptorProto_Type.TYPE_SFIXED64:
if (isJsTypeFieldOption(options, field)) {
switch (field.options!.jstype) {
case FieldOptions_JSType.JS_STRING:
return `"${numericDefaultVal}"`;
case FieldOptions_JSType.JS_NUMBER:
return numericDefaultVal;
}
}
if (options.forceLong === LongOption.LONG) {
const value =
field.type === FieldDescriptorProto_Type.TYPE_UINT64 || field.type === FieldDescriptorProto_Type.TYPE_FIXED64
? "UZERO"
: "ZERO";
return code`${utils.Long}.${useDefaultValue ? "fromNumber" : value}${
useDefaultValue ? `(${numericDefaultVal})` : ""
}`;
} else if (options.forceLong === LongOption.STRING) {
return `"${numericDefaultVal}"`;
} else if (options.forceLong === LongOption.BIGINT) {
return options.bigIntLiteral ? code`${numericDefaultVal}n` : code`BigInt("${numericDefaultVal}")`;
} else {
return numericDefaultVal;
}
case FieldDescriptorProto_Type.TYPE_BOOL:
return useDefaultValue ? field.defaultValue : false;
case FieldDescriptorProto_Type.TYPE_STRING:
return useDefaultValue ? `"${field.defaultValue}"` : '""';
case FieldDescriptorProto_Type.TYPE_BYTES:
// todo(proto2): need to look into all the possible default values for the bytes type, and handle each one
if (options.env === EnvOption.NODE) {
return "Buffer.alloc(0)";
}
return "new Uint8Array(0)";
case FieldDescriptorProto_Type.TYPE_MESSAGE:
case FieldDescriptorProto_Type.TYPE_GROUP:
default:
return nullOrUndefined(options);
}
}
/** Creates code that checks that the field is not the default value. Supports scalars and enums. */
export function notDefaultCheck(
ctx: Context,
field: FieldDescriptorProto,
messageOptions: MessageOptions | undefined,
place: string,
): Code {
const { typeMap, options, currentFile } = ctx;
const isOptional = isOptionalProperty(field, messageOptions, options, currentFile.isProto3Syntax);
if (options.noDefaultsForOptionals) {
return isOptional
? code`${place} !== undefined ${withAndMaybeCheckIsNotNull(options, place)}`
: code`${place} !== undefined`;
}
const maybeNotUndefinedAnd = isOptional
? `${place} !== undefined ${withAndMaybeCheckIsNotNull(options, place)} &&`
: "";
switch (field.type) {
case FieldDescriptorProto_Type.TYPE_DOUBLE:
case FieldDescriptorProto_Type.TYPE_FLOAT:
case FieldDescriptorProto_Type.TYPE_INT32:
case FieldDescriptorProto_Type.TYPE_UINT32:
case FieldDescriptorProto_Type.TYPE_SINT32:
case FieldDescriptorProto_Type.TYPE_FIXED32:
case FieldDescriptorProto_Type.TYPE_SFIXED32:
case FieldDescriptorProto_Type.TYPE_BOOL:
case FieldDescriptorProto_Type.TYPE_STRING:
return code`${maybeNotUndefinedAnd} ${place} !== ${defaultValue(ctx, field)}`;
case FieldDescriptorProto_Type.TYPE_ENUM:
// proto3 enforces enums starting at 0, however proto2 does not, so we have
// to probe and see if zero is an allowed value. If it's not, pick the first one.
// This is probably not great, but it's only used in fromJSON and fromPartial,
// and I believe the semantics of those in the proto2 world are generally undefined.
const typeInfo = typeMap.get(field.typeName)!;
const enumProto = typeInfo[2] as EnumDescriptorProto;
const defaultEnum = enumProto.value.find((v) => v.number === defaultValue(ctx, field)) || enumProto.value[0];
if (options.stringEnums) {
const enumType = messageToTypeName(ctx, field.typeName);
const enumValue = getEnumMemberName(ctx, enumProto, defaultEnum);
return code`${maybeNotUndefinedAnd} ${place} !== ${enumType}.${enumValue}`;
} else {
return code`${maybeNotUndefinedAnd} ${place} !== ${defaultEnum.number}`;
}
case FieldDescriptorProto_Type.TYPE_UINT64:
case FieldDescriptorProto_Type.TYPE_FIXED64:
case FieldDescriptorProto_Type.TYPE_INT64:
case FieldDescriptorProto_Type.TYPE_SINT64:
case FieldDescriptorProto_Type.TYPE_SFIXED64:
if (options.forceLong === LongOption.LONG && !isJsTypeFieldOption(options, field)) {
return code`${maybeNotUndefinedAnd} !${place}.equals(${defaultValue(ctx, field)})`;
} else {
return code`${maybeNotUndefinedAnd} ${place} !== ${defaultValue(ctx, field)}`;
}
case FieldDescriptorProto_Type.TYPE_BYTES:
// todo(proto2): need to look into all the possible default values for the bytes type, and handle each one
return code`${maybeNotUndefinedAnd} ${place}.length !== 0`;
default:
throw new Error("Not implemented for the given type.");
}
}
/** A map of proto type name, e.g. `foo.Message.Inner`, to module/class name, e.g. `foo`, `Message_Inner`. */
export type TypeMap = Map<string, [string, string, DescriptorProto | EnumDescriptorProto]>;
/** Scans all of the proto files in `request` and builds a map of proto typeName -> TS module/name. */
export function createTypeMap(request: CodeGeneratorRequest, options: Options): TypeMap {
const typeMap: TypeMap = new Map();
for (const file of request.protoFile) {
// We assume a file.name of google/protobuf/wrappers.proto --> a module path of google/protobuf/wrapper.ts
const moduleName = file.name.replace(".proto", "");
// So given a fullName like FooMessage_InnerMessage, proto will see that as package.name.FooMessage.InnerMessage
function saveMapping(
tsFullName: string,
desc: DescriptorProto | EnumDescriptorProto,
s: SourceInfo,
protoFullName: string,
): void {
// package is optional, but make sure we have a dot-prefixed type name either way
const prefix = file.package.length === 0 ? "" : `.${file.package}`;
typeMap.set(`${prefix}.${protoFullName}`, [moduleName, tsFullName, desc]);
}
visit(file, SourceInfo.empty(), saveMapping, options, saveMapping);
}
return typeMap;
}
/** A "Scalar Value Type" as defined in https://developers.google.com/protocol-buffers/docs/proto3#scalar */
export function isScalar(field: FieldDescriptorProto): boolean {
const scalarTypes = [
FieldDescriptorProto_Type.TYPE_DOUBLE,
FieldDescriptorProto_Type.TYPE_FLOAT,
FieldDescriptorProto_Type.TYPE_INT32,
FieldDescriptorProto_Type.TYPE_INT64,
FieldDescriptorProto_Type.TYPE_UINT32,
FieldDescriptorProto_Type.TYPE_UINT64,
FieldDescriptorProto_Type.TYPE_SINT32,
FieldDescriptorProto_Type.TYPE_SINT64,
FieldDescriptorProto_Type.TYPE_FIXED32,
FieldDescriptorProto_Type.TYPE_FIXED64,
FieldDescriptorProto_Type.TYPE_SFIXED32,
FieldDescriptorProto_Type.TYPE_SFIXED64,
FieldDescriptorProto_Type.TYPE_BOOL,
FieldDescriptorProto_Type.TYPE_STRING,
FieldDescriptorProto_Type.TYPE_BYTES,
];
return scalarTypes.includes(field.type);
}
// When useOptionals='messages', non-scalar fields are translated into optional
// properties.
// When useOptionals='all', all fields are translated into
// optional properties, with the exception of map Entry key/values, which must
// always be present.
// When useOptionals='deprecatedOnly', all deprecated fields are translated into
// optional properties, with the exception of map Entry key/values, which must
// always be present.
// OneOf fields are always optional, whenever oneof=unions option not in use.
export function isOptionalProperty(
field: FieldDescriptorProto,
messageOptions: MessageOptions | undefined,
options: Options,
isProto3Syntax: boolean,
): boolean {
const optionalMessages =
options.useOptionals === true || options.useOptionals === "messages" || options.useOptionals === "all";
const optionalAll = options.useOptionals === "all";
const deprecatedOnly = options.useOptionals === "deprecatedOnly" && field.options && field.options.deprecated;
return (
(optionalMessages && isMessage(field) && !isRepeated(field)) ||
((optionalAll || deprecatedOnly) && !messageOptions?.mapEntry) ||
(options.noDefaultsForOptionals && !isRepeated(field) && (isScalar(field) || isEnum(field))) ||
// file is proto2, we have enabled proto2 optionals, and the field itself is optional
(!isProto3Syntax &&
field.label === FieldDescriptorProto_Label.LABEL_OPTIONAL &&
!messageOptions?.mapEntry &&
!options.disableProto2Optionals) ||
// don't bother verifying that oneof is not union. union oneofs generate their own properties.
isWithinOneOf(field) ||
field.proto3Optional
);
}
/** This includes all scalars, enums and the [groups type](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/DescriptorProtos.FieldDescriptorProto.Type.html#TYPE_GROUP) */
export function isPrimitive(field: FieldDescriptorProto): boolean {
return !isMessage(field);
}
export function isBytes(field: FieldDescriptorProto): boolean {
return field.type === FieldDescriptorProto_Type.TYPE_BYTES;
}
export function isMessage(field: FieldDescriptorProto): boolean {
return field.type === FieldDescriptorProto_Type.TYPE_MESSAGE || field.type === FieldDescriptorProto_Type.TYPE_GROUP;
}
export function isEnum(field: FieldDescriptorProto): boolean {
return field.type === FieldDescriptorProto_Type.TYPE_ENUM;
}
export function isWithinOneOf(field: FieldDescriptorProto): boolean {
return field.hasOwnProperty("oneofIndex");
}
export function isWithinOneOfThatShouldBeUnion(options: Options, field: FieldDescriptorProto): boolean {
return (
isWithinOneOf(field) &&
(options.oneof === OneofOption.UNIONS || options.oneof === OneofOption.UNIONS_VALUE) &&
!field.proto3Optional
);
}
export function isRepeated(field: FieldDescriptorProto): boolean {
return field.label === FieldDescriptorProto_Label.LABEL_REPEATED;
}
export function isLong(field: FieldDescriptorProto): boolean {
return basicLongWireType(field.type) !== undefined;
}
export function isWholeNumber(field: FieldDescriptorProto): boolean {
return (
field.type === FieldDescriptorProto_Type.TYPE_INT32 ||
field.type === FieldDescriptorProto_Type.TYPE_INT64 ||
field.type === FieldDescriptorProto_Type.TYPE_UINT32 ||
field.type === FieldDescriptorProto_Type.TYPE_UINT64 ||
field.type === FieldDescriptorProto_Type.TYPE_SINT32 ||
field.type === FieldDescriptorProto_Type.TYPE_SINT64 ||
field.type === FieldDescriptorProto_Type.TYPE_FIXED32 ||
field.type === FieldDescriptorProto_Type.TYPE_FIXED64 ||
field.type === FieldDescriptorProto_Type.TYPE_SFIXED32 ||
field.type === FieldDescriptorProto_Type.TYPE_SFIXED64
);
}
export function isMapType(ctx: Context, messageDesc: DescriptorProto, field: FieldDescriptorProto): boolean {
return detectMapType(ctx, messageDesc, field) !== undefined;
}
export function isObjectId(field: FieldDescriptorProto): boolean {
// need to use endsWith instead of === because objectid could be imported from an external proto file
return field.typeName.endsWith(".ObjectId");
}
export function isTimestamp(field: FieldDescriptorProto): boolean {
return field.typeName === ".google.protobuf.Timestamp";
}
export function isValueType(ctx: Context, field: FieldDescriptorProto): boolean {
return valueTypeName(ctx, field.typeName) !== undefined;
}
export function isAnyValueType(field: FieldDescriptorProto): boolean {
return isAnyValueTypeName(field.typeName);
}
export function isAnyValueTypeName(typeName: string): boolean {
return typeName === "google.protobuf.Value" || typeName === ".google.protobuf.Value";
}
export function isBytesValueType(field: FieldDescriptorProto): boolean {
return field.typeName === ".google.protobuf.BytesValue";
}
export function isFieldMaskType(field: FieldDescriptorProto): boolean {
return isFieldMaskTypeName(field.typeName);
}
export function isFieldMaskTypeName(typeName: string): boolean {
return typeName === "google.protobuf.FieldMask" || typeName === ".google.protobuf.FieldMask";
}
export function isListValueType(field: FieldDescriptorProto): boolean {
return isListValueTypeName(field.typeName);
}
export function isListValueTypeName(typeName: string): boolean {
return typeName === "google.protobuf.ListValue" || typeName === ".google.protobuf.ListValue";
}
export function isStructType(field: FieldDescriptorProto): boolean {
return isStructTypeName(field.typeName);
}
export function isStructTypeName(typeName: string): boolean {
return typeName === "google.protobuf.Struct" || typeName === ".google.protobuf.Struct";
}
export function isLongValueType(field: FieldDescriptorProto): boolean {
return field.typeName === ".google.protobuf.Int64Value" || field.typeName === ".google.protobuf.UInt64Value";
}
export function isEmptyType(typeName: string): boolean {
return typeName === ".google.protobuf.Empty";
}
export function valueTypeName(ctx: Context, typeName: string): Code | undefined {
switch (typeName) {
case ".google.protobuf.StringValue":
return code`string`;
case ".google.protobuf.Int32Value":
case ".google.protobuf.UInt32Value":
case ".google.protobuf.DoubleValue":
case ".google.protobuf.FloatValue":
return code`number`;
case ".google.protobuf.Int64Value":
case ".google.protobuf.UInt64Value":
// return options ? longTypeName(options) : code`number`;
return longTypeName(ctx);
case ".google.protobuf.BoolValue":
return code`boolean`;
case ".google.protobuf.BytesValue":
return ctx.options.env === EnvOption.NODE
? code`Buffer`
: ctx.options.useJsonWireFormat
? code`string`
: code`Uint8Array`;
case ".google.protobuf.ListValue":
return ctx.options.useReadonlyTypes ? code`ReadonlyArray<any>` : code`Array<any>`;
case ".google.protobuf.Value":
return code`any`;
case ".google.protobuf.Struct":
return ctx.options.useReadonlyTypes ? code`{readonly [key: string]: any}` : code`{[key: string]: any}`;
case ".google.protobuf.FieldMask":
return ctx.options.useJsonWireFormat
? code`string`
: ctx.options.useReadonlyTypes
? code`readonly string[]`
: code`string[]`;
case ".google.protobuf.Duration":
return ctx.options.useJsonWireFormat ? code`string` : undefined;
case ".google.protobuf.Timestamp":
return ctx.options.useJsonWireFormat ? code`string` : undefined;
default:
return undefined;
}
}
export function wrapperTypeName(typeName: string): string | undefined {
switch (typeName) {
case ".google.protobuf.StringValue":
case ".google.protobuf.Int32Value":
case ".google.protobuf.UInt32Value":
case ".google.protobuf.DoubleValue":
case ".google.protobuf.FloatValue":
case ".google.protobuf.Int64Value":
case ".google.protobuf.UInt64Value":
case ".google.protobuf.BoolValue":
case ".google.protobuf.BytesValue":
case ".google.protobuf.ListValue":
case ".google.protobuf.Timestamp":
case ".google.protobuf.Struct":
case ".google.protobuf.Value":
return typeName.split(".")[3];
default:
return undefined;
}
}
function longTypeName(ctx: Context): Code {
const { options, utils } = ctx;
if (options.forceLong === LongOption.LONG) {
return code`${utils.Long}`;
} else if (options.forceLong === LongOption.STRING) {
return code`string`;
} else if (options.forceLong === LongOption.BIGINT) {
return code`bigint`;
} else {
return code`number`;
}
}
function jsTypeName(field: FieldDescriptorProto): Code | undefined {
if (field.options?.jstype === FieldOptions_JSType.JS_STRING) {
return code`string`;
} else if (field.options?.jstype === FieldOptions_JSType.JS_NUMBER) {
return code`number`;
}
}
/** Maps `.some_proto_namespace.Message` to a TypeName. */
export function messageToTypeName(
ctx: Context,
protoType: string,
typeOptions: { keepValueType?: boolean; repeated?: boolean } = {},
): Code {
const { options, typeMap } = ctx;
// Watch for the wrapper types `.google.protobuf.*Value`. If we're mapping
// them to basic built-in types, we union the type with undefined to
// indicate the value is optional. Exceptions:
// - If the field is repeated, values cannot be undefined.
let valueType = valueTypeName(ctx, protoType);
if (!typeOptions.keepValueType && valueType) {
if (typeOptions.repeated ?? false) {
return valueType;
}
return code`${valueType} | ${nullOrUndefined(options)}`;
}
// Look for other special prototypes like Timestamp that aren't technically wrapper types
if (!typeOptions.keepValueType && protoType === ".google.protobuf.Timestamp") {
if (options.useDate == DateOption.DATE) {
return code`Date`;
}
if (options.useDate == DateOption.STRING || options.useDate == DateOption.STRING_NANO) {
return code`string`;
}
}
// need to use endsWith instead of === because objectid could be imported from an external proto file
if (!typeOptions.keepValueType && options.useMongoObjectId && protoType.endsWith(".ObjectId")) {
return code`mongodb.ObjectId`;
}
const [module, type] = toModuleAndType(typeMap, protoType);
return code`${impProto(options, module, type)}`;
}
/** Breaks `.some_proto_namespace.Some.Message` into `['some_proto_namespace', 'Some_Message', Descriptor]. */
function toModuleAndType(typeMap: TypeMap, protoType: string): [string, string, DescriptorProto | EnumDescriptorProto] {
return typeMap.get(protoType) || fail(`No type found for ${protoType}`);
}
export function getEnumMethod(ctx: Context, enumProtoType: string, methodSuffix: string): Import {
const [module, type] = toModuleAndType(ctx.typeMap, enumProtoType);
return impProto(ctx.options, module, `${uncapitalize(type)}${methodSuffix}`);
}
/** Return the TypeName for any field (primitive/message/etc.) as exposed in the interface. */
export function toTypeName(
ctx: Context,
messageDesc: DescriptorProto | undefined,
field: FieldDescriptorProto,
ensureOptional = false,
): Code {
function finalize(type: Code, isOptional: boolean) {
if (isOptional) {
return code`${type} | ${nullOrUndefined(ctx.options, field.proto3Optional)}`;
}
return type;
}
const fieldType = getFieldOptionsJsType(field, ctx.options) ?? field.type;
const type = basicTypeName(ctx, { ...field, type: fieldType }, { keepValueType: false });
if (isRepeated(field)) {
const mapType = messageDesc ? detectMapType(ctx, messageDesc, field) : false;
if (mapType) {
const { keyType, valueType } = mapType;
if (shouldGenerateJSMapType(ctx, messageDesc!, field)) {
return finalize(code`Map<${keyType}, ${valueType}>`, ensureOptional);
}
return finalize(code`{ [key: ${keyType} ]: ${valueType} }`, ensureOptional);
}
if (ctx.options.useReadonlyTypes) {
return finalize(code`readonly ${type}[]`, ensureOptional);
}
return finalize(code`${type}[]`, ensureOptional);
}
if (isValueType(ctx, field)) {
// google.protobuf.*Value types are already unioned with `undefined`
// in messageToTypeName, so no need to consider them for that here.
return finalize(type, false);
}
// By default (useOptionals='none', oneof=properties), non-scalar fields
// outside oneofs and all fields within a oneof clause need to be unioned
// with `undefined` to indicate the value is optional.
//
// When useOptionals='messages' or useOptionals='all', non-scalar fields are
// translated to optional properties, so no need for the union with
// `undefined` here.
//
// When oneof=unions, we generate a single property for the entire `oneof`
// clause, spelling each option out inside a large type union. No need for
// union with `undefined` here, either.
const { options } = ctx;
return finalize(
type,
(!isWithinOneOf(field) &&
isMessage(field) &&
(options.useOptionals === false || options.useOptionals === "none")) ||
(isWithinOneOf(field) && options.oneof === OneofOption.PROPERTIES) ||
(isWithinOneOf(field) && field.proto3Optional) ||
ensureOptional,
);
}
/**
* For a protobuf map field, if the generated code should use the javascript Map type.
*
* If the type of a protobuf map key corresponds to the Long type, we always use the Map type. This avoids generating
* invalid code such as below (using Long as key of a javascript object):
*
* export interface Foo {
* bar: { [key: Long]: Long }
* }
*
* See https://github.com/stephenh/ts-proto/issues/708 for more details.
*/
export function shouldGenerateJSMapType(ctx: Context, message: DescriptorProto, field: FieldDescriptorProto): boolean {
if (ctx.options.useMapType) {
return true;
}
const mapType = detectMapType(ctx, message, field);
if (!mapType) {
return false;
}
return (
mapType.keyField.type === FieldDescriptorProto_Type.TYPE_BOOL ||
(isLong(mapType.keyField) && ctx.options.forceLong === LongOption.LONG)
);
}
export function detectMapType(
ctx: Context,
messageDesc: DescriptorProto,
fieldDesc: FieldDescriptorProto,
):
| {
messageDesc: DescriptorProto;
keyField: FieldDescriptorProto;
keyType: Code;
valueField: FieldDescriptorProto;
valueType: Code;
}
| undefined {
const { typeMap } = ctx;
if (
fieldDesc.label === FieldDescriptorProto_Label.LABEL_REPEATED &&
fieldDesc.type === FieldDescriptorProto_Type.TYPE_MESSAGE
) {
const mapType = typeMap.get(fieldDesc.typeName)![2] as DescriptorProto;
if (!mapType.options?.mapEntry) return undefined;
const [keyField, valueField] = mapType.field;
const keyType = toTypeName(ctx, messageDesc, keyField);
// use basicTypeName because we don't need the '| undefined'
const valueType = basicTypeName(ctx, valueField);
return { messageDesc: mapType, keyField, keyType, valueField, valueType };
}
return undefined;
}
export function rawRequestType(
ctx: Context,
methodDesc: MethodDescriptorProto,
typeOptions: { keepValueType?: boolean; repeated?: boolean } = {},
): Code {
return messageToTypeName(ctx, methodDesc.inputType, typeOptions);
}
export function observableType(ctx: Context, asType: boolean = false): Code {
if (ctx.options.useAsyncIterable) {
return code`AsyncIterable`;
} else if (asType) {
return code`${imp("t:Observable@rxjs")}`;
} else {
return code`${imp("Observable@rxjs")}`;
}
}
export function requestType(ctx: Context, methodDesc: MethodDescriptorProto, partial: boolean = false): Code {
let typeName = rawRequestType(ctx, methodDesc, { keepValueType: true });
if (partial) {
typeName = code`${ctx.utils.DeepPartial}<${typeName}>`;
}
if (methodDesc.clientStreaming) {
return code`${observableType(ctx)}<${typeName}>`;
}
return typeName;
}
export function responseType(
ctx: Context,
methodDesc: MethodDescriptorProto,
typeOptions: { keepValueType?: boolean; repeated?: boolean } = {},
): Code {
return messageToTypeName(ctx, methodDesc.outputType, { keepValueType: true });
}
export function responsePromise(ctx: Context, methodDesc: MethodDescriptorProto): Code {
return code`Promise<${responseType(ctx, methodDesc, { keepValueType: true })}>`;
}
export function responseObservable(ctx: Context, methodDesc: MethodDescriptorProto): Code {
return code`${observableType(ctx)}<${responseType(ctx, methodDesc, { keepValueType: true })}>`;
}
export function responsePromiseOrObservable(ctx: Context, methodDesc: MethodDescriptorProto): Code {
const { options } = ctx;
if (options.returnObservable || methodDesc.serverStreaming) {
return responseObservable(ctx, methodDesc);
}
return responsePromise(ctx, methodDesc);
}
export interface BatchMethod {
methodDesc: MethodDescriptorProto;
// a ${package + service + method name} key to identify this method in caches
uniqueIdentifier: string;
singleMethodName: string;
inputFieldName: string;
inputType: Code;
outputFieldName: string;
outputType: Code;
mapType: boolean;
}
export function detectBatchMethod(
ctx: Context,
fileDesc: FileDescriptorProto,
serviceDesc: ServiceDescriptorProto,
methodDesc: MethodDescriptorProto,
): BatchMethod | undefined {
const { typeMap } = ctx;
const nameMatches = methodDesc.name.startsWith("Batch");
const inputType = typeMap.get(methodDesc.inputType);
const outputType = typeMap.get(methodDesc.outputType);
if (nameMatches && inputType && outputType) {
// TODO: This might be enums?
const inputTypeDesc = inputType[2] as DescriptorProto;
const outputTypeDesc = outputType[2] as DescriptorProto;
if (hasSingleRepeatedField(inputTypeDesc) && hasSingleRepeatedField(outputTypeDesc)) {
const singleMethodName = methodDesc.name.replace("Batch", "Get");
const inputFieldName = inputTypeDesc.field[0].name;
const inputType = basicTypeName(ctx, inputTypeDesc.field[0]); // e.g. repeated string -> string
const outputFieldName = outputTypeDesc.field[0].name;
let outputType = basicTypeName(ctx, outputTypeDesc.field[0]); // e.g. repeated Entity -> Entity
const mapType = detectMapType(ctx, outputTypeDesc, outputTypeDesc.field[0]);
if (mapType) {
outputType = mapType.valueType;
}
const uniqueIdentifier = `${maybePrefixPackage(fileDesc, serviceDesc.name)}.${methodDesc.name}`;
return {
methodDesc: methodDesc,
uniqueIdentifier,
singleMethodName: FormattedMethodDescriptor.formatName(singleMethodName, ctx.options),
inputFieldName,
inputType,
outputFieldName,
outputType,
mapType: !!mapType,
};
}
}
return undefined;
}
function hasSingleRepeatedField(messageDesc: DescriptorProto): boolean {
return messageDesc.field.length == 1 && messageDesc.field[0].label === FieldDescriptorProto_Label.LABEL_REPEATED;
}
export function isJsTypeFieldOption(options: Options, field: FieldDescriptorProto): boolean {
return (
options.useJsTypeOverride &&
(field.options?.jstype === FieldOptions_JSType.JS_NUMBER || field.options?.jstype === FieldOptions_JSType.JS_STRING)
);
}