-
-
Notifications
You must be signed in to change notification settings - Fork 581
/
Copy pathexportSchema.ts
2202 lines (2083 loc) · 65.3 KB
/
exportSchema.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
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
import { writeFile } from "node:fs/promises";
import type { URL } from "node:url";
import { inspect } from "node:util";
import generate from "@babel/generator";
import { parse } from "@babel/parser";
import type { TemplateBuilderOptions } from "@babel/template";
import template from "@babel/template";
import type { NodePath } from "@babel/traverse";
import traverse from "@babel/traverse";
import * as t from "@babel/types";
import type {
GraphQLArgumentConfig,
GraphQLDirective,
GraphQLDirectiveConfig,
GraphQLEnumTypeConfig,
GraphQLEnumValueConfig,
GraphQLFieldConfig,
GraphQLFieldConfigArgumentMap,
GraphQLFieldConfigMap,
GraphQLInputFieldConfig,
GraphQLInputFieldConfigMap,
GraphQLInputObjectTypeConfig,
GraphQLInterfaceTypeConfig,
GraphQLNamedType,
GraphQLObjectTypeConfig,
GraphQLScalarTypeConfig,
GraphQLSchema,
GraphQLSchemaConfig,
GraphQLType,
GraphQLUnionTypeConfig,
} from "grafast/graphql";
import {
GraphQLEnumType,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLScalarType,
GraphQLUnionType,
isDirective,
isNamedType,
isSchema,
printSchema,
} from "grafast/graphql";
import type { GraphQLSchemaNormalizedConfig } from "graphql/type/schema";
import type { PgSQL, SQL } from "pg-sql2";
import type { ExportOptions } from "./interfaces.js";
import { optimize } from "./optimize/index.js";
import { reservedWords } from "./reservedWords.js";
import { wellKnown } from "./wellKnown.js";
// Cannot import sql because it's optional
// import { sql } from "pg-sql2";
// Instead:
let sql: PgSQL | undefined;
import("pg-sql2").then(
(pgSql2) => {
sql = pgSql2.sql;
},
(_e) => {
// no pg-sql2 module; no matter
},
);
function isSQL(thing: unknown): thing is SQL {
if (sql !== undefined) {
return sql.isSQL(thing);
} else {
// An approximation
if (typeof sql === "object" && sql !== null) {
return Object.getOwnPropertySymbols(thing).some(
(s) => s.description === "pg-sql2-type",
);
} else {
return false;
}
}
}
// Do **NOT** allow variables that start with `__`!
export const canRepresentAsIdentifier = (key: string) =>
/^(?:[a-z$]|_[a-z0-9$])[a-z0-9_$]*$/i.test(key);
function identifierOrLiteral(key: string | number) {
if (typeof key === "number") {
return t.numericLiteral(key);
}
if (canRepresentAsIdentifier(key)) {
return t.identifier(key);
} else {
return t.stringLiteral(key);
}
}
function literal(key: string | number) {
if (typeof key === "number") {
return t.numericLiteral(key);
} else {
return t.stringLiteral(key);
}
}
function locationHintToIdentifierName(locationHint: string): string {
let result = locationHint;
result = result.replace(/[[.]/g, "__").replace(/\]/g, "");
result = result.replace(/[^a-z0-9_]+/gi, "");
result = result.replace(/^([0-9])/, "_$1");
if (result.includes("scope")) {
console.log({ locationHint, result });
}
return result;
}
function getNameForThing(
thing: any,
locationHint: string,
baseNameHint: string,
): string {
if (thing.$exporter$name) {
return thing.$exporter$name;
} else if (typeof thing === "function") {
if (baseNameHint) {
return baseNameHint;
}
const thingName = (thing as any).name ?? (thing as any).displayName ?? null;
if (thingName) {
return (baseNameHint ? baseNameHint + "-" : "") + thingName;
}
return locationHintToIdentifierName(locationHint);
} else {
const thingConstructor = thing.constructor;
const thingConstructorNameRaw =
thingConstructor?.$exporter$name ??
thingConstructor?.name ??
thingConstructor?.displayName ??
null;
const thingConstructorName = ["Array", "Object", "Set", "Map"].includes(
thingConstructorNameRaw,
)
? null
: thingConstructorNameRaw;
const thingName = (thing as any).name ?? (thing as any).displayName ?? null;
const name =
thingConstructorName && thingName
? `${thingName}${thingConstructorName}`
: (thingName ?? thingConstructorName ?? null);
return baseNameHint || name
? (baseNameHint ?? "") + (baseNameHint && name ? "-" : "") + (name ?? "")
: "value";
}
}
function trimDef(def: string): string {
const str = def.replace(/\s+/g, " ");
const PREFIX_LENGTH = 60;
const SUFFIX_LENGTH = 10;
if (str.length < PREFIX_LENGTH + SUFFIX_LENGTH + 10) {
return str;
} else {
return (
str.slice(0, 0 + PREFIX_LENGTH) +
"..." +
str.slice(str.length - SUFFIX_LENGTH)
);
}
}
//const reallyGenerate = (generate as any).default as typeof generate;
const reallyGenerate = generate;
const templateOptions: TemplateBuilderOptions = {
plugins: ["typescript"],
};
export function isNotNullish<T>(input: T | null | undefined): input is T {
return input != null;
}
function isImportable(
thing: unknown,
): thing is { $$export: { moduleName: string; exportName: string } } {
return (
(typeof thing === "object" || typeof thing === "function") &&
thing !== null &&
"$$export" in (thing as object | AnyFunction)
);
}
type AnyFunction = {
(...args: any[]): any;
displayName?: string;
};
type ExportedFromFactory<T, TTuple extends any[]> = T & {
$exporter$args: [...TTuple];
$exporter$factory: (...args: TTuple) => T;
$exporter$name: string | undefined;
};
function isExportedFromFactory<T, TTuple extends any[]>(
thing: T,
): thing is ExportedFromFactory<T, TTuple> {
return (
(typeof thing === "object" || typeof thing === "function") &&
thing !== null &&
"$exporter$factory" in thing
);
}
const BUILTINS = ["Int", "Float", "Boolean", "ID", "String"];
function isBuiltinType(type: GraphQLNamedType): boolean {
return type.name.startsWith("__") || BUILTINS.includes(type.name);
}
const RESERVED_VARIABLES: Record<string, true> = {
// Reserved variables
AbortController: true,
Array: true,
Buffer: true,
DOMException: true,
Error: true,
Event: true,
EventTarget: true,
JSON: true,
Math: true,
MessageChannel: true,
MessageEvent: true,
MessagePort: true,
Object: true,
TextDecoder: true,
TextEncoder: true,
URL: true,
URLSearchParams: true,
WebAssembly: true,
__dirname: true,
__filename: true,
atob: true,
btoa: true,
clearImmediate: true,
clearInterval: true,
clearTimeout: true,
console: true,
exports: true,
global: true,
module: true,
performance: true,
process: true,
queueMicrotask: true,
require: true,
setImmediate: true,
setInterval: true,
setTimeout: true,
structuredClone: true,
};
for (const reservedWord of reservedWords) {
RESERVED_VARIABLES[reservedWord] = true;
}
Object.freeze(RESERVED_VARIABLES);
class CodegenFile {
_variables: {
[name: string]: true;
} = Object.assign(Object.create(null), RESERVED_VARIABLES);
_imports: {
[fromModule: string]: {
[exportName: "default" | "*" | string]: {
variableName: t.Identifier;
asType?: boolean;
};
};
} = Object.create(null);
_types: {
[typeName: string]: {
type: GraphQLNamedType;
variableName: t.Identifier;
declaration: t.Statement | null;
};
} = Object.create(null);
_directives: {
[typeName: string]: {
directive: GraphQLDirective;
variableName: t.Identifier;
declaration: t.Statement | null;
};
} = Object.create(null);
_statements: t.Statement[] = [];
_values: Map<any, t.Expression> = new Map();
_funcToAstCache: Map<AnyFunction, FunctionExpressionIncludingAttributes> =
new Map();
constructor(public options: ExportOptions) {}
addStatements(statements: t.Statement | t.Statement[]): void {
if (Array.isArray(statements)) {
this._statements.push(...statements);
} else {
this._statements.push(statements);
}
}
makeVariable(preferredName: string): t.Identifier {
const allowedName = preferredName.replace(/[^_a-z0-9]+/gi, "_");
for (let i = 0; i < 10000; i++) {
const variableName = allowedName + (i > 0 ? String(i + 1) : "");
if (!this._variables[variableName]) {
this._variables[variableName] = true;
return t.identifier(variableName);
}
}
throw new Error("Could not find a suitable variable name");
}
import(
fromModule: string,
exportNames: "default" | "*" | string | string[] = "default",
asType = false,
): t.Identifier | t.MemberExpression {
if (Array.isArray(exportNames)) {
const [exportName, ...path] = exportNames;
if (!exportName) {
throw new Error("Could not determine the export name");
}
const variable = this.importOnly(fromModule, exportName, asType);
if (path.length) {
let result: t.Node = variable;
for (const pathSegment of path) {
result = t.memberExpression(result, identifierOrLiteral(pathSegment));
}
return result;
} else {
return variable;
}
} else {
const variable = this.importOnly(fromModule, exportNames, asType);
return variable;
}
}
importOnly(
fromModule: string,
exportName: "default" | "*" | string = "default",
asType = false,
): t.Identifier {
const importedModule =
this._imports[fromModule] ??
(this._imports[fromModule] = Object.create(
null,
) as (typeof this._imports)[string]);
const existing = importedModule[exportName];
if (existing) {
if (!asType) {
existing.asType = false;
}
return existing.variableName;
} else {
const preferredName =
exportName === "default" || exportName === "*"
? fromModule
: exportName;
const variableName = this.makeVariable(preferredName);
importedModule[exportName] = {
variableName,
asType,
};
return variableName;
}
}
declareType(type: GraphQLNamedType): t.Identifier {
const existing = this._types[type.name];
if (existing) {
if (existing.type !== type) {
throw new Error("Duplicate types with same name found! Error!");
}
return existing.variableName;
}
if (BUILTINS.includes(type.name)) {
return this.importOnly("graphql", "GraphQL" + type.name);
}
if (isBuiltinType(type)) {
throw new Error(
`declareType called with introspection type '${type.name}'`,
);
}
const VARIABLE_NAME = this.makeVariable(type.name);
const spec: CodegenFile["_types"][string] = {
type,
variableName: VARIABLE_NAME,
declaration: null,
};
this._types[type.name] = spec;
// Must perform declaration _AFTER_ registering type, otherwise we might
// get infinite recursion.
spec.declaration = this.makeTypeDeclaration(type, VARIABLE_NAME);
this.addStatements(spec.declaration);
return VARIABLE_NAME;
}
declareDirective(directive: GraphQLDirective): t.Identifier {
const existing = this._directives[directive.name];
if (existing) {
if (existing.directive !== directive) {
throw new Error("Duplicate types with same name found! Error!");
}
return existing.variableName;
}
const config = directive.toConfig();
const VARIABLE_NAME = this.makeVariable(config.name);
const spec: CodegenFile["_directives"][string] = {
directive,
variableName: VARIABLE_NAME,
declaration: null,
};
this._directives[config.name] = spec;
const locationHint = `@${config.name}`;
// Must perform declaration _AFTER_ registering type, otherwise we might
// get infinite recursion.
const iDirectiveLocation = this.import("graphql", "DirectiveLocation");
spec.declaration = declareGraphQLEntity(
this,
VARIABLE_NAME,
"GraphQLDirective",
{
name: t.stringLiteral(config.name),
description: desc(config.description),
locations: t.arrayExpression(
config.locations.map((l) =>
t.memberExpression(
iDirectiveLocation,
identifierOrLiteral(String(l)),
),
),
),
args:
config.args && Object.keys(config.args).length > 0
? this.makeFieldArgs(
config.args,
`${locationHint}.args`,
`@${config.name}.args`,
)
: null,
isRepeatable: t.booleanLiteral(config.isRepeatable),
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`@${config.name}.extensions`,
),
},
);
this.addStatements(spec.declaration);
return VARIABLE_NAME;
}
private typeExpression(type: GraphQLType): t.Expression {
if (type instanceof GraphQLNonNull) {
const iGraphQLNonNull = this.import("graphql", "GraphQLNonNull");
return t.newExpression(iGraphQLNonNull, [
this.typeExpression(type.ofType),
]);
} else if (type instanceof GraphQLList) {
const iGraphQLList = this.import("graphql", "GraphQLList");
return t.newExpression(iGraphQLList, [this.typeExpression(type.ofType)]);
} else {
return this.declareType(type);
}
}
private makeEnumValue(
config: GraphQLEnumValueConfig,
typeName: string,
enumValueName: string,
): t.Expression {
const locationHint = `${typeName}.values[${JSON.stringify(enumValueName)}]`;
const mappedConfig: {
[key in keyof GraphQLEnumValueConfig as Exclude<
keyof GraphQLEnumValueConfig,
"astNode"
>]-?: t.Expression | null;
} = {
description: desc(config.description),
value: convertToIdentifierViaAST(
this,
config.value,
`${typeName}.${enumValueName}`,
`${locationHint}.value`,
),
extensions: extensions(
this,
config.extensions,
`${locationHint}.extensions`,
`${typeName}.extensions`,
),
deprecationReason: desc(config.deprecationReason),
};
return configToAST(mappedConfig);
}
// For objects and interfaces
private makeObjectFields(
fields: GraphQLFieldConfigMap<any, any>,
typeName: string,
): t.Expression {
const obj = Object.entries(fields).reduce(
(memo, [fieldName, config]) => {
if (!fieldName.startsWith("__")) {
const locationHint = `${typeName}.fields[${fieldName}]`;
const mappedConfig: {
[key in keyof GraphQLFieldConfig<any, any> as Exclude<
keyof GraphQLFieldConfig<any, any>,
"astNode"
>]-?: t.Expression | null;
} = {
description: desc(config.description),
type: this.typeExpression(config.type),
args:
config.args && Object.keys(config.args).length > 0
? this.makeFieldArgs(
config.args,
`${typeName}.fields[${fieldName}].args`,
`${typeName}.${fieldName}`,
)
: null,
resolve: config.resolve
? func(
this,
config.resolve,
`${locationHint}.resolve`,
`${typeName}.${fieldName}.resolve`,
)
: null,
subscribe: config.subscribe
? func(
this,
config.subscribe,
`${locationHint}.subscribe`,
`${typeName}.${fieldName}.subscribe`,
)
: null,
deprecationReason: desc(config.deprecationReason),
extensions: extensions(
this,
config.extensions,
`${locationHint}.extensions`,
`${typeName}.${fieldName}.extensions`,
),
};
memo[fieldName] = configToAST(mappedConfig);
}
return memo;
},
{} as { [key: string]: t.Expression | null },
);
return t.objectExpression(objectToObjectProperties(obj));
}
private makeInputObjectFields(
fields: GraphQLInputFieldConfigMap,
typeName: string,
): t.Expression {
const obj = Object.entries(fields).reduce(
(memo, [fieldName, config]) => {
if (!fieldName.startsWith("__")) {
const locationHint = `${typeName}.fields[${fieldName}]`;
const mappedConfig: {
[key in keyof GraphQLInputFieldConfig as Exclude<
keyof GraphQLInputFieldConfig,
"astNode"
>]-?: t.Expression | null;
} = {
description: desc(config.description),
type: this.typeExpression(config.type),
defaultValue:
config.defaultValue !== undefined
? convertToIdentifierViaAST(
this,
config.defaultValue,
`${typeName}.${fieldName}.defaultValue`,
`${locationHint}.defaultValue`,
)
: null,
deprecationReason: desc(config.deprecationReason),
extensions: extensions(
this,
config.extensions,
`${locationHint}.extensions`,
`${typeName}.${fieldName}.extensions`,
),
};
memo[fieldName] = configToAST(mappedConfig);
}
return memo;
},
{} as { [key: string]: t.Expression | null },
);
return t.objectExpression(objectToObjectProperties(obj));
}
private makeFieldArgs(
args: GraphQLFieldConfigArgumentMap,
baseLocationHint: string,
nameHint: string,
): t.Expression {
const obj = Object.entries(args).reduce(
(memo, [argName, config]) => {
if (!argName.startsWith("__")) {
const locationHint = `${baseLocationHint}[${argName}]`;
const mappedConfig: {
[key in keyof GraphQLArgumentConfig as Exclude<
keyof GraphQLArgumentConfig,
"astNode"
>]-?: t.Expression | null;
} = {
description: desc(config.description),
type: this.typeExpression(config.type),
defaultValue:
config.defaultValue !== undefined
? convertToIdentifierViaAST(
this,
config.defaultValue,
`${nameHint}.${argName}.defaultValue`,
`${locationHint}.defaultValue`,
)
: null,
deprecationReason: desc(config.deprecationReason),
extensions: extensions(
this,
config.extensions,
`${locationHint}.extensions`,
`${nameHint}.${argName}.extensions`,
),
};
memo[argName] = configToAST(mappedConfig);
}
return memo;
},
{} as { [key: string]: t.Expression | null },
);
return t.objectExpression(objectToObjectProperties(obj));
}
private makeTypeDeclaration(
type: GraphQLNamedType,
VARIABLE_NAME: t.Identifier,
): t.Statement {
if (type instanceof GraphQLObjectType) {
const config = type.toConfig();
return declareGraphQLEntity(this, VARIABLE_NAME, "GraphQLObjectType", {
name: t.stringLiteral(config.name),
description: desc(config.description),
isTypeOf: config.isTypeOf
? func(
this,
config.isTypeOf,
`${config.name}.isTypeOf`,
`${config.name}.isTypeOf`,
)
: null,
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`${config.name}.extensions`,
),
fields: t.arrowFunctionExpression(
[],
this.makeObjectFields(config.fields, config.name),
),
interfaces:
config.interfaces.length > 0
? t.arrowFunctionExpression(
[],
t.arrayExpression(
config.interfaces.map((interfaceType) =>
this.declareType(interfaceType),
),
),
)
: null,
});
} else if (type instanceof GraphQLInterfaceType) {
const config = type.toConfig();
return declareGraphQLEntity(this, VARIABLE_NAME, "GraphQLInterfaceType", {
name: t.stringLiteral(config.name),
description: desc(config.description),
resolveType: config.resolveType
? func(
this,
config.resolveType,
`${config.name}.resolveType`,
`${config.name}.resolveType`,
)
: null,
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`${config.name}.extensions`,
),
fields: t.arrowFunctionExpression(
[],
this.makeObjectFields(config.fields, config.name),
),
interfaces:
config.interfaces.length > 0
? t.arrayExpression(
config.interfaces.map((interfaceType) =>
this.declareType(interfaceType),
),
)
: null,
});
} else if (type instanceof GraphQLUnionType) {
const config = type.toConfig();
return declareGraphQLEntity(this, VARIABLE_NAME, "GraphQLUnionType", {
name: t.stringLiteral(config.name),
description: desc(config.description),
resolveType: config.resolveType
? func(
this,
config.resolveType,
`${config.name}.resolveType`,
`${config.name}.resolveType`,
)
: null,
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`${config.name}.extensions`,
),
types: t.arrowFunctionExpression(
[],
t.arrayExpression(config.types.map((t) => this.declareType(t))),
),
});
} else if (type instanceof GraphQLInputObjectType) {
const config = type.toConfig();
return declareGraphQLEntity(
this,
VARIABLE_NAME,
"GraphQLInputObjectType",
{
name: t.stringLiteral(config.name),
description: desc(config.description),
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`${config.name}.extensions`,
),
fields: t.arrowFunctionExpression(
[],
this.makeInputObjectFields(config.fields, config.name),
),
},
);
} else if (type instanceof GraphQLScalarType) {
const config = type.toConfig();
return declareGraphQLEntity(this, VARIABLE_NAME, "GraphQLScalarType", {
name: t.stringLiteral(config.name),
description: desc(config.description),
specifiedByURL: desc(config.specifiedByURL),
serialize: func(
this,
config.serialize,
`${config.name}.serialize`,
`${config.name}.serialize`,
),
parseValue: func(
this,
config.parseValue,
`${config.name}.parseValue`,
`${config.name}.parseValue`,
),
parseLiteral: func(
this,
config.parseLiteral,
`${config.name}.parseLiteral`,
`${config.name}.parseLiteral`,
),
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`${config.name}.extensions`,
),
});
} else if (type instanceof GraphQLEnumType) {
const config = type.toConfig();
return declareGraphQLEntity(this, VARIABLE_NAME, "GraphQLEnumType", {
name: t.stringLiteral(config.name),
description: desc(config.description),
extensions: extensions(
this,
config.extensions,
`${config.name}.extensions`,
`${config.name}.extensions`,
),
values: objectNullPrototype(
Object.entries(config.values).map(([key, value]) =>
t.objectProperty(
identifierOrLiteral(key),
this.makeEnumValue(value, config.name, key),
),
),
),
});
} else {
const never: never = type;
throw new Error(
`Did not understand type: ${(never as any).constructor.name}`,
);
}
}
toAST(): t.File {
const importStatements: t.Statement[] = [];
Object.keys(this._imports)
.sort()
.forEach((moduleName) => {
const importedModule = this._imports[moduleName];
const MODULE_NAME = t.stringLiteral(moduleName);
if (!importedModule) {
return;
}
const {
"*": starImport,
default: defaultImport,
...rest
} = importedModule;
if (starImport) {
const VARIABLE_NAME = starImport.variableName;
importStatements.push(
starImport.asType
? importStarAsType({ MODULE_NAME, VARIABLE_NAME })
: importStar({ MODULE_NAME, VARIABLE_NAME }),
);
}
const exportNames = Object.keys(rest).sort();
if (defaultImport || exportNames.length > 0) {
const importStatement = t.importDeclaration(
[
...(defaultImport
? [t.importDefaultSpecifier(defaultImport.variableName)]
: []),
...(exportNames.length
? exportNames.map((name) =>
t.importSpecifier(
rest[name]!.variableName,
t.identifier(name),
),
)
: []),
],
MODULE_NAME,
);
importStatements.push(importStatement);
}
});
const allStatements = [...importStatements, ...this._statements];
return t.file(t.program(allStatements));
}
}
const importStarAsType = template.statement(
`\
import type VARIABLE_NAME from MODULE_NAME;
`,
templateOptions,
);
/**
* A manual way of doing this (which doesn't seem to work).
*
* ```
* const importStar = template.statement(
* `import * as VARIABLE_NAME from MODULE_NAME;`,
* templateOptions,
* );
* ```
*/
const importStar = (args: {
VARIABLE_NAME: t.Identifier;
MODULE_NAME: t.StringLiteral;
}) =>
t.importDeclaration(
[t.importNamespaceSpecifier(args.VARIABLE_NAME)],
args.MODULE_NAME,
);
const declareConstructorWithConfig = template.statement(
`\
export const VARIABLE_NAME = new CONSTRUCTOR(CONFIG);
`,
templateOptions,
);
type GraphQLEntityName =
| "GraphQLSchema"
| "GraphQLDirective"
| "GraphQLObjectType"
| "GraphQLInterfaceType"
| "GraphQLUnionType"
| "GraphQLInputObjectType"
| "GraphQLScalarType"
| "GraphQLEnumType";
type ConfigForGraphQLEntity<TKey extends GraphQLEntityName> =
TKey extends "GraphQLSchema"
? GraphQLSchemaConfig
: TKey extends "GraphQLDirective"
? GraphQLDirectiveConfig
: TKey extends "GraphQLObjectType"
? GraphQLObjectTypeConfig<unknown, unknown>
: TKey extends "GraphQLInterfaceType"
? GraphQLInterfaceTypeConfig<unknown, unknown>
: TKey extends "GraphQLUnionType"
? GraphQLUnionTypeConfig<unknown, unknown>
: TKey extends "GraphQLInputObjectType"
? GraphQLInputObjectTypeConfig
: TKey extends "GraphQLScalarType"
? GraphQLScalarTypeConfig<unknown, unknown>
: TKey extends "GraphQLEnumType"
? GraphQLEnumTypeConfig
: never;
function declareGraphQLEntity<TKey extends GraphQLEntityName>(
file: CodegenFile,
VARIABLE_NAME: t.Identifier,
constructorName: TKey,
config: {
[key in keyof ConfigForGraphQLEntity<TKey> as Exclude<
keyof ConfigForGraphQLEntity<TKey>,
"astNode" | "extensionASTNodes"
>]-?: t.Expression | null;
},
) {
return declareConstructorWithConfig({
VARIABLE_NAME,
CONSTRUCTOR: file.import("graphql", constructorName),
CONFIG: configToAST(config),
});
}
function desc(description: string | null | undefined): t.Expression | null {
return description ? t.stringLiteral(description) : null;
}
/**
* Returns if the key can be used as a regular object key (and will be seen as
* one of the "own" properties of the object) when created using object literal
* syntax.
*
* I.e. returns `true` unless key is `__proto__`
*
* @see {@link https://tc39.es/ecma262/#sec-runtime-semantics-propertydefinitionevaluation}
*/
function canBeRegularObjectKey(key: string): boolean {
return key !== "__proto__";
}
function _convertToAST(
file: CodegenFile,
thing: unknown,
locationHint: string,
nameHint: string,
depth: number,
reference: t.Expression,
): t.Expression {
const handleSubvalue = (
value: any,
tKey: t.Expression,
key: string | number,
) => {
const existingIdentifier = getExistingIdentifier(file, value);
if (existingIdentifier) {
return existingIdentifier;
} else if (isExportedFromFactory(value)) {
const val = convertToIdentifierViaAST(
file,
value,
nameHint + `.${key}`,
locationHint + `[${JSON.stringify(key)}]`,
depth + 1,
);
return val;
} else {
const newReference = t.memberExpression(
reference,
tKey,
!t.isIdentifier(tKey),
);
file._values.set(value, newReference);