-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcodegen.go
1227 lines (1122 loc) · 44.5 KB
/
codegen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
)
var (
importPathFlag = StringSlice("import_path", []string{}, "A mapping of proto imports to TS imports, as `PROTO_PATH=TS_PATH` pairs (this flag can be specified more than once). If the proto does not end with '.proto' then these act as directory prefixes.")
strictImportsFlag = flag.Bool("strict_imports", false, "If set, all directly imported protos must have an -import_path specified. This prevents the plugin from \"guessing\" import paths based on the proto path. This is also useful when integrating with build systems where all direct dependencies must be explicitly specified.")
importModuleSpecifierEnding = flag.String("import_module_specifier_ending", "", "Suffix to apply to generated import module specifiers. May need to be set to \".js\" in rare cases.")
outFlag = flag.String("out", "", "Output file `path`. If this is set and multiple protos are provided as input, the generated code for all protos will be written to this file. Any '.ts' or '.js' extension will be ignored.")
importPaths = map[string]string{}
)
// Top-level declarations that are duplicated at the top of each generated file.
//
// TODO: maybe publish an NPM package with these declarations so they aren't
// duplicated as much.
const (
streamTypeDeclarations = `
export namespace $stream {
export type ServerStream<T> = {
/** Cancels the RPC. */
cancel(): void;
}
export type ServerStreamHandler<T> = {
/** Handles a message on the stream. */
next: (message: T) => void;
/** Handles an error on the stream. */
error: (e: any) => void;
/** Called after all messages have been received from the server. Not called on error. */
complete: () => void;
}
export type StreamingRPCParams = {
signal: AbortSignal;
complete: () => void;
}
}
`
)
func generateCode(req *pluginpb.CodeGeneratorRequest) (*pluginpb.CodeGeneratorResponse, error) {
for _, p := range *importPathFlag {
parts := strings.SplitN(p, "=", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid import_path %q: should be of the form `PROTO_PATH_PREFIX=TS_PATH_PREFIX`", p)
}
protoPath, tsPath := parts[0], parts[1]
if !strings.HasSuffix(protoPath, "/") && !strings.HasSuffix(protoPath, ".proto") {
protoPath += "/"
}
if !strings.HasSuffix(tsPath, "/") && !strings.HasSuffix(protoPath, ".proto") {
tsPath += "/"
}
importPaths[protoPath] = tsPath
}
// Debug: print a minimal version of the incoming CodeGeneratorRequest.
if os.Getenv("VERBOSE") == "1" {
// Throw away all source code info other than comments & the fields they
// apply to.
for _, f := range req.GetProtoFile() {
var nonEmptyLocations []*descriptorpb.SourceCodeInfo_Location
for _, l := range f.GetSourceCodeInfo().GetLocation() {
if l.GetLeadingComments() != "" {
l.Span = nil // span is unused
nonEmptyLocations = append(nonEmptyLocations, l)
}
}
f.GetSourceCodeInfo().Location = nonEmptyLocations
}
jb, _ := protojson.MarshalOptions{Multiline: true}.Marshal(req)
logf("CodeGeneratorRequest: %s\n", string(jb))
}
var features uint64
features |= uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
res := &pluginpb.CodeGeneratorResponse{
SupportedFeatures: &features,
}
idx := BuildIndex(req)
// If --out is set, write all sources to a single file.
if *outFlag != "" {
c := newCodegen(idx, *outFlag, req.GetFileToGenerate()...)
outs, err := c.Generate()
if err != nil {
return nil, err
}
res.File = append(res.File, outs...)
} else {
// Otherwise write each source named according to the .proto path
for _, path := range req.GetFileToGenerate() {
out := strings.TrimSuffix(path, ".proto")
c := newCodegen(idx, out, path)
outs, err := c.Generate()
if err != nil {
return nil, err
}
res.File = append(res.File, outs...)
}
}
return res, nil
}
// Namespace represents a namespace tree to be generated.
type Namespace struct {
Name string
Files []*descriptorpb.FileDescriptorProto
Children map[string]*Namespace
}
// Codegen generates code for a single proto file descriptor.
type Codegen struct {
Index *Index
// Generated TypeScript declarations (.d.ts content)
d *TS
// Generated JS implementation (.js content)
j *TS
// Paths to the top-level protos to be translated to TS.
Paths []string
// Out is the file being generated by this codegen.
Out string
// Map of input file path -> map of SourceCodeInfo_Location.path stringified
// list repr like "[4 5 1 2 0 3]" -> SourceCodeInfo_Location.leading_comment
Comments map[string]map[string]string
// Map of symbol -> import path
ImportedSymbols map[string]string
// Map of import path -> symbol
ImportedFiles map[string]string
}
func newCodegen(idx *Index, out string, paths ...string) *Codegen {
// Map of file path -> serialized
comments := map[string]map[string]string{}
for _, path := range paths {
comments[path] = map[string]string{}
for _, l := range idx.Files[path].GetSourceCodeInfo().GetLocation() {
if l.GetLeadingComments() == "" {
continue
}
comments[path][fmt.Sprint(l.GetPath())] = l.GetLeadingComments()
}
}
return &Codegen{
d: &TS{},
j: &TS{JS: true},
Index: idx,
Paths: paths,
Out: out,
Comments: comments,
ImportedSymbols: map[string]string{},
ImportedFiles: map[string]string{},
}
}
// Generate returns two files: a .js file with generated message, enum, and
// service classes, as well as a companion .d.ts file with TypeScript typings
// for the JS code.
func (c *Codegen) Generate() ([]*pluginpb.CodeGeneratorResponse_File, error) {
j, d := c.j, c.d
// Check that all dependencies are indexed, since we need to know how to
// import their types.
for _, path := range c.Paths {
for _, d := range c.Index.Files[path].GetDependency() {
if _, ok := c.Index.Files[d]; !ok {
return nil, fmt.Errorf("missing dependency %q in code generation request", d)
}
}
}
var outs []*pluginpb.CodeGeneratorResponse_File
d.DefaultImport("protobufjs/minimal", "* as $protobuf")
j.DefaultImport("protobufjs/minimal", "* as $protobuf")
j.L("// Common aliases")
j.L("const $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;")
j.L("// Exported root namespace")
j.L("const $root = {};")
root := c.buildNamespaceTree()
for _, name := range sortedKeys(root.Children) {
c.generateNamespace(root.Children[name], name)
}
outNoExt := c.Out
for _, ext := range []string{".js", ".ts", ".d.ts"} {
outNoExt = strings.ReplaceAll(outNoExt, ext, "")
}
declarationName := outNoExt + ".d.ts"
declarationContent := d.String()
declaration := &pluginpb.CodeGeneratorResponse_File{
Name: &declarationName,
Content: &declarationContent,
}
outs = append(outs, declaration)
jsName := outNoExt + ".js"
jsContent := j.String()
js := &pluginpb.CodeGeneratorResponse_File{
Name: &jsName,
Content: &jsContent,
}
outs = append(outs, js)
return outs, nil
}
func (c *Codegen) buildNamespaceTree() *Namespace {
root := &Namespace{Children: map[string]*Namespace{}}
for _, path := range c.Paths {
f := c.Index.Files[path]
parts := strings.Split(f.GetPackage(), ".")
ns := root
for _, part := range parts {
c := ns.Children[part]
if c == nil {
c = &Namespace{Name: part, Children: map[string]*Namespace{}}
ns.Children[part] = c
}
ns = c
}
ns.Files = append(ns.Files, f)
}
return root
}
func (c *Codegen) generateNamespace(ns *Namespace, nsPath string) {
j, d := c.j, c.d
d.Lf("export namespace %s {", ns.Name)
if strings.Contains(nsPath, ".") {
j.Lf("%s.%s = (() => {", stringPart(nsPath, ".", -2), ns.Name)
} else {
j.Lf("$root.%s = (() => {", ns.Name)
}
j.Lf("const %s = {};", ns.Name)
for _, f := range ns.Files {
c.generate(f, []int32{}, nsPath, f.GetMessageType(), f.GetEnumType(), f.GetService())
}
for _, name := range sortedKeys(ns.Children) {
c.generateNamespace(ns.Children[name], nsPath+"."+name)
}
d.L("}")
j.Lf("return %s;", ns.Name)
j.L("})();")
if !strings.Contains(nsPath, ".") {
j.Lf("export const %s = $root.%s;", ns.Name, ns.Name)
}
}
func (c *Codegen) generate(file *descriptorpb.FileDescriptorProto, sourcePath []int32, ns string, messages []*descriptorpb.DescriptorProto, enums []*descriptorpb.EnumDescriptorProto, services []*descriptorpb.ServiceDescriptorProto) {
j, d := c.j, c.d
curNS := stringPart(ns, ".", -1)
// Generate message type interfaces
for messageIndex, messageType := range messages {
messageFieldTag := fileDescriptorMessageTypeTagNumber
if len(sourcePath) > 0 {
messageFieldTag = descriptorNestedTypeTagNumber
}
messagePath := append(sourcePath, int32(messageFieldTag), int32(messageIndex))
// Message interface type
d.BlockComment(c.Comments[file.GetName()][fmt.Sprint(messagePath)])
d.Lf("export interface I%s {", messageType.GetName())
for fieldIndex, field := range messageType.Field {
fieldPath := append(messagePath, descriptorFieldTagNumber, int32(fieldIndex))
d.BlockComment(c.Comments[file.GetName()][fmt.Sprint(fieldPath)])
d.Lf("%s?: %s;", field.GetJsonName(), c.typeAnnotation(field))
}
d.L("}")
// Message class type + implementation
d.Lf("export class %s implements I%s {", messageType.GetName(), messageType.GetName())
j.Lf("%s.%s = (() => {", curNS, messageType.GetName())
j.Lf("class %s {", messageType.GetName())
// Declare fields (to implement interface)
for _, field := range messageType.GetField() {
d.Lf("%s: %s;", field.GetJsonName(), c.typeAnnotation(field))
}
// Oneof getters/setters
var numOneofs int32
for _, field := range messageType.GetField() {
if field.OneofIndex != nil && field.GetOneofIndex()+1 > numOneofs {
numOneofs = field.GetOneofIndex() + 1
}
}
if numOneofs > 0 {
oneofFieldNames := make([][]string, int(numOneofs))
for _, field := range messageType.GetField() {
// Don't generate oneof API for optionals. protoc treats optionals as
// oneofs containing a single field, but this is just for backwards
// compatibility with code generators that don't have proper support for
// optionals. We properly support optionals by typing them as
// "T | undefined | null"
if field.GetProto3Optional() {
continue
}
if field.OneofIndex != nil {
i := *field.OneofIndex
oneofFieldNames[i] = append(oneofFieldNames[i], field.GetJsonName())
}
}
for i, decl := range messageType.GetOneofDecl() {
fieldNames := oneofFieldNames[i]
if len(fieldNames) == 0 {
continue
}
fieldStrings := make([]string, 0, len(fieldNames))
for _, f := range fieldNames {
fieldStrings = append(fieldStrings, fmt.Sprintf(`"%s"`, f))
}
fieldNameType := strings.Join(fieldStrings, " | ")
fieldNameArray := "[" + strings.Join(fieldStrings, ", ") + "]"
// TODO: maybe more performant in some cases to only iterate over own
// properties of `this`
d.Lf("/**")
d.Lf(" * Returns the `%s` oneof field name that is set,", oneofFieldName(decl))
d.Lf(" * or undefined if none is set.")
d.Lf(" */")
d.Lf("get %s(): %s | undefined;", oneofFieldName(decl), fieldNameType)
j.Lf("get %s() {", oneofFieldName(decl))
j.Lf("for (const key of %s) {", fieldNameArray)
j.L("if (this[key] !== null && this[key] !== undefined) return key;")
j.L("}")
j.L("}")
d.Lf("/**")
d.Lf(" * Sets which `%s` oneof field is set", oneofFieldName(decl))
d.Lf(" * by deleting any other fields in the oneof that might be set.")
d.Lf(" */")
d.Lf("set %s(name: %s | undefined): void;", oneofFieldName(decl), fieldNameType)
j.Lf("set %s(name) {", oneofFieldName(decl))
j.Lf("for (const key of %s) {", fieldNameArray)
j.L("if (key !== name) delete this[key];")
j.L("}")
j.L("}")
}
}
// Constructor
d.Lf("constructor(properties?: I%s);", messageType.GetName())
j.Lf("constructor(properties) {")
// All repeated fields and maps are initialized to empty
for _, f := range messageType.GetField() {
if c.isMapField(f) {
j.Lf("this.%s = {};", f.GetJsonName())
continue
}
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
j.Lf("this.%s = [];", f.GetJsonName())
continue
}
}
j.L("if (properties) {")
j.Lf("for (let key of Object.keys(properties)) {")
j.L("if (properties[key] != null) this[key] = properties[key];")
j.L("}")
j.L("}")
j.L("}")
// Message.create()
d.Lf("static create(properties?: I%s): %s;", messageType.GetName(), messageType.GetName())
j.L("static create(properties) {")
j.Lf("return new %s(properties)", messageType.GetName())
j.L("}")
//
// Encode method
//
d.Lf("static encode(message: I%s, writer?: $protobuf.Writer): $protobuf.Writer;", messageType.GetName())
j.Lf("static encode(message, writer) {")
j.L("if (!writer) writer = $Writer.create();")
for _, f := range messageType.GetField() {
// Map fields (encode as repeated map entry message)
if c.isMapField(f) {
j.Lf(`if (message.%s != null && Object.hasOwnProperty.call(message, "%s")) {`, f.GetJsonName(), f.GetJsonName())
j.Lf("for (const key of Object.keys(message.%s)) {", f.GetJsonName())
mapEntryType := c.Index.MessageTypes[f.GetTypeName()]
// Map entries always exactly two fields: key, then value
kf := mapEntryType.GetField()[0]
vf := mapEntryType.GetField()[1]
begin := fmt.Sprintf("writer.uint32(%d).fork()", f.GetNumber()<<3|lenWireType)
encodeKey := fmt.Sprintf(".uint32(%d).%s(key)", kf.GetNumber()<<3|wireType(kf), encodeMethodName(kf))
if vf.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
classReference := c.resolveTypeName(vf.GetTypeName(), "$root.")
j.L(begin + encodeKey + ";")
j.Lf("%s.encode(message.%s[key], writer.uint32(%d).fork()).ldelim().ldelim();", classReference, f.GetJsonName(), vf.GetNumber()<<3|wireType(vf))
} else {
encodeValue := fmt.Sprintf(".uint32(%d).%s(message.%s[key])", vf.GetNumber()<<3|wireType(vf), encodeMethodName(vf), f.GetJsonName())
j.L(begin + encodeKey + encodeValue + ".ldelim();")
}
j.L("}")
j.L("}")
continue
}
// Packed repeated fields
if isPackedField(f) {
j.Lf(`if (message.%s != null && Object.hasOwnProperty.call(message, "%s")) {`, f.GetJsonName(), f.GetJsonName())
j.Lf("writer.uint32(%d).fork();", f.GetNumber()<<3|lenWireType)
j.Lf("for (const element of message.%s) {", f.GetJsonName())
j.Lf("writer.%s(element)", encodeMethodName(f))
j.Lf("}")
j.L("writer.ldelim();")
j.L("}")
continue
}
// Non-packed repeated fields
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
j.Lf(`if (message.%s != null && Object.hasOwnProperty.call(message, "%s")) {`, f.GetJsonName(), f.GetJsonName())
j.Lf("for (const element of message.%s) {", f.GetJsonName())
if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
classReference := c.resolveTypeName(f.GetTypeName(), "$root.")
j.Lf("%s.encode(element, writer.uint32(%d).fork()).ldelim();", classReference, f.GetNumber()<<3|lenWireType)
} else {
j.Lf("writer.uint32(%d).%s(element);", f.GetNumber()<<3|wireType(f), encodeMethodName(f))
}
j.L("}")
j.L("}")
continue
}
// Non-repeated fields
j.Lf(`if (message.%s != null && Object.hasOwnProperty.call(message, "%s")) {`, f.GetJsonName(), f.GetJsonName())
if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
// TODO: handle groups
classReference := c.resolveTypeName(f.GetTypeName(), "$root.")
j.Lf("%s.encode(message.%s, writer.uint32(%d).fork()).ldelim();", classReference, f.GetJsonName(), f.GetNumber()<<3|lenWireType)
} else {
j.Lf("writer.uint32(%d).%s(message.%s);", f.GetNumber()<<3|wireType(f), encodeMethodName(f), f.GetJsonName())
}
j.L("}")
continue
}
j.L("return writer;")
j.L("}") // encode
//
// Decode method
//
d.Lf("static decode(reader: $protobuf.Reader | Uint8Array, length?: number): %s;", messageType.GetName())
j.Lf("static decode(reader, length) {")
j.L("if (!(reader instanceof $Reader)) reader = $Reader.create(reader);")
j.L("let end = length === undefined ? reader.len : reader.pos + length;")
j.Lf("let message = new %s();", messageType.GetName())
j.L("let key, value;")
j.L("while (reader.pos < end) {")
j.L("let tag = reader.uint32();")
j.L("switch (tag >>> 3) {")
for _, f := range messageType.GetField() {
j.Lf("case %d: {", f.GetNumber())
(func() {
// Map fields
if c.isMapField(f) {
j.Lf("if (message.%s === $util.emptyObject) message.%s = {};", f.GetJsonName(), f.GetJsonName())
j.L("let end2 = reader.uint32() + reader.pos;")
entryType := c.Index.MessageTypes[f.GetTypeName()]
kf := entryType.GetField()[0]
vf := entryType.GetField()[1]
j.Lf("key = %s;", c.defaultValueExpression(kf))
j.Lf("value = %s;", c.defaultValueExpression(vf))
j.L("while (reader.pos < end2) {")
j.L("let tag2 = reader.uint32();")
j.L("switch (tag2 >>> 3) {")
j.L("case 1: {")
j.Lf("key = reader.%s();", encodeMethodName(kf))
j.L("break;")
j.L("}")
j.L("case 2: {")
if vf.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
classReference := c.resolveTypeName(vf.GetTypeName(), "$root.")
j.Lf("value = %s.decode(reader, reader.uint32());", classReference)
} else {
j.Lf("value = reader.%s();", encodeMethodName(vf))
}
j.L("break;")
j.L("}")
j.L("}") // switch
j.Lf("message.%s[key] = value;", f.GetJsonName())
j.L("}") // while
return
}
// Packable (always check for forward and backward compatibility)
if isPackableField(f) {
// Note: the ".length" condition makes sure we replace the
// $util.emptyArray with a new mutable array
j.Lf("if (!message.%s || !message.%s.length) {", f.GetJsonName(), f.GetJsonName())
j.Lf("message.%s = [];", f.GetJsonName())
j.L("}")
j.Lf("if ((tag & %d) === %d) {", wireTypeMask, lenWireType)
j.L("let end2 = reader.uint32() + reader.pos;")
j.Lf("while (reader.pos < end2) message.%s.push(reader.%s());", f.GetJsonName(), encodeMethodName(f))
j.L("} else {")
j.Lf("message.%s.push(reader.%s());", f.GetJsonName(), encodeMethodName(f))
j.L("}")
return
}
// Non-packable repeated fields
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
// Note: the ".length" condition makes sure we replace the
// $util.emptyArray with a new mutable array
j.Lf("if (!message.%s || !message.%s.length) {", f.GetJsonName(), f.GetJsonName())
j.Lf("message.%s = [];", f.GetJsonName())
j.L("}")
if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
classReference := c.resolveTypeName(f.GetTypeName(), "$root.")
j.Lf("message.%s.push(%s.decode(reader, reader.uint32()));", f.GetJsonName(), classReference)
} else {
j.Lf("message.%s.push(reader.%s());", f.GetJsonName(), encodeMethodName(f))
}
return
}
// Non-repeated fields
if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
classReference := c.resolveTypeName(f.GetTypeName(), "$root.")
j.Lf("message.%s = %s.decode(reader, reader.uint32());", f.GetJsonName(), classReference)
} else {
j.Lf("message.%s = reader.%s();", f.GetJsonName(), encodeMethodName(f))
}
})()
j.L("break;")
j.L("}")
}
j.L("default: {")
j.Lf("reader.skipType(tag & %d);", wireTypeMask)
j.L("break;")
j.L("}")
j.L("}") // switch
j.L("}") // while
j.L("return message;")
j.L("}") // decode()
//
// fromObject method
//
d.Lf("static fromObject(object: Record<string, any>): %s;", messageType.GetName())
j.L("static fromObject(object) {")
j.Lf("if (object instanceof $root.%s.%s) {", ns, messageType.GetName())
j.L("return object;")
j.L("}")
j.Lf("const message = new $root.%s.%s();", ns, messageType.GetName())
for _, f := range messageType.GetField() {
// Map fields
if c.isMapField(f) {
j.Lf("if (object.%s) {", f.GetJsonName())
j.Lf(`if (typeof object.%s !== "object") {`, f.GetJsonName())
j.Lf(`throw new TypeError(".%s.%s.%s: object expected, but got " + (typeof object.%s));`, ns, messageType.GetName(), f.GetJsonName(), f.GetJsonName())
j.L("}")
j.Lf("message.%s = {};", f.GetJsonName())
j.Lf("for (let keys = Object.keys(object.%s), i = 0; i < keys.length; ++i) {", f.GetJsonName())
src := fmt.Sprintf("object.%s[keys[i]]", f.GetJsonName())
dest := fmt.Sprintf("message.%s[keys[i]]", f.GetJsonName())
mapEntryType := c.Index.MessageTypes[f.GetTypeName()]
vf := mapEntryType.GetField()[1]
c.generateFromObjectConversionStatements(dest, src, vf, messageType, ns)
j.Lf("}")
j.L("}")
continue
}
// Repeated fields
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
j.Lf("if (object.%s) {", f.GetJsonName())
j.Lf("if (!Array.isArray(object.%s)) {", f.GetJsonName())
j.Lf(`throw new TypeError(".%s.%s.%s: array type expected, but got " + (typeof object.%s))`, ns, messageType.GetName(), f.GetJsonName(), f.GetJsonName())
j.Lf("}")
j.Lf("message.%s = new Array(object.%s.length);", f.GetJsonName(), f.GetJsonName())
j.Lf("for (let i = 0; i < object.%s.length; ++i) {", f.GetJsonName())
src := fmt.Sprintf("object.%s[i]", f.GetJsonName())
dest := fmt.Sprintf("message.%s[i]", f.GetJsonName())
c.generateFromObjectConversionStatements(dest, src, f, messageType, ns)
j.Lf("}")
j.Lf("}")
continue
}
// Non-repeated fields
j.Lf("if (object.%s != null) {", f.GetJsonName())
src := fmt.Sprintf("object.%s", f.GetJsonName())
dest := fmt.Sprintf("message.%s", f.GetJsonName())
c.generateFromObjectConversionStatements(dest, src, f, messageType, ns)
j.Lf("}")
}
j.L("return message;")
j.L("}")
//
// toObject method
//
d.Lf("static toObject(message: %s, options: $protobuf.IConversionOptions): Record<string, any>;", messageType.GetName())
j.L("static toObject(message, options = {}) {")
j.L("const object = {};")
// Init arrays
j.L("if (options.arrays || options.defaults) {")
for _, f := range messageType.GetField() {
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED && !c.isMapField(f) {
j.Lf("object.%s = [];", f.GetJsonName())
}
}
j.L("}")
// Init maps
j.L("if (options.objects || options.defaults) {")
for _, f := range messageType.GetField() {
if c.isMapField(f) {
j.Lf("object.%s = {};", f.GetJsonName())
}
}
j.L("}")
// Init default values
j.L("if (options.defaults) {")
for _, f := range messageType.GetField() {
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED || c.isMapField(f) || f.GetProto3Optional() || f.OneofIndex != nil {
continue
}
if isLong(f.GetType()) {
j.L("if ($util.Long) {")
j.Lf("let long = new $util.Long(0, 0, %t)", isUint(f.GetType()))
j.Lf(`object.%s = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long;`, f.GetJsonName())
j.L("} else {")
j.Lf(`object.%s = options.longs === String ? "0" : 0;`, f.GetJsonName())
j.L("}")
continue
}
if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_BYTES {
j.L("if (options.bytes === String) {")
j.Lf(`object.%s = ""`, f.GetJsonName())
j.L("} else {")
j.Lf("object.%s = [];", f.GetJsonName())
j.Lf("if (options.bytes !== Array) {")
j.Lf("object.%s = $util.newBuffer(object.%s);", f.GetJsonName(), f.GetJsonName())
j.L("}")
j.L("}")
continue
}
if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_ENUM {
j.Lf(`object.%s = options.enums === String ? "%s" : 0`, f.GetJsonName(), c.enumZeroValue(f).GetName())
continue
}
j.Lf("object.%s = %s;", f.GetJsonName(), c.defaultValueExpression(f))
}
j.L("}")
// Convert message fields
j.L("let keys;")
for _, f := range messageType.GetField() {
if c.isMapField(f) {
mapEntryType := c.Index.MessageTypes[f.GetTypeName()]
vf := mapEntryType.GetField()[1]
j.Lf("if (message.%s && (keys = Object.keys(message.%s)).length) {", f.GetJsonName(), f.GetJsonName())
j.Lf("object.%s = {};", f.GetJsonName())
j.L("for (let i = 0; i < keys.length; ++i) {")
j.Lf("object.%s[keys[i]] = %s;", f.GetJsonName(), c.toObjectConversionExpression(vf, "message."+f.GetJsonName()+"[keys[i]]"))
j.L("}")
j.L("}")
continue
}
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
j.Lf(`if (message.%s && message.%s.length) {`, f.GetJsonName(), f.GetJsonName())
j.Lf("object.%s = new Array(message.%s.length);", f.GetJsonName(), f.GetJsonName())
j.Lf("for (let i = 0; i < message.%s.length; ++i) {", f.GetJsonName())
j.Lf("object.%s[i] = %s;", f.GetJsonName(), c.toObjectConversionExpression(f, "message.%s[i]", f.GetJsonName()))
j.Lf("}")
j.Lf("}")
continue
}
j.Lf(`if (message.%s != null && message.hasOwnProperty("%s")) {`, f.GetJsonName(), f.GetJsonName())
j.Lf("object.%s = %s;", f.GetJsonName(), c.toObjectConversionExpression(f, "message.%s", f.GetJsonName()))
if f.OneofIndex != nil && !f.GetProto3Optional() {
j.L("if (options.oneofs) {")
j.Lf(`object.%s = "%s";`, oneofFieldName(parentOneof(messageType, f)), f.GetJsonName())
j.L("}")
}
j.L("}")
}
j.L("return object;")
j.L("}")
// toJSON
d.L("toJSON(): Record<string, any>")
// getTypeUrl
d.L(`static getTypeUrl(typeUrlPrefix?: string): string;`)
j.L(`static getTypeUrl(typeUrlPrefix = "type.googleapis.com") {`)
j.Lf(`return typeUrlPrefix + "/%s.%s";`, ns, messageType.GetName())
j.L("}")
// End class definition
d.L("}")
j.L("}")
// Define prototype methods (note: not the same as static methods)
j.Lf("%s.prototype.toJSON = function toJSON() {", messageType.GetName())
j.L("return this.constructor.toObject(this, $protobuf.util.toJSONOptions);")
j.L("}")
// Assign defaults to class prototype instance
for _, field := range messageType.GetField() {
j.Lf("%s.prototype.%s = %s;", messageType.GetName(), field.GetJsonName(), c.defaultValueExpression(field))
}
// Generate sub-namespaces containing any nested messages and enums.
// Don't generate map entry types explicitly since we generate native
// map code instead.
nestedMessageTypes := excludeMapEntries(messageType.GetNestedType())
if len(nestedMessageTypes) > 0 || len(messageType.GetEnumType()) > 0 {
d.Lf("export namespace %s {", messageType.GetName())
c.generate(file, messagePath, ns+"."+messageType.GetName(), nestedMessageTypes, messageType.GetEnumType(), nil /*=services*/)
d.L("}")
}
j.Lf("return %s;", messageType.GetName())
j.L("})();")
}
// Generate enums
for enumIndex, enumType := range enums {
enumFieldTag := fileDescriptorEnumTypeTagNumber
if len(sourcePath) > 0 {
enumFieldTag = descriptorEnumTypeTagNumber
}
enumPath := append(sourcePath, enumFieldTag, int32(enumIndex))
d.BlockComment(c.Comments[file.GetName()][fmt.Sprint(enumPath)])
d.Lf("export enum %s {", enumType.GetName())
j.Lf("%s.%s = (function() {", curNS, enumType.GetName())
j.Lf("const valuesById = {};")
j.Lf("const values = Object.create(valuesById);")
for valueIndex, value := range enumType.GetValue() {
valuePath := append(enumPath, enumDescriptorValueTagNumber, int32(valueIndex))
d.BlockComment(c.Comments[file.GetName()][fmt.Sprint(valuePath)])
d.Lf("%s = %d,", value.GetName(), value.GetNumber())
j.Lf("values[valuesById[%d] = %q] = %d;", value.GetNumber(), value.GetName(), value.GetNumber())
}
d.L("}")
j.Lf("return values;")
j.L("})();")
}
// Generate services
for serviceIndex, serviceType := range services {
// Add type definitions required by services
d.AddTopLevelDeclaration(streamTypeDeclarations)
servicePath := append(sourcePath, fileDescriptorServiceTagNumber, int32(serviceIndex))
d.BlockComment(c.Comments[file.GetName()][fmt.Sprint(servicePath)])
d.Lf("export interface I%s {", serviceType.GetName())
for methodIndex, method := range serviceType.GetMethod() {
methodPath := append(servicePath, serviceMethodTagNumber, int32(methodIndex))
d.BlockComment(c.Comments[file.GetName()][fmt.Sprint(methodPath)])
if method.GetServerStreaming() {
d.Lf(`%s: { readonly name: "%s"; readonly serverStreaming: true; } & ((request: %s, handler: $stream.ServerStreamHandler<%s>) => $stream.ServerStream<%s>);`,
serviceMethodJSName(method), method.GetName(), interfaceTypeName(c.resolveTypeName(method.GetInputType(), "")), c.resolveTypeName(method.GetOutputType(), ""), c.resolveTypeName(method.GetOutputType(), ""))
} else {
// Note: we don't support the callback style of method calling that
// protobufjs supports - only promises are supported for now.
d.Lf(
`%s: { readonly name: "%s"; readonly serverStreaming: false; } & ((request: %s) => Promise<%s>);`,
serviceMethodJSName(method), method.GetName(), interfaceTypeName(c.resolveTypeName(method.GetInputType(), "")), c.resolveTypeName(method.GetOutputType(), ""))
}
}
d.L("}")
d.Lf("export class %s extends $protobuf.rpc.Service implements I%s {", serviceType.GetName(), serviceType.GetName())
j.Lf("%s.%s = (() => {", curNS, serviceType.GetName())
j.Lf("class %s extends $protobuf.rpc.Service {", serviceType.GetName())
d.L("constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);")
j.L("constructor(rpcImpl, requestDelimited = false, responseDelimited = false) {")
j.Lf("super(rpcImpl, requestDelimited, responseDelimited);")
j.L("}")
d.Lf("static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): %s;", serviceType.GetName())
j.L("static create(rpcImpl, requestDelimited = false, responseDelimited = false) {")
j.Lf("return new %s(rpcImpl, requestDelimited, responseDelimited);", serviceType.GetName())
j.L("}")
for _, method := range serviceType.GetMethod() {
d.Lf(`%s: I%s["%s"];`, serviceMethodJSName(method), serviceType.GetName(), serviceMethodJSName(method))
}
// End class definition
d.L("}")
j.L("}")
// Define service methods on class prototype, including readonly "name" prop
for _, method := range serviceType.GetMethod() {
if method.GetServerStreaming() {
j.Lf(
"Object.defineProperty(%s.prototype.%s = function %s(request, handler) {",
serviceType.GetName(), serviceMethodJSName(method), serviceMethodJSName(method))
j.Lf("if (!handler) throw TypeError('stream handler is required for server-streaming RPC');")
j.Lf(`if (!handler.next) throw TypeError("stream handler is missing 'next' callback property");`)
j.Lf("const controller = new AbortController();")
j.Lf("const stream = { cancel: () => controller.abort() };")
j.Lf("const callback = (error, data) => {")
// Ignore AbortError
j.Lf("if (error) {")
j.Lf("if (typeof error === 'object' && error.name === 'AbortError') {")
j.Lf("return; // stream canceled")
j.Lf("}")
j.Lf("handler.error(error)")
j.Lf("} else if (data) {")
j.Lf("handler.next(data);")
j.Lf("}")
j.Lf("}")
// Hack: temporarily patch rpcImpl to receive an extra options parameter
// indicating that this is a server-streaming RPC. This means that we
// will invoke the callback multiple times.
j.Lf(`const originalRPCImpl = this.rpcImpl;`)
j.Lf("const streamParams = { serverStream: true, complete: () => handler.complete(), signal: controller.signal };")
j.Lf(`this.rpcImpl = (method, data, callback) => originalRPCImpl(method, data, callback, streamParams);`)
j.Lf("try {")
j.Lf("this.rpcCall(%s, %s, %s, request, callback);", serviceMethodJSName(method), c.resolveTypeName(method.GetInputType(), "$root."), c.resolveTypeName(method.GetOutputType(), "$root."))
j.Lf("return stream;")
j.Lf("} finally {")
j.Lf("this.rpcImpl = originalRPCImpl;")
j.Lf("}")
} else {
// Assume unary
j.Lf(
"Object.defineProperty(%s.prototype.%s = function %s(request) {",
serviceType.GetName(), serviceMethodJSName(method), serviceMethodJSName(method))
j.Lf("return this.rpcCall(%s, %s, %s, request);", serviceMethodJSName(method), c.resolveTypeName(method.GetInputType(), "$root."), c.resolveTypeName(method.GetOutputType(), "$root."))
}
j.Lf(`}, "name", { value: "%s" });`, method.GetName())
j.Lf(
`Object.defineProperty(%s.prototype.%s, "serverStreaming", { value: %t });`,
serviceType.GetName(), serviceMethodJSName(method), method.GetServerStreaming())
}
j.Lf("return %s;", serviceType.GetName())
j.L("})();")
}
}
// resolveTypeName accepts a fully-qualified proto type name such as
// ".my.package.MyMessage.MyNestedEnum" and resolves it to a fully qualified
// TypeScript symbol.
//
// If the symbol exists in the local file, the given "localRootPrefix" is
// prepended instead of importing a file. The $root prefix is needed to ensure
// an absolute symbol reference, i.e. to avoid accidentally referencing a symbol
// in the current scope.
//
// The localRootPrefix should be set to "$root." and only when generating JS
// code, because TypeScript declarations do not need the "$root" prefix to
// figure out the right type.
// TODO: test this assumption - is this accurate?
func (c *Codegen) resolveTypeName(name string, localRootPrefix string) string {
importFile := c.Index.Files[c.Index.FilesByType[name].GetName()]
for _, path := range c.Paths {
// Type will be generated in the current output file; no need to import.
if path == importFile.GetName() {
return localRootPrefix + name[1:]
}
}
if importFile == nil {
fatalf("could not resolve import for %s")
}
if _, ok := importPaths[importFile.GetName()]; !ok && *strictImportsFlag {
fatalf("-strict_imports failure: missing %q in -import_path entries %s", importFile.GetName(), *importPathFlag)
}
// Import the type, possibly with aliasing.
resolvedImportPath := strings.TrimSuffix(importFile.GetName(), ".proto")
// logf("prefixed import path (before prefixing): %s", prefixedImportPath)
for protoPath, tsPath := range importPaths {
if protoPath == importFile.GetName() {
resolvedImportPath = tsPath
break
}
if strings.HasSuffix(protoPath, "/") && strings.HasPrefix(resolvedImportPath, protoPath) {
resolvedImportPath = filepath.Join(tsPath, strings.TrimPrefix(resolvedImportPath, protoPath))
// logf("prefixed import path for %s -> %s", importFile.GetName(), prefixedImportPath)
break
}
}
importRelPath, err := filepath.Rel(filepath.Join(".", filepath.Dir(c.Out)), filepath.Join(".", resolvedImportPath))
if err != nil {
fatalf("failed to compute relpath: %s", err)
}
if !strings.HasPrefix(importRelPath, ".") {
importRelPath = "./" + importRelPath
}
alias := ""
if c.ImportedSymbols[importRelPath] != "" {
alias = c.ImportedSymbols[importRelPath]
}
importPkg := strings.Split(name, ".")[1]
// To keep things simple for now, alias all imported symbols even if they
// don't conflict with any symbols in the scopes where they are referenced.
if alias == "" {
i := 0
for i == 0 || (c.ImportedFiles[alias] != "" && c.ImportedFiles[alias] != importRelPath) {
i++
alias = fmt.Sprintf("%s$%d", importPkg, i)
}
c.ImportedFiles[alias] = importRelPath
c.ImportedSymbols[importRelPath] = alias
c.d.Import(importRelPath, importPkg, alias)
c.j.Import(importRelPath, importPkg, alias)
}
parts := strings.Split(name, ".")
parts[1] = alias
resolved := strings.Join(parts[1:], ".")
return resolved
}
func (c *Codegen) typeAnnotation(f *descriptorpb.FieldDescriptorProto) string {
if c.isMapField(f) {
entryType := c.Index.MessageTypes[f.GetTypeName()]
kf := entryType.GetField()[0]
vf := entryType.GetField()[1]
return fmt.Sprintf("Record<%s, %s>", c.presentSingularTypeAnnotation(kf), c.presentSingularTypeAnnotation(vf))
}
if f.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REPEATED {
return fmt.Sprintf("Array<%s>", c.presentSingularTypeAnnotation(f))
}
return c.singularTypeAnnotation(f)
}
func (c *Codegen) singularTypeAnnotation(f *descriptorpb.FieldDescriptorProto) string {
a := c.presentSingularTypeAnnotation(f)
if f.GetProto3Optional() {
a += " | null | undefined /* optional */"
} else if f.GetType() == descriptorpb.FieldDescriptorProto_TYPE_MESSAGE {
a += " | null | undefined"
}
return a
}
func (c *Codegen) presentSingularTypeAnnotation(f *descriptorpb.FieldDescriptorProto) string {
if isLong(f.GetType()) {
c.d.DefaultImport("long", "Long")
c.j.DefaultImport("long", "Long")
return "Long"
}
switch f.GetType() {
case descriptorpb.FieldDescriptorProto_TYPE_DOUBLE,
descriptorpb.FieldDescriptorProto_TYPE_FLOAT,
descriptorpb.FieldDescriptorProto_TYPE_UINT32,
descriptorpb.FieldDescriptorProto_TYPE_INT32,
descriptorpb.FieldDescriptorProto_TYPE_FIXED32,
descriptorpb.FieldDescriptorProto_TYPE_SFIXED32,
descriptorpb.FieldDescriptorProto_TYPE_SINT32:
return "number"
case descriptorpb.FieldDescriptorProto_TYPE_BOOL:
return "boolean"
case descriptorpb.FieldDescriptorProto_TYPE_BYTES:
return "Uint8Array"
case descriptorpb.FieldDescriptorProto_TYPE_STRING:
return "string"
case descriptorpb.FieldDescriptorProto_TYPE_ENUM:
return c.resolveTypeName(f.GetTypeName(), "")
case descriptorpb.FieldDescriptorProto_TYPE_MESSAGE:
// TODO: support --noforce-message to allow interface types here?
return c.resolveTypeName(f.GetTypeName(), "")
default:
typeName := f.GetTypeName()