-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
gen.go
2722 lines (2404 loc) 路 81.8 KB
/
gen.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
// Copyright 2016-2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Pulling out some of the repeated strings tokens into constants would harm readability, so we just ignore the
// goconst linter's warning.
//
// nolint: lll, goconst
package nodejs
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"path"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/pkg/v3/codegen/testing/tstypes"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
)
// The minimum version of @pulumi/pulumi compatible with the generated SDK.
const MinimumValidSDKVersion string = "^3.42.0"
const MinimumTypescriptVersion string = "^4.3.5"
const MinimumNodeTypesVersion string = "^14"
type typeDetails struct {
outputType bool
inputType bool
usedInFunctionOutputVersionInputs bool // helps decide naming under the tfbridge20 flag
}
// title capitalizes the first rune in s.
//
// Examples:
// "hello" => "Hello"
// "hiAlice" => "HiAlice"
// "hi.Bob" => "Hi.Bob"
//
// Note: This is expected to work on strings which are not valid identifiers.
func title(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
return string(append([]rune{unicode.ToUpper(runes[0])}, runes[1:]...))
}
// camel converts s to camel case.
//
// Examples:
// "helloWorld" => "helloWorld"
// "HelloWorld" => "helloWorld"
// "JSONObject" => "jsonobject"
// "My-FRIEND.Bob" => "my-FRIEND.Bob"
func camel(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
res := make([]rune, 0, len(runes))
for i, r := range runes {
if unicode.IsLower(r) {
res = append(res, runes[i:]...)
break
}
res = append(res, unicode.ToLower(r))
}
return string(res)
}
// pascal converts s to pascal case. Word breaks are signified by illegal
// identifier runes (excluding '.'). These are found by use of
// isLegalIdentifierPart.
//
// Examples:
// "My-Friend.Bob" => "MyFriend.Bob"
// "JSONObject" => "JSONObject"'
// "a-glad-dayTime" => "AGladDayTime"
//
// Note: because camel aggressively down-cases the first continuous sub-string
// of uppercase characters, we cannot define pascal as title(camel(x)).
func pascal(s string) string {
split := [][]rune{{}}
runes := []rune(s)
for _, r := range runes {
if !isLegalIdentifierPart(r) && r != '.' {
split = append(split, []rune{})
} else {
split[len(split)-1] = append(split[len(split)-1], r)
}
}
words := make([]string, len(split))
for i, v := range split {
words[i] = title(string(v))
}
return strings.Join(words, "")
}
// externalModuleName Formats the name of package to comply with an external
// module.
func externalModuleName(s string) string {
return fmt.Sprintf("pulumi%s", pascal(s))
}
type modContext struct {
pkg schema.PackageReference
mod string
types []*schema.ObjectType
enums []*schema.EnumType
resources []*schema.Resource
functions []*schema.Function
typeDetails map[*schema.ObjectType]*typeDetails
children []*modContext
extraSourceFiles []string
tool string
// Name overrides set in NodeJSInfo
modToPkg map[string]string // Module name -> package name
compatibility string // Toggle compatibility mode for a specified target.
disableUnionOutputTypes bool // Disable unions in output types.
// Determine whether to lift single-value method return values
liftSingleValueMethodReturns bool
}
func (mod *modContext) String() string {
return mod.mod
}
func (mod *modContext) details(t *schema.ObjectType) *typeDetails {
details, ok := mod.typeDetails[t]
if !ok {
details = &typeDetails{}
if mod.typeDetails == nil {
mod.typeDetails = map[*schema.ObjectType]*typeDetails{}
}
mod.typeDetails[t] = details
}
return details
}
func (mod *modContext) tokenToModName(tok string) string {
components := strings.Split(tok, ":")
contract.Assertf(len(components) == 3, "malformed token %v", tok)
modName := mod.pkg.TokenToModule(tok)
if override, ok := mod.modToPkg[modName]; ok {
modName = override
}
if modName != "" {
modName = strings.Replace(modName, "/", ".", -1) + "."
}
return modName
}
func (mod *modContext) namingContext(pkg schema.PackageReference) (namingCtx *modContext, pkgName string, external bool) {
namingCtx = mod
if pkg != nil && !codegen.PkgEquals(pkg, mod.pkg) {
external = true
pkgName = pkg.Name() + "."
var info NodePackageInfo
def, err := pkg.Definition()
contract.AssertNoError(err)
contract.AssertNoError(def.ImportLanguages(map[string]schema.Language{"nodejs": Importer}))
if v, ok := def.Language["nodejs"].(NodePackageInfo); ok {
info = v
}
namingCtx = &modContext{
pkg: pkg,
modToPkg: info.ModuleToPackage,
compatibility: info.Compatibility,
}
}
return
}
func (mod *modContext) objectType(pkg schema.PackageReference, details *typeDetails, tok string, input, args, enum bool) string {
root := "outputs."
if input {
root = "inputs."
}
namingCtx, pkgName, external := mod.namingContext(pkg)
if external {
pkgName = externalModuleName(pkgName)
root = "types.output."
if input {
root = "types.input."
}
}
modName, name := namingCtx.tokenToModName(tok), tokenToName(tok)
if enum {
prefix := "enums."
if external {
prefix = pkgName
}
return prefix + modName + title(name)
}
if args && input && details != nil && details.usedInFunctionOutputVersionInputs {
name += "Args"
} else if args && namingCtx.compatibility != tfbridge20 && namingCtx.compatibility != kubernetes20 {
name += "Args"
}
return pkgName + root + modName + title(name)
}
func (mod *modContext) resourceType(r *schema.ResourceType) string {
if strings.HasPrefix(r.Token, "pulumi:providers:") {
pkgName := strings.TrimPrefix(r.Token, "pulumi:providers:")
if pkgName != mod.pkg.Name() {
pkgName = externalModuleName(pkgName)
}
return fmt.Sprintf("%s.Provider", pkgName)
}
pkg := mod.pkg
if r.Resource != nil {
pkg = r.Resource.PackageReference
}
namingCtx, pkgName, external := mod.namingContext(pkg)
if !external {
name := tokenToName(r.Token)
return title(name)
}
pkgName = externalModuleName(pkgName)
modName, name := namingCtx.tokenToModName(r.Token), tokenToName(r.Token)
return pkgName + modName + title(name)
}
func tokenToName(tok string) string {
components := strings.Split(tok, ":")
contract.Assertf(len(components) == 3, "malformed token %v", tok)
return title(components[2])
}
func resourceName(r *schema.Resource) string {
if r.IsProvider {
return "Provider"
}
return tokenToName(r.Token)
}
func (mod *modContext) resourceFileName(r *schema.Resource) string {
fileName := camel(resourceName(r)) + ".ts"
if mod.isReservedSourceFileName(fileName) {
fileName = camel(resourceName(r)) + "_.ts"
}
return fileName
}
func tokenToFunctionName(tok string) string {
return camel(tokenToName(tok))
}
func (mod *modContext) typeAst(t schema.Type, input bool, constValue interface{}) tstypes.TypeAst {
switch t := t.(type) {
case *schema.OptionalType:
return tstypes.Union(
mod.typeAst(t.ElementType, input, constValue),
tstypes.Identifier("undefined"),
)
case *schema.InputType:
typ := mod.typeString(codegen.SimplifyInputUnion(t.ElementType), input, constValue)
if typ == "any" {
return tstypes.Identifier("any")
}
return tstypes.Identifier(fmt.Sprintf("pulumi.Input<%s>", typ))
case *schema.EnumType:
return tstypes.Identifier(mod.objectType(t.PackageReference, nil, t.Token, input, false, true))
case *schema.ArrayType:
return tstypes.Array(mod.typeAst(t.ElementType, input, constValue))
case *schema.MapType:
return tstypes.StringMap(mod.typeAst(t.ElementType, input, constValue))
case *schema.ObjectType:
details := mod.details(t)
return tstypes.Identifier(mod.objectType(t.PackageReference, details, t.Token, input, t.IsInputShape(), false))
case *schema.ResourceType:
return tstypes.Identifier(mod.resourceType(t))
case *schema.TokenType:
return tstypes.Identifier(tokenToName(t.Token))
case *schema.UnionType:
if !input && mod.disableUnionOutputTypes {
if t.DefaultType != nil {
return mod.typeAst(t.DefaultType, input, constValue)
}
return tstypes.Identifier("any")
}
elements := make([]tstypes.TypeAst, len(t.ElementTypes))
for i, e := range t.ElementTypes {
elements[i] = mod.typeAst(e, input, constValue)
}
return tstypes.Union(elements...)
default:
switch t {
case schema.BoolType:
return tstypes.Identifier("boolean")
case schema.IntType, schema.NumberType:
return tstypes.Identifier("number")
case schema.StringType:
if constValue != nil {
return tstypes.Identifier(fmt.Sprintf("%q", constValue.(string)))
}
return tstypes.Identifier("string")
case schema.ArchiveType:
return tstypes.Identifier("pulumi.asset.Archive")
case schema.AssetType:
return tstypes.Union(
tstypes.Identifier("pulumi.asset.Asset"),
tstypes.Identifier("pulumi.asset.Archive"),
)
case schema.JSONType:
fallthrough
case schema.AnyType:
return tstypes.Identifier("any")
}
}
panic(fmt.Errorf("unexpected type %T", t))
}
func (mod *modContext) typeString(t schema.Type, input bool, constValue interface{}) string {
return tstypes.TypeLiteral(tstypes.Normalize(mod.typeAst(t, input, constValue)))
}
func isStringType(t schema.Type) bool {
t = codegen.UnwrapType(t)
switch typ := t.(type) {
case *schema.TokenType:
t = typ.UnderlyingType
case *schema.EnumType:
t = typ.ElementType
case *schema.UnionType:
// The following case detects for relaxed string enums. If it's a Union, check if one ElementType is an EnumType.
// If yes, t is the ElementType of the EnumType.
for _, tt := range typ.ElementTypes {
t = codegen.UnwrapType(tt)
if typ, ok := t.(*schema.EnumType); ok {
t = typ.ElementType
}
}
}
return t == schema.StringType
}
func sanitizeComment(str string) string {
return strings.Replace(str, "*/", "*/", -1)
}
func printComment(w io.Writer, comment, deprecationMessage, indent string) {
if comment == "" && deprecationMessage == "" {
return
}
lines := strings.Split(sanitizeComment(comment), "\n")
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
fmt.Fprintf(w, "%s/**\n", indent)
for _, l := range lines {
if l == "" {
fmt.Fprintf(w, "%s *\n", indent)
} else {
fmt.Fprintf(w, "%s * %s\n", indent, l)
}
}
if deprecationMessage != "" {
if len(lines) > 0 {
fmt.Fprintf(w, "%s *\n", indent)
}
fmt.Fprintf(w, "%s * @deprecated %s\n", indent, deprecationMessage)
}
fmt.Fprintf(w, "%s */\n", indent)
}
// Generates a plain interface type.
//
// We use this to represent both argument and plain object types.
func (mod *modContext) genPlainType(w io.Writer, name, comment string,
properties []*schema.Property, input, readonly bool, level int) error {
indent := strings.Repeat(" ", level)
printComment(w, comment, "", indent)
fmt.Fprintf(w, "%sexport interface %s {\n", indent, name)
for _, p := range properties {
printComment(w, p.Comment, p.DeprecationMessage, indent+" ")
prefix := ""
if readonly {
prefix = "readonly "
}
sigil, propertyType := "", p.Type
if !p.IsRequired() {
sigil, propertyType = "?", codegen.RequiredType(p)
}
typ := mod.typeString(propertyType, input, p.ConstValue)
fmt.Fprintf(w, "%s %s%s%s: %s;\n", indent, prefix, p.Name, sigil, typ)
}
fmt.Fprintf(w, "%s}\n", indent)
return nil
}
// Generate a provide defaults function for an associated plain object.
func (mod *modContext) genPlainObjectDefaultFunc(w io.Writer, name string,
properties []*schema.Property, input, readonly bool, level int) error {
indent := strings.Repeat(" ", level)
defaults := []string{}
for _, p := range properties {
if p.DefaultValue != nil {
dv, err := mod.getDefaultValue(p.DefaultValue, codegen.UnwrapType(p.Type))
if err != nil {
return err
}
defaults = append(defaults, fmt.Sprintf("%s: (val.%s) ?? %s", p.Name, p.Name, dv))
} else if funcName := mod.provideDefaultsFuncName(p.Type, input); funcName != "" {
// ProvideDefaults functions have the form `(Input<shape> | undefined) ->
// Output<shape> | undefined`. We need to disallow the undefined. This is safe
// because val.%arg existed in the input (type system enforced).
var compositeObject string
if codegen.IsNOptionalInput(p.Type) {
compositeObject = fmt.Sprintf("pulumi.output(val.%s).apply(%s)", p.Name, funcName)
} else {
compositeObject = fmt.Sprintf("%s(val.%s)", funcName, p.Name)
}
if !p.IsRequired() {
compositeObject = fmt.Sprintf("(val.%s ? %s : undefined)", p.Name, compositeObject)
}
defaults = append(defaults, fmt.Sprintf("%s: %s", p.Name, compositeObject))
}
}
// There are no defaults, so don't generate a default function.
if len(defaults) == 0 {
return nil
}
// Generates a function header that looks like this:
// export function %sProvideDefaults(val: pulumi.Input<%s> | undefined): pulumi.Output<%s> | undefined {
// const def = (val: LayeredTypeArgs) => ({
// ...val,
defaultProvderName := provideDefaultsFuncNameFromName(name)
printComment(w, fmt.Sprintf("%s sets the appropriate defaults for %s",
defaultProvderName, name), "", indent)
fmt.Fprintf(w, "%sexport function %s(val: %s): "+
"%s {\n", indent, defaultProvderName, name, name)
fmt.Fprintf(w, "%s return {\n", indent)
fmt.Fprintf(w, "%s ...val,\n", indent)
// Fields look as follows
// %s: (val.%s) ?? devValue,
for _, val := range defaults {
fmt.Fprintf(w, "%s %s,\n", indent, val)
}
fmt.Fprintf(w, "%s };\n", indent)
fmt.Fprintf(w, "%s}\n", indent)
return nil
}
// The name of the helper function used to provide default values to plain
// types, derived purely from the name of the enclosing type. Prefer to use
// provideDefaultsFuncName when full type information is available.
func provideDefaultsFuncNameFromName(typeName string) string {
var i int
if in := strings.LastIndex(typeName, "."); in != -1 {
i = in
}
// path + camel(name) + ProvideDefaults suffix
return typeName[:i] + camel(typeName[i:]) + "ProvideDefaults"
}
// The name of the function used to set defaults on the plain type.
//
// `type` is the type which the function applies to.
// `input` indicates whither `type` is an input type.
func (mod *modContext) provideDefaultsFuncName(typ schema.Type, input bool) string {
if !codegen.IsProvideDefaultsFuncRequired(typ) {
return ""
}
requiredType := codegen.UnwrapType(typ)
typeName := mod.typeString(requiredType, input, nil)
return provideDefaultsFuncNameFromName(typeName)
}
func tsPrimitiveValue(value interface{}) (string, error) {
v := reflect.ValueOf(value)
if v.Kind() == reflect.Interface {
v = v.Elem()
}
switch v.Kind() {
case reflect.Bool:
if v.Bool() {
return "true", nil
}
return "false", nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
return strconv.FormatInt(v.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:
return strconv.FormatUint(v.Uint(), 10), nil
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(v.Float(), 'f', -1, 64), nil
case reflect.String:
return fmt.Sprintf("%q", v.String()), nil
default:
return "", fmt.Errorf("unsupported default value of type %T", value)
}
}
func (mod *modContext) getConstValue(cv interface{}) (string, error) {
if cv == nil {
return "", nil
}
return tsPrimitiveValue(cv)
}
func (mod *modContext) getDefaultValue(dv *schema.DefaultValue, t schema.Type) (string, error) {
var val string
if dv.Value != nil {
v, err := tsPrimitiveValue(dv.Value)
if err != nil {
return "", err
}
val = v
}
if len(dv.Environment) != 0 {
getType := ""
switch t {
case schema.BoolType:
getType = "Boolean"
case schema.IntType, schema.NumberType:
getType = "Number"
}
envVars := fmt.Sprintf("%q", dv.Environment[0])
for _, e := range dv.Environment[1:] {
envVars += fmt.Sprintf(", %q", e)
}
cast := ""
if t != schema.StringType && getType == "" {
cast = "<any>"
}
getEnv := fmt.Sprintf("%sutilities.getEnv%s(%s)", cast, getType, envVars)
if val != "" {
val = fmt.Sprintf("(%s || %s)", getEnv, val)
} else {
val = getEnv
}
}
return val, nil
}
func (mod *modContext) genAlias(w io.Writer, alias *schema.Alias) {
fmt.Fprintf(w, "{ ")
var parts []string
if alias.Name != nil {
parts = append(parts, fmt.Sprintf("name: \"%v\"", *alias.Name))
}
if alias.Project != nil {
parts = append(parts, fmt.Sprintf("project: \"%v\"", *alias.Project))
}
if alias.Type != nil {
parts = append(parts, fmt.Sprintf("type: \"%v\"", *alias.Type))
}
for i, part := range parts {
if i > 0 {
fmt.Fprintf(w, ", ")
}
fmt.Fprintf(w, "%s", part)
}
fmt.Fprintf(w, " }")
}
func (mod *modContext) genResource(w io.Writer, r *schema.Resource) (resourceFileInfo, error) {
info := resourceFileInfo{}
// Create a resource module file into which all of this resource's types will go.
name := resourceName(r)
info.resourceClassName = name
// Write the TypeDoc/JSDoc for the resource class
printComment(w, codegen.FilterExamples(r.Comment, "typescript"), r.DeprecationMessage, "")
var baseType, optionsType string
switch {
case r.IsComponent:
baseType, optionsType = "ComponentResource", "ComponentResourceOptions"
case r.IsProvider:
baseType, optionsType = "ProviderResource", "ResourceOptions"
default:
baseType, optionsType = "CustomResource", "CustomResourceOptions"
}
// Begin defining the class.
fmt.Fprintf(w, "export class %s extends pulumi.%s {\n", info.resourceClassName, baseType)
// Emit a static factory to read instances of this resource unless this is a provider resource or ComponentResource.
stateType := name + "State"
if !r.IsProvider && !r.IsComponent {
fmt.Fprintf(w, " /**\n")
fmt.Fprintf(w, " * Get an existing %s resource's state with the given name, ID, and optional extra\n", name)
fmt.Fprintf(w, " * properties used to qualify the lookup.\n")
fmt.Fprintf(w, " *\n")
fmt.Fprintf(w, " * @param name The _unique_ name of the resulting resource.\n")
fmt.Fprintf(w, " * @param id The _unique_ provider ID of the resource to lookup.\n")
// TODO: Document id format: https://github.com/pulumi/pulumi/issues/4754
if r.StateInputs != nil {
fmt.Fprintf(w, " * @param state Any extra arguments used during the lookup.\n")
}
fmt.Fprintf(w, " * @param opts Optional settings to control the behavior of the CustomResource.\n")
fmt.Fprintf(w, " */\n")
stateParam, stateRef := "", "undefined as any, "
if r.StateInputs != nil {
stateParam, stateRef = fmt.Sprintf("state?: %s, ", stateType), "<any>state, "
}
fmt.Fprintf(w, " public static get(name: string, id: pulumi.Input<pulumi.ID>, %sopts?: pulumi.%s): %s {\n",
stateParam, optionsType, name)
if r.DeprecationMessage != "" && mod.compatibility != kubernetes20 {
fmt.Fprintf(w, " pulumi.log.warn(\"%s is deprecated: %s\")\n", name, escape(r.DeprecationMessage))
}
fmt.Fprintf(w, " return new %s(name, %s{ ...opts, id: id });\n", name, stateRef)
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, "\n")
}
pulumiType := r.Token
if r.IsProvider {
pulumiType = mod.pkg.Name()
}
fmt.Fprintf(w, " /** @internal */\n")
fmt.Fprintf(w, " public static readonly __pulumiType = '%s';\n", pulumiType)
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, " /**\n")
fmt.Fprintf(w, " * Returns true if the given object is an instance of %s. This is designed to work even\n", name)
fmt.Fprintf(w, " * when multiple copies of the Pulumi SDK have been loaded into the same process.\n")
fmt.Fprintf(w, " */\n")
fmt.Fprintf(w, " public static isInstance(obj: any): obj is %s {\n", name)
fmt.Fprintf(w, " if (obj === undefined || obj === null) {\n")
fmt.Fprintf(w, " return false;\n")
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, " return obj['__pulumiType'] === %s.__pulumiType;\n", name)
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, "\n")
// Emit all properties (using their output types).
// TODO[pulumi/pulumi#397]: represent sensitive types using a Secret<T> type.
ins := codegen.NewStringSet()
allOptionalInputs := true
for _, prop := range r.InputProperties {
ins.Add(prop.Name)
allOptionalInputs = allOptionalInputs && !prop.IsRequired()
}
for _, prop := range r.Properties {
printComment(w, prop.Comment, prop.DeprecationMessage, " ")
// Make a little comment in the code so it's easy to pick out output properties.
var outcomment string
if !ins.Has(prop.Name) {
outcomment = "/*out*/ "
}
propertyType := prop.Type
if mod.compatibility == kubernetes20 {
propertyType = codegen.RequiredType(prop)
}
fmt.Fprintf(w, " public %sreadonly %s!: pulumi.Output<%s>;\n", outcomment, prop.Name, mod.typeString(propertyType, false, prop.ConstValue))
}
fmt.Fprintf(w, "\n")
// Now create a constructor that chains supercalls and stores into properties.
fmt.Fprintf(w, " /**\n")
fmt.Fprintf(w, " * Create a %s resource with the given unique name, arguments, and options.\n", name)
fmt.Fprintf(w, " *\n")
fmt.Fprintf(w, " * @param name The _unique_ name of the resource.\n")
fmt.Fprintf(w, " * @param args The arguments to use to populate this resource's properties.\n")
fmt.Fprintf(w, " * @param opts A bag of options that control this resource's behavior.\n")
fmt.Fprintf(w, " */\n")
// k8s provider "get" methods don't require args, so make args optional.
if mod.compatibility == kubernetes20 {
allOptionalInputs = true
}
// Write out callable constructor: We only emit a single public constructor, even though we use a private signature
// as well as part of the implementation of `.get`. This is complicated slightly by the fact that, if there is no
// args type, we will emit a constructor lacking that parameter.
var argsFlags string
if allOptionalInputs {
// If the number of required input properties was zero, we can make the args object optional.
argsFlags = "?"
}
argsType := name + "Args"
var trailingBrace string
switch {
case r.IsProvider, r.StateInputs == nil:
trailingBrace = " {"
default:
trailingBrace = ""
}
if r.DeprecationMessage != "" {
fmt.Fprintf(w, " /** @deprecated %s */\n", r.DeprecationMessage)
}
fmt.Fprintf(w, " constructor(name: string, args%s: %s, opts?: pulumi.%s)%s\n", argsFlags, argsType,
optionsType, trailingBrace)
genInputProps := func() error {
for _, prop := range r.InputProperties {
if prop.IsRequired() {
fmt.Fprintf(w, " if ((!args || args.%s === undefined) && !opts.urn) {\n", prop.Name)
fmt.Fprintf(w, " throw new Error(\"Missing required property '%s'\");\n", prop.Name)
fmt.Fprintf(w, " }\n")
}
}
for _, prop := range r.InputProperties {
var arg string
applyDefaults := func(arg string) string {
if name := mod.provideDefaultsFuncName(prop.Type, true /*input*/); name != "" {
var body string
if codegen.IsNOptionalInput(prop.Type) {
body = fmt.Sprintf("pulumi.output(%[2]s).apply(%[1]s)", name, arg)
} else {
body = fmt.Sprintf("%s(%s)", name, arg)
}
return fmt.Sprintf("(%s ? %s : undefined)", arg, body)
}
return arg
}
argValue := applyDefaults(fmt.Sprintf("args.%s", prop.Name))
if prop.Secret {
arg = fmt.Sprintf("args?.%[1]s ? pulumi.secret(%[2]s) : undefined", prop.Name, argValue)
} else {
arg = fmt.Sprintf("args ? %[1]s : undefined", argValue)
}
prefix := " "
if prop.ConstValue != nil {
cv, err := mod.getConstValue(prop.ConstValue)
if err != nil {
return err
}
arg = cv
} else {
if prop.DefaultValue != nil {
dv, err := mod.getDefaultValue(prop.DefaultValue, codegen.UnwrapType(prop.Type))
if err != nil {
return err
}
arg = fmt.Sprintf("(%s) ?? %s", arg, dv)
}
// provider properties must be marshaled as JSON strings.
if r.IsProvider && !isStringType(prop.Type) {
arg = fmt.Sprintf("pulumi.output(%s).apply(JSON.stringify)", arg)
}
}
fmt.Fprintf(w, "%sresourceInputs[\"%s\"] = %s;\n", prefix, prop.Name, arg)
}
for _, prop := range r.Properties {
prefix := " "
if !ins.Has(prop.Name) {
fmt.Fprintf(w, "%sresourceInputs[\"%s\"] = undefined /*out*/;\n", prefix, prop.Name)
}
}
return nil
}
if !r.IsProvider {
if r.StateInputs != nil {
if r.DeprecationMessage != "" {
fmt.Fprintf(w, " /** @deprecated %s */\n", r.DeprecationMessage)
}
// Now write out a general purpose constructor implementation that can handle the public signature as well as the
// signature to support construction via `.get`. And then emit the body preamble which will pluck out the
// conditional state into sensible variables using dynamic type tests.
fmt.Fprintf(w, " constructor(name: string, argsOrState?: %s | %s, opts?: pulumi.%s) {\n",
argsType, stateType, optionsType)
}
if r.DeprecationMessage != "" && mod.compatibility != kubernetes20 {
fmt.Fprintf(w, " pulumi.log.warn(\"%s is deprecated: %s\")\n", name, escape(r.DeprecationMessage))
}
fmt.Fprintf(w, " let resourceInputs: pulumi.Inputs = {};\n")
fmt.Fprintf(w, " opts = opts || {};\n")
if r.StateInputs != nil {
// The lookup case:
fmt.Fprintf(w, " if (opts.id) {\n")
fmt.Fprintf(w, " const state = argsOrState as %[1]s | undefined;\n", stateType)
for _, prop := range r.StateInputs.Properties {
fmt.Fprintf(w, " resourceInputs[\"%[1]s\"] = state ? state.%[1]s : undefined;\n", prop.Name)
}
// The creation case (with args):
fmt.Fprintf(w, " } else {\n")
fmt.Fprintf(w, " const args = argsOrState as %s | undefined;\n", argsType)
err := genInputProps()
if err != nil {
return resourceFileInfo{}, err
}
} else {
// The creation case:
fmt.Fprintf(w, " if (!opts.id) {\n")
err := genInputProps()
if err != nil {
return resourceFileInfo{}, err
}
// The get case:
fmt.Fprintf(w, " } else {\n")
for _, prop := range r.Properties {
fmt.Fprintf(w, " resourceInputs[\"%[1]s\"] = undefined /*out*/;\n", prop.Name)
}
}
} else {
fmt.Fprintf(w, " let resourceInputs: pulumi.Inputs = {};\n")
fmt.Fprintf(w, " opts = opts || {};\n")
fmt.Fprintf(w, " {\n")
err := genInputProps()
if err != nil {
return resourceFileInfo{}, err
}
}
var secretProps []string
for _, prop := range r.Properties {
if prop.Secret {
secretProps = append(secretProps, prop.Name)
}
}
fmt.Fprintf(w, " }\n")
// If the caller didn't request a specific version, supply one using the version of this library.
// If a `pluginDownloadURL` was supplied by the generating schema, we supply a default facility
// much like for version. Both operations are handled in the utilities library.
fmt.Fprint(w, " opts = pulumi.mergeOptions(utilities.resourceOptsDefaults(), opts);\n")
// Now invoke the super constructor with the type, name, and a property map.
if len(r.Aliases) > 0 {
fmt.Fprintf(w, " const aliasOpts = { aliases: [")
for i, alias := range r.Aliases {
if i > 0 {
fmt.Fprintf(w, ", ")
}
mod.genAlias(w, alias)
}
fmt.Fprintf(w, "] };\n")
fmt.Fprintf(w, " opts = pulumi.mergeOptions(opts, aliasOpts);\n")
}
if len(secretProps) > 0 {
fmt.Fprintf(w, ` const secretOpts = { additionalSecretOutputs: ["%s"] };`, strings.Join(secretProps, `", "`))
fmt.Fprintf(w, "\n opts = pulumi.mergeOptions(opts, secretOpts);\n")
}
replaceOnChanges, errList := r.ReplaceOnChanges()
for _, err := range errList {
cmdutil.Diag().Warningf(&diag.Diag{Message: err.Error()})
}
replaceOnChangesStrings := schema.PropertyListJoinToString(replaceOnChanges,
func(x string) string { return x })
if len(replaceOnChanges) > 0 {
fmt.Fprintf(w, ` const replaceOnChanges = { replaceOnChanges: ["%s"] };`, strings.Join(replaceOnChangesStrings, `", "`))
fmt.Fprintf(w, "\n opts = pulumi.mergeOptions(opts, replaceOnChanges);\n")
}
// If it's a ComponentResource, set the remote option.
if r.IsComponent {
fmt.Fprintf(w, " super(%s.__pulumiType, name, resourceInputs, opts, true /*remote*/);\n", name)
} else {
fmt.Fprintf(w, " super(%s.__pulumiType, name, resourceInputs, opts);\n", name)
}
fmt.Fprintf(w, " }\n")
// Generate methods.
genMethod := func(method *schema.Method) {
methodName := camel(method.Name)
fun := method.Function
shouldLiftReturn := mod.liftSingleValueMethodReturns && fun.Outputs != nil && len(fun.Outputs.Properties) == 1
// Write the TypeDoc/JSDoc for the data source function.
fmt.Fprint(w, "\n")
printComment(w, codegen.FilterExamples(fun.Comment, "typescript"), fun.DeprecationMessage, " ")
// Now, emit the method signature.
var args []*schema.Property
var argsig string
argsOptional := true
if fun.Inputs != nil {
// Filter out the __self__ argument from the inputs.
args = make([]*schema.Property, 0, len(fun.Inputs.InputShape.Properties))
for _, arg := range fun.Inputs.InputShape.Properties {
if arg.Name == "__self__" {
continue
}
if arg.IsRequired() {
argsOptional = false
}
args = append(args, arg)
}
if len(args) > 0 {
optFlag := ""
if argsOptional {
optFlag = "?"
}
argsig = fmt.Sprintf("args%s: %s.%sArgs", optFlag, name, title(method.Name))
}
}
var retty string
if fun.Outputs == nil {
retty = "void"
} else if shouldLiftReturn {
retty = fmt.Sprintf("pulumi.Output<%s>", mod.typeString(fun.Outputs.Properties[0].Type, false, nil))
} else {
retty = fmt.Sprintf("pulumi.Output<%s.%sResult>", name, title(method.Name))
}
fmt.Fprintf(w, " %s(%s): %s {\n", methodName, argsig, retty)
if fun.DeprecationMessage != "" {
fmt.Fprintf(w, " pulumi.log.warn(\"%s.%s is deprecated: %s\")\n", name, methodName,
escape(fun.DeprecationMessage))
}
// Zero initialize the args if empty and necessary.
if len(args) > 0 && argsOptional {
fmt.Fprintf(w, " args = args || {};\n")
}
// Now simply call the runtime function with the arguments, returning the results.
var ret string
if fun.Outputs != nil {
if shouldLiftReturn {
ret = fmt.Sprintf("const result: pulumi.Output<%s.%sResult> = ", name, title(method.Name))
} else {
ret = "return "
}
}
fmt.Fprintf(w, " %spulumi.runtime.call(\"%s\", {\n", ret, fun.Token)
if fun.Inputs != nil {
for _, p := range fun.Inputs.InputShape.Properties {
// Pass the argument to the invocation.
if p.Name == "__self__" {
fmt.Fprintf(w, " \"%s\": this,\n", p.Name)
} else {
fmt.Fprintf(w, " \"%[1]s\": args.%[1]s,\n", p.Name)
}
}