@contello/client 2.2.2 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +15 -14
- package/dist/cli.js.map +1 -0
- package/dist/generate-DIoN94iO.js +1068 -0
- package/dist/generate-DIoN94iO.js.map +1 -0
- package/dist/index.cjs +897 -1103
- package/dist/index.d.cts +118 -119
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.ts +119 -119
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +887 -1055
- package/dist/index.js.map +1 -0
- package/package.json +4 -3
- package/dist/generate-Z4LVDAB4.js +0 -1241
|
@@ -1,1241 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// src/generate/index.ts
|
|
4
|
-
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
5
|
-
import { glob } from "fs/promises";
|
|
6
|
-
import { dirname, relative, resolve as resolve2 } from "path";
|
|
7
|
-
import { Kind as Kind5, Source, parse as parse2, visit } from "graphql";
|
|
8
|
-
|
|
9
|
-
// src/generate/config.ts
|
|
10
|
-
import { resolve } from "path";
|
|
11
|
-
import { pathToFileURL } from "url";
|
|
12
|
-
var CONFIG_NAMES = ["contello.config.ts", "contello.config.js", "contello.config.mjs"];
|
|
13
|
-
async function loadConfig(cwd) {
|
|
14
|
-
for (const name of CONFIG_NAMES) {
|
|
15
|
-
const configPath = resolve(cwd, name);
|
|
16
|
-
try {
|
|
17
|
-
const mod = await import(pathToFileURL(configPath).href);
|
|
18
|
-
const config = mod.default ?? mod;
|
|
19
|
-
if (!config.projects || !Array.isArray(config.projects)) {
|
|
20
|
-
throw new Error(`${name}: expected "projects" to be an array`);
|
|
21
|
-
}
|
|
22
|
-
for (const [i, project] of config.projects.entries()) {
|
|
23
|
-
if (!project.url) throw new Error(`${name}: projects[${i}].url is required`);
|
|
24
|
-
if (!project.project) throw new Error(`${name}: projects[${i}].project is required`);
|
|
25
|
-
if (!project.token) throw new Error(`${name}: projects[${i}].token is required`);
|
|
26
|
-
if (!project.documents) throw new Error(`${name}: projects[${i}].documents is required`);
|
|
27
|
-
if (!project.output) throw new Error(`${name}: projects[${i}].output is required`);
|
|
28
|
-
}
|
|
29
|
-
return config;
|
|
30
|
-
} catch (error) {
|
|
31
|
-
if (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "ENOENT") {
|
|
32
|
-
continue;
|
|
33
|
-
}
|
|
34
|
-
throw error;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
throw new Error(`no config file found (tried: ${CONFIG_NAMES.join(", ")})`);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// src/generate/documents.ts
|
|
41
|
-
import {
|
|
42
|
-
Kind,
|
|
43
|
-
NoFragmentCyclesRule,
|
|
44
|
-
NoUnusedFragmentsRule,
|
|
45
|
-
getLocation,
|
|
46
|
-
print,
|
|
47
|
-
specifiedRules,
|
|
48
|
-
validate
|
|
49
|
-
} from "graphql";
|
|
50
|
-
var SUPPRESSED_RULE_NAMES = /* @__PURE__ */ new Set([NoFragmentCyclesRule.name, NoUnusedFragmentsRule.name]);
|
|
51
|
-
var VALIDATION_RULES = specifiedRules.filter((rule) => !SUPPRESSED_RULE_NAMES.has(rule.name));
|
|
52
|
-
function collectFragments(documents) {
|
|
53
|
-
const fragments = /* @__PURE__ */ new Map();
|
|
54
|
-
for (const doc of documents) {
|
|
55
|
-
for (const def of doc.definitions) {
|
|
56
|
-
if (def.kind === Kind.FRAGMENT_DEFINITION) {
|
|
57
|
-
fragments.set(def.name.value, def);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
return fragments;
|
|
62
|
-
}
|
|
63
|
-
function collectOperations(documents) {
|
|
64
|
-
const operations = [];
|
|
65
|
-
const seen = /* @__PURE__ */ new Set();
|
|
66
|
-
for (const doc of documents) {
|
|
67
|
-
for (const def of doc.definitions) {
|
|
68
|
-
if (def.kind === Kind.OPERATION_DEFINITION) {
|
|
69
|
-
if (!def.name) {
|
|
70
|
-
throw new Error(`unnamed operations are not supported:
|
|
71
|
-
|
|
72
|
-
${print(def)}`);
|
|
73
|
-
}
|
|
74
|
-
if (seen.has(def.name.value)) {
|
|
75
|
-
throw new Error(`duplicate operation name: "${def.name.value}"`);
|
|
76
|
-
}
|
|
77
|
-
seen.add(def.name.value);
|
|
78
|
-
operations.push(def);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
return operations;
|
|
83
|
-
}
|
|
84
|
-
function collectUsedFragments(node, allFragments, collected) {
|
|
85
|
-
const selections = [...node.selectionSet?.selections ?? []];
|
|
86
|
-
while (selections.length > 0) {
|
|
87
|
-
const sel = selections.pop();
|
|
88
|
-
if (sel.kind === Kind.FRAGMENT_SPREAD) {
|
|
89
|
-
const name = sel.name.value;
|
|
90
|
-
if (!collected.has(name)) {
|
|
91
|
-
const fragment = allFragments.get(name);
|
|
92
|
-
if (!fragment) {
|
|
93
|
-
throw new Error(`unknown fragment: "${name}"`);
|
|
94
|
-
}
|
|
95
|
-
collected.set(name, fragment);
|
|
96
|
-
collectUsedFragments(fragment, allFragments, collected);
|
|
97
|
-
}
|
|
98
|
-
} else if ("selectionSet" in sel && sel.selectionSet) {
|
|
99
|
-
selections.push(...sel.selectionSet.selections);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
function sortFragmentsByDependency(fragments) {
|
|
104
|
-
const sorted = [];
|
|
105
|
-
const visited = /* @__PURE__ */ new Set();
|
|
106
|
-
function visit2(name) {
|
|
107
|
-
if (visited.has(name)) {
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
visited.add(name);
|
|
111
|
-
const fragment = fragments.get(name);
|
|
112
|
-
if (!fragment) {
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
const deps = /* @__PURE__ */ new Map();
|
|
116
|
-
collectUsedFragments(fragment, fragments, deps);
|
|
117
|
-
for (const [depName] of deps) {
|
|
118
|
-
if (depName !== name) {
|
|
119
|
-
visit2(depName);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
sorted.push(fragment);
|
|
123
|
-
}
|
|
124
|
-
for (const [name] of fragments) {
|
|
125
|
-
visit2(name);
|
|
126
|
-
}
|
|
127
|
-
return sorted;
|
|
128
|
-
}
|
|
129
|
-
function validateDocuments(schema, fragments, operations) {
|
|
130
|
-
const combined = {
|
|
131
|
-
kind: Kind.DOCUMENT,
|
|
132
|
-
definitions: [...fragments.values(), ...operations]
|
|
133
|
-
};
|
|
134
|
-
const errors = validate(schema, combined, VALIDATION_RULES);
|
|
135
|
-
if (errors.length === 0) {
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
const formatted = errors.map((err) => {
|
|
139
|
-
const locations = (err.nodes ?? []).map((node) => {
|
|
140
|
-
if (!node.loc) {
|
|
141
|
-
return null;
|
|
142
|
-
}
|
|
143
|
-
const { source, start } = node.loc;
|
|
144
|
-
const { line, column } = getLocation(source, start);
|
|
145
|
-
return ` at ${source.name}:${line}:${column}`;
|
|
146
|
-
}).filter((s) => s !== null);
|
|
147
|
-
return locations.length > 0 ? ` ${err.message}
|
|
148
|
-
${locations.join("\n")}` : ` ${err.message}`;
|
|
149
|
-
});
|
|
150
|
-
throw new Error(`graphql validation failed:
|
|
151
|
-
|
|
152
|
-
${formatted.join("\n\n")}
|
|
153
|
-
`);
|
|
154
|
-
}
|
|
155
|
-
function operationDocumentExpression(operation, allFragments) {
|
|
156
|
-
const usedFragments = /* @__PURE__ */ new Map();
|
|
157
|
-
collectUsedFragments(operation, allFragments, usedFragments);
|
|
158
|
-
const sortedFragments = sortFragmentsByDependency(usedFragments);
|
|
159
|
-
const refs = sortedFragments.map((f) => `\${${f.name.value}FragmentSchema}`);
|
|
160
|
-
const parts = refs.length > 0 ? [refs.join(String.raw`\n`), print(operation)] : [print(operation)];
|
|
161
|
-
return `\`${parts.join("\n")}\``;
|
|
162
|
-
}
|
|
163
|
-
function fragmentBundleExpression(fragment, allFragments) {
|
|
164
|
-
const usedFragments = /* @__PURE__ */ new Map();
|
|
165
|
-
collectUsedFragments(fragment, allFragments, usedFragments);
|
|
166
|
-
usedFragments.set(fragment.name.value, fragment);
|
|
167
|
-
const sortedFragments = sortFragmentsByDependency(usedFragments);
|
|
168
|
-
if (sortedFragments.length === 1) {
|
|
169
|
-
return `${sortedFragments[0].name.value}FragmentSchema`;
|
|
170
|
-
}
|
|
171
|
-
return `\`${sortedFragments.map((f) => `\${${f.name.value}FragmentSchema}`).join(String.raw`\n`)}\``;
|
|
172
|
-
}
|
|
173
|
-
function generateFragmentSchemas(fragments) {
|
|
174
|
-
const sorted = [...fragments.values()].toSorted((a, b) => a.name.value.localeCompare(b.name.value));
|
|
175
|
-
const lines = [];
|
|
176
|
-
for (const fragment of sorted) {
|
|
177
|
-
lines.push(`const ${fragment.name.value}FragmentSchema = \`${print(fragment)}\`;`);
|
|
178
|
-
}
|
|
179
|
-
return lines.join("\n");
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// src/generate/introspect.ts
|
|
183
|
-
import { buildClientSchema, getIntrospectionQuery } from "graphql";
|
|
184
|
-
async function introspectSchema(url, project, token) {
|
|
185
|
-
const endpoint = `${url}/graphql/projects/${project}`;
|
|
186
|
-
const response = await fetch(endpoint, {
|
|
187
|
-
method: "POST",
|
|
188
|
-
headers: { "content-type": "application/json", token },
|
|
189
|
-
body: JSON.stringify({ query: getIntrospectionQuery() })
|
|
190
|
-
});
|
|
191
|
-
if (!response.ok) {
|
|
192
|
-
throw new Error(`introspection failed: ${response.status} ${response.statusText} (${endpoint})`);
|
|
193
|
-
}
|
|
194
|
-
const json = await response.json();
|
|
195
|
-
if (json.errors?.length) {
|
|
196
|
-
throw new Error(`introspection errors: ${json.errors.map((e) => e.message).join(", ")}`);
|
|
197
|
-
}
|
|
198
|
-
if (!json.data) {
|
|
199
|
-
throw new Error(`introspection returned no data (${endpoint})`);
|
|
200
|
-
}
|
|
201
|
-
return buildClientSchema(json.data);
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
// src/generate/operation-types.ts
|
|
205
|
-
import {
|
|
206
|
-
Kind as Kind2,
|
|
207
|
-
doTypesOverlap as checkTypesOverlap,
|
|
208
|
-
isCompositeType,
|
|
209
|
-
isEnumType,
|
|
210
|
-
isInterfaceType,
|
|
211
|
-
isListType,
|
|
212
|
-
isNonNullType,
|
|
213
|
-
isObjectType,
|
|
214
|
-
isScalarType,
|
|
215
|
-
typeFromAST
|
|
216
|
-
} from "graphql";
|
|
217
|
-
|
|
218
|
-
// src/generate/scalar-types.ts
|
|
219
|
-
var SCALAR_MAP = {
|
|
220
|
-
String: "string",
|
|
221
|
-
Int: "number",
|
|
222
|
-
Float: "number",
|
|
223
|
-
Boolean: "boolean",
|
|
224
|
-
ID: "string",
|
|
225
|
-
DateTime: "string",
|
|
226
|
-
LocalDateTime: "LocalDateTime",
|
|
227
|
-
LocalDate: "LocalDate"
|
|
228
|
-
};
|
|
229
|
-
var MANAGED_SCALARS = ["LocalDateTime", "LocalDate"];
|
|
230
|
-
var DEFAULT_CUSTOM_SCALAR = "unknown";
|
|
231
|
-
function resolveScalarType(name) {
|
|
232
|
-
return SCALAR_MAP[name] ?? DEFAULT_CUSTOM_SCALAR;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
// src/generate/utils.ts
|
|
236
|
-
function uncapitalize(name) {
|
|
237
|
-
return name.charAt(0).toLowerCase() + name.slice(1);
|
|
238
|
-
}
|
|
239
|
-
function pascalCase(name) {
|
|
240
|
-
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
241
|
-
}
|
|
242
|
-
function deriveModelName(typeName) {
|
|
243
|
-
for (const suffix of ["Entity", "Component"]) {
|
|
244
|
-
if (typeName.endsWith(suffix)) {
|
|
245
|
-
return uncapitalize(typeName.slice(0, -suffix.length));
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
return void 0;
|
|
249
|
-
}
|
|
250
|
-
function isContelloModel(schema, typeName) {
|
|
251
|
-
for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
|
|
252
|
-
const union = schema.getType(unionName);
|
|
253
|
-
if (union && typeof union === "object" && "getTypes" in union) {
|
|
254
|
-
const members = union.getTypes();
|
|
255
|
-
if (members.some((m) => m.name === typeName)) {
|
|
256
|
-
return true;
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return false;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// src/generate/operation-types.ts
|
|
264
|
-
function unwrapType(type) {
|
|
265
|
-
let isList = false;
|
|
266
|
-
let isNonNull = false;
|
|
267
|
-
let current = type;
|
|
268
|
-
if (isNonNullType(current)) {
|
|
269
|
-
isNonNull = true;
|
|
270
|
-
current = current.ofType;
|
|
271
|
-
}
|
|
272
|
-
if (isListType(current)) {
|
|
273
|
-
isList = true;
|
|
274
|
-
current = current.ofType;
|
|
275
|
-
if (isNonNullType(current)) {
|
|
276
|
-
current = current.ofType;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
return { namedType: current, isList, isNonNull };
|
|
280
|
-
}
|
|
281
|
-
function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent) {
|
|
282
|
-
const fields = [];
|
|
283
|
-
const inlineUnions = [];
|
|
284
|
-
const fragmentRefs = [];
|
|
285
|
-
let hasTypenameField = false;
|
|
286
|
-
for (const selection of selectionSet.selections) {
|
|
287
|
-
switch (selection.kind) {
|
|
288
|
-
case Kind2.FIELD: {
|
|
289
|
-
const fieldName = selection.alias?.value ?? selection.name.value;
|
|
290
|
-
if (selection.name.value === "__typename") {
|
|
291
|
-
hasTypenameField = true;
|
|
292
|
-
continue;
|
|
293
|
-
}
|
|
294
|
-
const schemaField = isObjectType(parentType) || isInterfaceType(parentType) ? parentType.getFields()[selection.name.value] : void 0;
|
|
295
|
-
if (!schemaField) {
|
|
296
|
-
throw new Error(`field "${selection.name.value}" does not exist on type "${parentType.name}"`);
|
|
297
|
-
}
|
|
298
|
-
const { namedType, isList, isNonNull } = unwrapType(schemaField.type);
|
|
299
|
-
let tsType;
|
|
300
|
-
if (selection.selectionSet && isCompositeType(namedType)) {
|
|
301
|
-
tsType = resolveSelectionSetType(schema, selection.selectionSet, namedType, fragments, `${indent} `);
|
|
302
|
-
} else if (isScalarType(namedType)) {
|
|
303
|
-
tsType = resolveScalarType(namedType.name);
|
|
304
|
-
} else if (isEnumType(namedType)) {
|
|
305
|
-
tsType = namedType.name;
|
|
306
|
-
} else {
|
|
307
|
-
tsType = namedType.toString();
|
|
308
|
-
}
|
|
309
|
-
if (isList) {
|
|
310
|
-
const wrapped = /[ |&]/.test(tsType) ? `(${tsType})` : tsType;
|
|
311
|
-
tsType = `${wrapped}[]`;
|
|
312
|
-
}
|
|
313
|
-
if (isNonNull) {
|
|
314
|
-
fields.push(`${indent} ${fieldName}: ${tsType};`);
|
|
315
|
-
} else {
|
|
316
|
-
fields.push(`${indent} ${fieldName}?: ${tsType} | undefined;`);
|
|
317
|
-
}
|
|
318
|
-
break;
|
|
319
|
-
}
|
|
320
|
-
case Kind2.INLINE_FRAGMENT: {
|
|
321
|
-
if (selection.typeCondition && selection.selectionSet) {
|
|
322
|
-
const typeName = selection.typeCondition.name.value;
|
|
323
|
-
const conditionalType = schema.getType(typeName);
|
|
324
|
-
if (!conditionalType) {
|
|
325
|
-
throw new Error(`unknown type "${typeName}" in inline fragment`);
|
|
326
|
-
}
|
|
327
|
-
if (isCompositeType(conditionalType)) {
|
|
328
|
-
if (isInterfaceType(conditionalType)) {
|
|
329
|
-
const inner = resolveSelectionSet(schema, selection.selectionSet, conditionalType, fragments, indent);
|
|
330
|
-
fields.push(...inner.fields);
|
|
331
|
-
fragmentRefs.push(...inner.fragmentRefs);
|
|
332
|
-
} else if (isObjectType(conditionalType)) {
|
|
333
|
-
const nested = resolveSelectionSetType(
|
|
334
|
-
schema,
|
|
335
|
-
selection.selectionSet,
|
|
336
|
-
conditionalType,
|
|
337
|
-
fragments,
|
|
338
|
-
indent
|
|
339
|
-
);
|
|
340
|
-
if (nested.startsWith("{")) {
|
|
341
|
-
const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
|
|
342
|
-
const discriminant = model ? `${indent} __typename: '${conditionalType.name}';
|
|
343
|
-
${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.name}';`;
|
|
344
|
-
inlineUnions.push(`{
|
|
345
|
-
${discriminant}
|
|
346
|
-
${nested.slice(2)}`);
|
|
347
|
-
} else {
|
|
348
|
-
const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
|
|
349
|
-
const discriminant = model ? `{
|
|
350
|
-
${indent} __typename: '${conditionalType.name}';
|
|
351
|
-
${indent} __model: '${model}';
|
|
352
|
-
${indent}}` : `{
|
|
353
|
-
${indent} __typename: '${conditionalType.name}';
|
|
354
|
-
${indent}}`;
|
|
355
|
-
inlineUnions.push(`${discriminant} & ${nested}`);
|
|
356
|
-
}
|
|
357
|
-
} else {
|
|
358
|
-
const nested = resolveSelectionSetType(
|
|
359
|
-
schema,
|
|
360
|
-
selection.selectionSet,
|
|
361
|
-
conditionalType,
|
|
362
|
-
fragments,
|
|
363
|
-
indent
|
|
364
|
-
);
|
|
365
|
-
inlineUnions.push(nested);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
break;
|
|
370
|
-
}
|
|
371
|
-
case Kind2.FRAGMENT_SPREAD: {
|
|
372
|
-
const fragmentName = selection.name.value;
|
|
373
|
-
const fragment = fragments.get(fragmentName);
|
|
374
|
-
if (fragment?.selectionSet) {
|
|
375
|
-
const fragmentType = schema.getType(fragment.typeCondition.name.value);
|
|
376
|
-
if (fragmentType && isCompositeType(fragmentType)) {
|
|
377
|
-
if (!checkTypesOverlap(schema, parentType, fragmentType)) {
|
|
378
|
-
throw new Error(
|
|
379
|
-
`fragment "${fragmentName}" (on ${fragmentType.name}) cannot be spread on type "${parentType.name}"`
|
|
380
|
-
);
|
|
381
|
-
}
|
|
382
|
-
fragmentRefs.push(`${fragmentName}Fragment`);
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
break;
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
return { fields, inlineUnions, fragmentRefs, hasTypenameField };
|
|
390
|
-
}
|
|
391
|
-
function resolveSelectionSetType(schema, selectionSet, parentType, fragments, indent) {
|
|
392
|
-
const { fields, inlineUnions, fragmentRefs, hasTypenameField } = resolveSelectionSet(
|
|
393
|
-
schema,
|
|
394
|
-
selectionSet,
|
|
395
|
-
parentType,
|
|
396
|
-
fragments,
|
|
397
|
-
indent
|
|
398
|
-
);
|
|
399
|
-
if (hasTypenameField && inlineUnions.length === 0) {
|
|
400
|
-
const typenameField = isObjectType(parentType) ? `${indent} __typename: '${parentType.name}';` : `${indent} __typename: string;`;
|
|
401
|
-
fields.unshift(typenameField);
|
|
402
|
-
}
|
|
403
|
-
if (fields.length === 0 && fragmentRefs.length === 0 && inlineUnions.length > 0) {
|
|
404
|
-
return inlineUnions.join(" | ");
|
|
405
|
-
}
|
|
406
|
-
const parts = [];
|
|
407
|
-
if (fields.length > 0) {
|
|
408
|
-
parts.push(`{
|
|
409
|
-
${fields.join("\n")}
|
|
410
|
-
${indent}}`);
|
|
411
|
-
}
|
|
412
|
-
parts.push(...fragmentRefs);
|
|
413
|
-
if (inlineUnions.length > 0) {
|
|
414
|
-
parts.push(`(${inlineUnions.join(" | ")})`);
|
|
415
|
-
}
|
|
416
|
-
if (parts.length === 0) {
|
|
417
|
-
return "{}";
|
|
418
|
-
}
|
|
419
|
-
return parts.join(" & ");
|
|
420
|
-
}
|
|
421
|
-
function generateVariablesType(schema, operation) {
|
|
422
|
-
const vars = operation.variableDefinitions ?? [];
|
|
423
|
-
if (vars.length === 0) {
|
|
424
|
-
return "Record<string, never>";
|
|
425
|
-
}
|
|
426
|
-
const fields = [];
|
|
427
|
-
for (const v of vars) {
|
|
428
|
-
const varType = typeFromAST(schema, v.type);
|
|
429
|
-
if (!varType) {
|
|
430
|
-
throw new Error(`cannot resolve type for variable "$${v.variable.name.value}"`);
|
|
431
|
-
}
|
|
432
|
-
const isRequired = isNonNullType(varType) && !v.defaultValue;
|
|
433
|
-
const tsType = graphqlTypeToTs(varType);
|
|
434
|
-
if (isRequired) {
|
|
435
|
-
fields.push(` ${v.variable.name.value}: ${tsType};`);
|
|
436
|
-
} else {
|
|
437
|
-
fields.push(` ${v.variable.name.value}?: ${tsType} | undefined;`);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
return `{
|
|
441
|
-
${fields.join("\n")}
|
|
442
|
-
}`;
|
|
443
|
-
}
|
|
444
|
-
function graphqlTypeToTs(type) {
|
|
445
|
-
if (isNonNullType(type)) {
|
|
446
|
-
return graphqlTypeToTs(type.ofType);
|
|
447
|
-
}
|
|
448
|
-
if (isListType(type)) {
|
|
449
|
-
return `${graphqlTypeToTs(type.ofType)}[]`;
|
|
450
|
-
}
|
|
451
|
-
if (isScalarType(type)) {
|
|
452
|
-
return resolveScalarType(type.name);
|
|
453
|
-
}
|
|
454
|
-
if (isEnumType(type)) {
|
|
455
|
-
return type.name;
|
|
456
|
-
}
|
|
457
|
-
return type.name;
|
|
458
|
-
}
|
|
459
|
-
function generateFragmentTypes(schema, fragments) {
|
|
460
|
-
const lines = [];
|
|
461
|
-
for (const [name, fragment] of fragments) {
|
|
462
|
-
const typeName = `${name}Fragment`;
|
|
463
|
-
const parentType = schema.getType(fragment.typeCondition.name.value);
|
|
464
|
-
if (parentType && isCompositeType(parentType)) {
|
|
465
|
-
const resultType = resolveSelectionSetType(schema, fragment.selectionSet, parentType, fragments, "");
|
|
466
|
-
lines.push(`export type ${typeName} = ${resultType};`);
|
|
467
|
-
} else {
|
|
468
|
-
lines.push(`export type ${typeName} = {};`);
|
|
469
|
-
}
|
|
470
|
-
lines.push("");
|
|
471
|
-
}
|
|
472
|
-
return lines.join("\n");
|
|
473
|
-
}
|
|
474
|
-
function generateOperationTypes(schema, operations, fragments) {
|
|
475
|
-
const lines = [];
|
|
476
|
-
for (const op of operations) {
|
|
477
|
-
const name = op.name.value;
|
|
478
|
-
const typeSuffix = pascalCase(op.operation);
|
|
479
|
-
const resultTypeName = `${name}${typeSuffix}`;
|
|
480
|
-
const variablesTypeName = `${resultTypeName}Variables`;
|
|
481
|
-
const rootType = op.operation === "query" ? schema.getQueryType() : op.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
|
|
482
|
-
if (rootType && op.selectionSet) {
|
|
483
|
-
const resultType = resolveSelectionSetType(schema, op.selectionSet, rootType, fragments, "");
|
|
484
|
-
lines.push(`export type ${resultTypeName} = ${resultType};`);
|
|
485
|
-
} else {
|
|
486
|
-
lines.push(`export type ${resultTypeName} = {};`);
|
|
487
|
-
}
|
|
488
|
-
lines.push("");
|
|
489
|
-
const variablesType = generateVariablesType(schema, op);
|
|
490
|
-
lines.push(`export type ${variablesTypeName} = ${variablesType};`, "");
|
|
491
|
-
}
|
|
492
|
-
return lines.join("\n");
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
// src/generate/operations.ts
|
|
496
|
-
function generateOperationsType(operations) {
|
|
497
|
-
const lines = ["export type Operations = {"];
|
|
498
|
-
for (const op of operations) {
|
|
499
|
-
const name = op.name.value;
|
|
500
|
-
const camelName = uncapitalize(name);
|
|
501
|
-
const typeSuffix = pascalCase(op.operation);
|
|
502
|
-
const resultType = `${name}${typeSuffix}`;
|
|
503
|
-
const variablesType = `${resultType}Variables`;
|
|
504
|
-
lines.push(` ${camelName}: {`, ` document: string;`, ` kind: '${op.operation}';`, ` __result?: ${resultType} | undefined;`, ` __variables?: ${variablesType} | undefined;`, " };");
|
|
505
|
-
}
|
|
506
|
-
lines.push("};");
|
|
507
|
-
return lines.join("\n");
|
|
508
|
-
}
|
|
509
|
-
function generateOperationsConst(operations) {
|
|
510
|
-
const lines = ["const operations: Operations = {"];
|
|
511
|
-
for (const op of operations) {
|
|
512
|
-
const camelName = uncapitalize(op.name.value);
|
|
513
|
-
lines.push(` ${camelName}: { document: ${camelName}Document, kind: '${op.operation}' },`);
|
|
514
|
-
}
|
|
515
|
-
lines.push("};");
|
|
516
|
-
return lines.join("\n");
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// src/generate/schema-types.ts
|
|
520
|
-
import {
|
|
521
|
-
isEnumType as isEnumType2,
|
|
522
|
-
isInputObjectType,
|
|
523
|
-
isInterfaceType as isInterfaceType2,
|
|
524
|
-
isListType as isListType2,
|
|
525
|
-
isNonNullType as isNonNullType2,
|
|
526
|
-
isObjectType as isObjectType2,
|
|
527
|
-
isScalarType as isScalarType2,
|
|
528
|
-
isUnionType
|
|
529
|
-
} from "graphql";
|
|
530
|
-
function typeToTs(type, nonNull = false) {
|
|
531
|
-
if (isNonNullType2(type)) {
|
|
532
|
-
return typeToTs(type.ofType, true);
|
|
533
|
-
}
|
|
534
|
-
if (isListType2(type)) {
|
|
535
|
-
const inner = typeToTs(type.ofType);
|
|
536
|
-
const wrapped = inner.includes(" | ") ? `(${inner})` : inner;
|
|
537
|
-
return nonNull ? `${wrapped}[]` : `${wrapped}[] | undefined`;
|
|
538
|
-
}
|
|
539
|
-
const name = isScalarType2(type) ? resolveScalarType(type.name) : type.name;
|
|
540
|
-
return nonNull ? name : `${name} | undefined`;
|
|
541
|
-
}
|
|
542
|
-
function inputTypeToTs(type, nonNull = false) {
|
|
543
|
-
return typeToTs(type, nonNull);
|
|
544
|
-
}
|
|
545
|
-
function generateEnum(type) {
|
|
546
|
-
const values = type.getValues().map((v) => `'${v.value}'`).toSorted().join(" | ");
|
|
547
|
-
return `export type ${type.name} = ${values};`;
|
|
548
|
-
}
|
|
549
|
-
function sortedFields(type) {
|
|
550
|
-
return Object.values(type.getFields()).toSorted((a, b) => a.name.localeCompare(b.name));
|
|
551
|
-
}
|
|
552
|
-
function generateObjectType(type, modelNames) {
|
|
553
|
-
const fields = sortedFields(type);
|
|
554
|
-
const lines = [];
|
|
555
|
-
const model = modelNames.get(type.name);
|
|
556
|
-
lines.push(`export type ${type.name} = {`, ` __typename?: '${type.name}' | undefined;`);
|
|
557
|
-
if (model) {
|
|
558
|
-
lines.push(` __model?: '${model}' | undefined;`);
|
|
559
|
-
}
|
|
560
|
-
for (const field of fields) {
|
|
561
|
-
lines.push(` ${field.name}${isNonNullType2(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
|
|
562
|
-
}
|
|
563
|
-
lines.push("};");
|
|
564
|
-
return lines.join("\n");
|
|
565
|
-
}
|
|
566
|
-
function generateInputType(type) {
|
|
567
|
-
const fields = sortedFields(type);
|
|
568
|
-
const lines = [`export type ${type.name} = {`];
|
|
569
|
-
for (const field of fields) {
|
|
570
|
-
lines.push(` ${field.name}${isNonNullType2(field.type) ? "" : "?"}: ${inputTypeToTs(field.type)};`);
|
|
571
|
-
}
|
|
572
|
-
lines.push("};");
|
|
573
|
-
return lines.join("\n");
|
|
574
|
-
}
|
|
575
|
-
function generateUnion(type) {
|
|
576
|
-
const members = type.getTypes().map((t) => t.name).toSorted();
|
|
577
|
-
return `export type ${type.name} = ${members.join(" | ")};`;
|
|
578
|
-
}
|
|
579
|
-
function isInternalType(name) {
|
|
580
|
-
return name.startsWith("__");
|
|
581
|
-
}
|
|
582
|
-
function generateSchemaTypes(schema) {
|
|
583
|
-
const typeMap = schema.getTypeMap();
|
|
584
|
-
const lines = [];
|
|
585
|
-
const byName = (a, b) => a.name.localeCompare(b.name);
|
|
586
|
-
const customScalars = Object.values(typeMap).filter((t) => isScalarType2(t) && !isInternalType(t.name) && !SCALAR_MAP[t.name]).toSorted(byName);
|
|
587
|
-
if (customScalars.length > 0) {
|
|
588
|
-
for (const scalar of customScalars) {
|
|
589
|
-
lines.push(`export type ${scalar.name} = ${DEFAULT_CUSTOM_SCALAR};`);
|
|
590
|
-
}
|
|
591
|
-
lines.push("");
|
|
592
|
-
}
|
|
593
|
-
const enums = Object.values(typeMap).filter((t) => isEnumType2(t) && !isInternalType(t.name)).toSorted(byName);
|
|
594
|
-
for (const e of enums) {
|
|
595
|
-
lines.push(generateEnum(e));
|
|
596
|
-
}
|
|
597
|
-
if (enums.length > 0) {
|
|
598
|
-
lines.push("");
|
|
599
|
-
}
|
|
600
|
-
const inputs = Object.values(typeMap).filter((t) => isInputObjectType(t) && !isInternalType(t.name)).toSorted(byName);
|
|
601
|
-
for (const input of inputs) {
|
|
602
|
-
lines.push(generateInputType(input), "");
|
|
603
|
-
}
|
|
604
|
-
const modelNames = /* @__PURE__ */ new Map();
|
|
605
|
-
const entityModelNames = /* @__PURE__ */ new Map();
|
|
606
|
-
for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
|
|
607
|
-
const union = typeMap[unionName];
|
|
608
|
-
if (union && isUnionType(union)) {
|
|
609
|
-
for (const member of union.getTypes()) {
|
|
610
|
-
const model = deriveModelName(member.name);
|
|
611
|
-
if (model) {
|
|
612
|
-
modelNames.set(member.name, model);
|
|
613
|
-
if (unionName === "ContelloEntity") {
|
|
614
|
-
entityModelNames.set(member.name, model);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
const objects = Object.values(typeMap).filter((t) => isObjectType2(t) && !isInternalType(t.name)).toSorted(byName);
|
|
621
|
-
for (const obj of objects) {
|
|
622
|
-
lines.push(generateObjectType(obj, modelNames), "");
|
|
623
|
-
}
|
|
624
|
-
const interfaces = Object.values(typeMap).filter((t) => isInterfaceType2(t) && !isInternalType(t.name)).toSorted(byName);
|
|
625
|
-
for (const iface of interfaces) {
|
|
626
|
-
const fields = Object.values(iface.getFields()).toSorted(
|
|
627
|
-
(a, b) => a.name.localeCompare(b.name)
|
|
628
|
-
);
|
|
629
|
-
const fieldLines = [`export type ${iface.name} = {`, ` __typename?: string | undefined;`];
|
|
630
|
-
for (const field of fields) {
|
|
631
|
-
fieldLines.push(` ${field.name}${isNonNullType2(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
|
|
632
|
-
}
|
|
633
|
-
fieldLines.push("};");
|
|
634
|
-
lines.push(fieldLines.join("\n"), "");
|
|
635
|
-
}
|
|
636
|
-
const unions = Object.values(typeMap).filter((t) => isUnionType(t) && !isInternalType(t.name)).toSorted(byName);
|
|
637
|
-
for (const union of unions) {
|
|
638
|
-
lines.push(generateUnion(union));
|
|
639
|
-
}
|
|
640
|
-
if (unions.length > 0) {
|
|
641
|
-
lines.push("");
|
|
642
|
-
}
|
|
643
|
-
return lines.join("\n");
|
|
644
|
-
}
|
|
645
|
-
function extractEntityModels(schema) {
|
|
646
|
-
const map = /* @__PURE__ */ new Map();
|
|
647
|
-
const union = schema.getTypeMap()["ContelloEntity"];
|
|
648
|
-
if (!union || !isUnionType(union)) {
|
|
649
|
-
return map;
|
|
650
|
-
}
|
|
651
|
-
for (const member of union.getTypes()) {
|
|
652
|
-
const model = deriveModelName(member.name);
|
|
653
|
-
if (model) {
|
|
654
|
-
map.set(model, member.name);
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
return map;
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
// src/generate/sources.ts
|
|
661
|
-
import {
|
|
662
|
-
isListType as isListType3,
|
|
663
|
-
isNonNullType as isNonNullType3,
|
|
664
|
-
isObjectType as isObjectType3
|
|
665
|
-
} from "graphql";
|
|
666
|
-
var BUILT_IN_SOURCES = [
|
|
667
|
-
{ typeName: "ContelloRoute", cardinality: "route", fieldName: "contelloRoutesBatch" },
|
|
668
|
-
{ typeName: "ContelloAsset", cardinality: "asset", fieldName: "contelloAssetsBatch" },
|
|
669
|
-
{ typeName: "ContelloI18nMessage", cardinality: "i18nMessage", fieldName: "contelloI18nMessagesBatch" }
|
|
670
|
-
];
|
|
671
|
-
function indexEntitySources(schema) {
|
|
672
|
-
const result = /* @__PURE__ */ new Map();
|
|
673
|
-
const subscription = schema.getSubscriptionType();
|
|
674
|
-
if (!subscription) {
|
|
675
|
-
return result;
|
|
676
|
-
}
|
|
677
|
-
const singletonCandidates = /* @__PURE__ */ new Map();
|
|
678
|
-
for (const field of Object.values(subscription.getFields())) {
|
|
679
|
-
const { entityType, isList } = unwrapEntity(field.type);
|
|
680
|
-
if (!entityType || !isContelloModel(schema, entityType.name)) {
|
|
681
|
-
continue;
|
|
682
|
-
}
|
|
683
|
-
const model = deriveModelName(entityType.name);
|
|
684
|
-
if (!model) {
|
|
685
|
-
continue;
|
|
686
|
-
}
|
|
687
|
-
if (isList) {
|
|
688
|
-
result.set(entityType.name, { cardinality: "entity", fieldName: field.name, model });
|
|
689
|
-
} else if (!singletonCandidates.has(entityType.name)) {
|
|
690
|
-
singletonCandidates.set(entityType.name, { fieldName: field.name });
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
for (const [typeName, { fieldName }] of singletonCandidates) {
|
|
694
|
-
if (result.has(typeName)) {
|
|
695
|
-
continue;
|
|
696
|
-
}
|
|
697
|
-
const model = deriveModelName(typeName);
|
|
698
|
-
if (!model) {
|
|
699
|
-
continue;
|
|
700
|
-
}
|
|
701
|
-
result.set(typeName, { cardinality: "singleton", fieldName, model });
|
|
702
|
-
}
|
|
703
|
-
return result;
|
|
704
|
-
}
|
|
705
|
-
function indexBuiltInSources(schema) {
|
|
706
|
-
const result = /* @__PURE__ */ new Map();
|
|
707
|
-
const subscription = schema.getSubscriptionType();
|
|
708
|
-
if (!subscription) {
|
|
709
|
-
return result;
|
|
710
|
-
}
|
|
711
|
-
const fields = subscription.getFields();
|
|
712
|
-
for (const builtIn of BUILT_IN_SOURCES) {
|
|
713
|
-
if (!schema.getType(builtIn.typeName) || !fields[builtIn.fieldName]) {
|
|
714
|
-
continue;
|
|
715
|
-
}
|
|
716
|
-
result.set(builtIn.typeName, {
|
|
717
|
-
cardinality: builtIn.cardinality,
|
|
718
|
-
fieldName: builtIn.fieldName
|
|
719
|
-
});
|
|
720
|
-
}
|
|
721
|
-
return result;
|
|
722
|
-
}
|
|
723
|
-
function unwrapEntity(type) {
|
|
724
|
-
let current = type;
|
|
725
|
-
let isList = false;
|
|
726
|
-
if (isNonNullType3(current)) {
|
|
727
|
-
current = current.ofType;
|
|
728
|
-
}
|
|
729
|
-
if (isListType3(current)) {
|
|
730
|
-
isList = true;
|
|
731
|
-
current = current.ofType;
|
|
732
|
-
if (isNonNullType3(current)) {
|
|
733
|
-
current = current.ofType;
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
return {
|
|
737
|
-
entityType: isObjectType3(current) ? current : void 0,
|
|
738
|
-
isList
|
|
739
|
-
};
|
|
740
|
-
}
|
|
741
|
-
function organize(entries) {
|
|
742
|
-
const byKey = /* @__PURE__ */ new Map();
|
|
743
|
-
for (const entry of entries) {
|
|
744
|
-
const existing = byKey.get(entry.binding.sourceKey);
|
|
745
|
-
if (existing) {
|
|
746
|
-
throw new Error(
|
|
747
|
-
`multiple fragments target the same source key "${entry.binding.sourceKey}": "${existing.fragmentName}" and "${entry.fragmentName}". A source key can have at most one fragment \u2014 merge the fragments or use the raw client for the alternative shape.`
|
|
748
|
-
);
|
|
749
|
-
}
|
|
750
|
-
byKey.set(entry.binding.sourceKey, entry);
|
|
751
|
-
}
|
|
752
|
-
return [...byKey.values()].toSorted((a, b) => a.binding.sourceKey.localeCompare(b.binding.sourceKey));
|
|
753
|
-
}
|
|
754
|
-
function generateSourcesType(entries) {
|
|
755
|
-
const sorted = organize(entries);
|
|
756
|
-
if (sorted.length === 0) {
|
|
757
|
-
return "";
|
|
758
|
-
}
|
|
759
|
-
const lines = ["export type Sources = {"];
|
|
760
|
-
for (const { fragmentName, binding } of sorted) {
|
|
761
|
-
const type = `SourceDef<'${binding.sourceKey}', '${binding.cardinality}', ${fragmentName}Fragment>`;
|
|
762
|
-
lines.push(` ${binding.sourceKey}: ${type};`);
|
|
763
|
-
}
|
|
764
|
-
lines.push("};");
|
|
765
|
-
return lines.join("\n");
|
|
766
|
-
}
|
|
767
|
-
function generateSourcesConst(entries) {
|
|
768
|
-
const sorted = organize(entries);
|
|
769
|
-
if (sorted.length === 0) {
|
|
770
|
-
return "";
|
|
771
|
-
}
|
|
772
|
-
const lines = ["const sources: Sources = {"];
|
|
773
|
-
for (const { fragmentName, binding, fragmentExpression } of sorted) {
|
|
774
|
-
lines.push(` ${binding.sourceKey}: {`, ` document: ${fragmentExpression},`, ` fragment: '${fragmentName}',`, ` subscription: '${binding.fieldName}',`, ` __model: '${binding.sourceKey}',`, ` __cardinality: '${binding.cardinality}',`, ` },`);
|
|
775
|
-
}
|
|
776
|
-
lines.push("};");
|
|
777
|
-
return lines.join("\n");
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
// src/generate/transform-components.ts
|
|
781
|
-
import {
|
|
782
|
-
Kind as Kind3,
|
|
783
|
-
isCompositeType as isCompositeType2,
|
|
784
|
-
isListType as isListType4,
|
|
785
|
-
isNonNullType as isNonNullType4,
|
|
786
|
-
isObjectType as isObjectType4,
|
|
787
|
-
isUnionType as isUnionType2,
|
|
788
|
-
parse
|
|
789
|
-
} from "graphql";
|
|
790
|
-
var FLAT_PREFIX = "_flat_";
|
|
791
|
-
var FLAT_COMPONENT_TYPE = "ContelloFlatComponent";
|
|
792
|
-
var COMPONENT_UNION = "ContelloComponent";
|
|
793
|
-
function isComponentUnion(schema, typeName) {
|
|
794
|
-
const type = schema.getType(typeName);
|
|
795
|
-
return !!type && isUnionType2(type) && type.name === COMPONENT_UNION;
|
|
796
|
-
}
|
|
797
|
-
function isComponentSubtype(schema, typeName) {
|
|
798
|
-
const union = schema.getType(COMPONENT_UNION);
|
|
799
|
-
if (!union || !isUnionType2(union)) {
|
|
800
|
-
return false;
|
|
801
|
-
}
|
|
802
|
-
return union.getTypes().some((t) => t.name === typeName);
|
|
803
|
-
}
|
|
804
|
-
function getNamedTypeName(type) {
|
|
805
|
-
if (isNonNullType4(type)) return getNamedTypeName(type.ofType);
|
|
806
|
-
if (isListType4(type)) return getNamedTypeName(type.ofType);
|
|
807
|
-
return type?.name;
|
|
808
|
-
}
|
|
809
|
-
var FLAT_REF_SELECTIONS = parse(
|
|
810
|
-
`{ __typename ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`
|
|
811
|
-
).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
|
|
812
|
-
var FLAT_REF_ONLY_SELECTIONS = parse(
|
|
813
|
-
`{ ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`
|
|
814
|
-
).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
|
|
815
|
-
function hasExistingFlatSpread(selectionSet) {
|
|
816
|
-
return selectionSet.selections.some(
|
|
817
|
-
(s) => s.kind === Kind3.INLINE_FRAGMENT && s.typeCondition?.name.value === FLAT_COMPONENT_TYPE
|
|
818
|
-
);
|
|
819
|
-
}
|
|
820
|
-
function addFlatRefSelections(selectionSet) {
|
|
821
|
-
if (hasExistingFlatSpread(selectionSet)) {
|
|
822
|
-
return selectionSet;
|
|
823
|
-
}
|
|
824
|
-
return {
|
|
825
|
-
...selectionSet,
|
|
826
|
-
selections: [...FLAT_REF_SELECTIONS.selections, ...selectionSet.selections]
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
function transformSelectionSet(schema, selectionSet, parentTypeName, fragments, refsOnly = false) {
|
|
830
|
-
const parentType = schema.getType(parentTypeName);
|
|
831
|
-
if (!parentType || !isObjectType4(parentType)) {
|
|
832
|
-
return selectionSet;
|
|
833
|
-
}
|
|
834
|
-
const parentFields = parentType.getFields();
|
|
835
|
-
const newSelections = [];
|
|
836
|
-
let changed = false;
|
|
837
|
-
function recurse(node, typeName) {
|
|
838
|
-
if (!node.selectionSet) {
|
|
839
|
-
newSelections.push(node);
|
|
840
|
-
return;
|
|
841
|
-
}
|
|
842
|
-
const transformed = transformSelectionSet(schema, node.selectionSet, typeName, fragments, refsOnly);
|
|
843
|
-
if (transformed === node.selectionSet) {
|
|
844
|
-
newSelections.push(node);
|
|
845
|
-
} else {
|
|
846
|
-
changed = true;
|
|
847
|
-
newSelections.push({ ...node, selectionSet: transformed });
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
for (const selection of selectionSet.selections) {
|
|
851
|
-
if (selection.kind === Kind3.FIELD) {
|
|
852
|
-
const fieldName = selection.name.value;
|
|
853
|
-
const schemaField = parentFields[fieldName];
|
|
854
|
-
if (!schemaField) {
|
|
855
|
-
newSelections.push(selection);
|
|
856
|
-
continue;
|
|
857
|
-
}
|
|
858
|
-
const namedTypeName2 = getNamedTypeName(schemaField.type);
|
|
859
|
-
if (namedTypeName2 && isComponentUnion(schema, namedTypeName2) && selection.selectionSet) {
|
|
860
|
-
const flatFieldName = `${FLAT_PREFIX}${fieldName}`;
|
|
861
|
-
if (!parentFields[flatFieldName]) {
|
|
862
|
-
newSelections.push(selection);
|
|
863
|
-
continue;
|
|
864
|
-
}
|
|
865
|
-
changed = true;
|
|
866
|
-
newSelections.push({ ...selection, selectionSet: FLAT_REF_ONLY_SELECTIONS });
|
|
867
|
-
if (!refsOnly) {
|
|
868
|
-
newSelections.push({
|
|
869
|
-
kind: Kind3.FIELD,
|
|
870
|
-
name: { kind: Kind3.NAME, value: flatFieldName },
|
|
871
|
-
selectionSet: addFlatRefSelections(selection.selectionSet)
|
|
872
|
-
});
|
|
873
|
-
}
|
|
874
|
-
} else if (namedTypeName2) {
|
|
875
|
-
recurse(selection, namedTypeName2);
|
|
876
|
-
} else {
|
|
877
|
-
newSelections.push(selection);
|
|
878
|
-
}
|
|
879
|
-
} else if (selection.kind === Kind3.INLINE_FRAGMENT) {
|
|
880
|
-
const typeName = selection.typeCondition?.name.value;
|
|
881
|
-
const type = typeName ? schema.getType(typeName) : void 0;
|
|
882
|
-
if (typeName && type && isCompositeType2(type) && isObjectType4(type)) {
|
|
883
|
-
recurse(selection, typeName);
|
|
884
|
-
} else {
|
|
885
|
-
newSelections.push(selection);
|
|
886
|
-
}
|
|
887
|
-
} else {
|
|
888
|
-
newSelections.push(selection);
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
if (!changed) {
|
|
892
|
-
return selectionSet;
|
|
893
|
-
}
|
|
894
|
-
return { ...selectionSet, selections: newSelections };
|
|
895
|
-
}
|
|
896
|
-
function transformOperation(schema, operation, fragments) {
|
|
897
|
-
const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
|
|
898
|
-
if (!rootType || !operation.selectionSet) {
|
|
899
|
-
return operation;
|
|
900
|
-
}
|
|
901
|
-
const transformed = transformSelectionSet(schema, operation.selectionSet, rootType.name, fragments);
|
|
902
|
-
if (transformed === operation.selectionSet) {
|
|
903
|
-
return operation;
|
|
904
|
-
}
|
|
905
|
-
return { ...operation, selectionSet: transformed };
|
|
906
|
-
}
|
|
907
|
-
function transformFragment(schema, fragment, fragments) {
|
|
908
|
-
const typeName = fragment.typeCondition.name.value;
|
|
909
|
-
const type = schema.getType(typeName);
|
|
910
|
-
if (!type || !isCompositeType2(type)) {
|
|
911
|
-
return fragment;
|
|
912
|
-
}
|
|
913
|
-
let selectionSet = fragment.selectionSet;
|
|
914
|
-
if (typeName === COMPONENT_UNION) {
|
|
915
|
-
selectionSet = addFlatRefSelections(selectionSet);
|
|
916
|
-
}
|
|
917
|
-
if (isObjectType4(type)) {
|
|
918
|
-
const refsOnly = isComponentSubtype(schema, typeName);
|
|
919
|
-
selectionSet = transformSelectionSet(schema, selectionSet, typeName, fragments, refsOnly);
|
|
920
|
-
} else if (isUnionType2(type)) {
|
|
921
|
-
const newSelections = selectionSet.selections.map((sel) => {
|
|
922
|
-
if (sel.kind === Kind3.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
|
|
923
|
-
const inlineTypeName = sel.typeCondition.name.value;
|
|
924
|
-
const inlineType = schema.getType(inlineTypeName);
|
|
925
|
-
if (inlineType && isObjectType4(inlineType)) {
|
|
926
|
-
const transformed = transformSelectionSet(schema, sel.selectionSet, inlineTypeName, fragments, true);
|
|
927
|
-
if (transformed !== sel.selectionSet) {
|
|
928
|
-
return { ...sel, selectionSet: transformed };
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
return sel;
|
|
933
|
-
});
|
|
934
|
-
selectionSet = { ...selectionSet, selections: newSelections };
|
|
935
|
-
}
|
|
936
|
-
if (selectionSet === fragment.selectionSet) {
|
|
937
|
-
return fragment;
|
|
938
|
-
}
|
|
939
|
-
return { ...fragment, selectionSet };
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
// src/generate/transform-scalars.ts
|
|
943
|
-
import {
|
|
944
|
-
Kind as Kind4,
|
|
945
|
-
isCompositeType as isCompositeType3,
|
|
946
|
-
isInterfaceType as isInterfaceType3,
|
|
947
|
-
isListType as isListType5,
|
|
948
|
-
isNonNullType as isNonNullType5,
|
|
949
|
-
isObjectType as isObjectType5,
|
|
950
|
-
isScalarType as isScalarType3
|
|
951
|
-
} from "graphql";
|
|
952
|
-
var SCALAR_PREFIX = {
|
|
953
|
-
LocalDateTime: "_ldt_",
|
|
954
|
-
LocalDate: "_ld_"
|
|
955
|
-
};
|
|
956
|
-
function namedTypeName(type) {
|
|
957
|
-
let current = type;
|
|
958
|
-
while (isNonNullType5(current) || isListType5(current)) {
|
|
959
|
-
current = current.ofType;
|
|
960
|
-
}
|
|
961
|
-
return isScalarType3(current) ? current.name : void 0;
|
|
962
|
-
}
|
|
963
|
-
function prefixFor(typeName) {
|
|
964
|
-
return SCALAR_PREFIX[typeName];
|
|
965
|
-
}
|
|
966
|
-
function transformSelectionSet2(schema, selectionSet, parentTypeName) {
|
|
967
|
-
const parentType = schema.getType(parentTypeName);
|
|
968
|
-
if (!parentType || !isObjectType5(parentType) && !isInterfaceType3(parentType)) {
|
|
969
|
-
return selectionSet;
|
|
970
|
-
}
|
|
971
|
-
const parentFields = parentType.getFields();
|
|
972
|
-
const newSelections = [];
|
|
973
|
-
let changed = false;
|
|
974
|
-
for (const selection of selectionSet.selections) {
|
|
975
|
-
if (selection.kind === Kind4.FIELD) {
|
|
976
|
-
const schemaField = parentFields[selection.name.value];
|
|
977
|
-
if (!schemaField) {
|
|
978
|
-
newSelections.push(selection);
|
|
979
|
-
continue;
|
|
980
|
-
}
|
|
981
|
-
const scalarName = namedTypeName(schemaField.type);
|
|
982
|
-
const prefix = scalarName ? prefixFor(scalarName) : void 0;
|
|
983
|
-
if (prefix) {
|
|
984
|
-
const aliasValue = selection.alias?.value ?? selection.name.value;
|
|
985
|
-
if (aliasValue.startsWith(prefix)) {
|
|
986
|
-
newSelections.push(selection);
|
|
987
|
-
} else {
|
|
988
|
-
changed = true;
|
|
989
|
-
newSelections.push({
|
|
990
|
-
...selection,
|
|
991
|
-
alias: { kind: Kind4.NAME, value: `${prefix}${aliasValue}` }
|
|
992
|
-
});
|
|
993
|
-
}
|
|
994
|
-
continue;
|
|
995
|
-
}
|
|
996
|
-
if (selection.selectionSet) {
|
|
997
|
-
const nestedTypeName = namedCompositeName(schemaField.type);
|
|
998
|
-
if (nestedTypeName) {
|
|
999
|
-
const transformed = transformSelectionSet2(schema, selection.selectionSet, nestedTypeName);
|
|
1000
|
-
if (transformed !== selection.selectionSet) {
|
|
1001
|
-
changed = true;
|
|
1002
|
-
newSelections.push({ ...selection, selectionSet: transformed });
|
|
1003
|
-
continue;
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
}
|
|
1007
|
-
newSelections.push(selection);
|
|
1008
|
-
} else if (selection.kind === Kind4.INLINE_FRAGMENT) {
|
|
1009
|
-
const typeName = selection.typeCondition?.name.value;
|
|
1010
|
-
if (typeName && selection.selectionSet) {
|
|
1011
|
-
const type = schema.getType(typeName);
|
|
1012
|
-
if (type && isCompositeType3(type)) {
|
|
1013
|
-
const transformed = transformSelectionSet2(schema, selection.selectionSet, typeName);
|
|
1014
|
-
if (transformed !== selection.selectionSet) {
|
|
1015
|
-
changed = true;
|
|
1016
|
-
newSelections.push({ ...selection, selectionSet: transformed });
|
|
1017
|
-
continue;
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
}
|
|
1021
|
-
newSelections.push(selection);
|
|
1022
|
-
} else {
|
|
1023
|
-
newSelections.push(selection);
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
if (!changed) {
|
|
1027
|
-
return selectionSet;
|
|
1028
|
-
}
|
|
1029
|
-
return { ...selectionSet, selections: newSelections };
|
|
1030
|
-
}
|
|
1031
|
-
function namedCompositeName(type) {
|
|
1032
|
-
let current = type;
|
|
1033
|
-
while (isNonNullType5(current) || isListType5(current)) {
|
|
1034
|
-
current = current.ofType;
|
|
1035
|
-
}
|
|
1036
|
-
return isCompositeType3(current) ? current.name : void 0;
|
|
1037
|
-
}
|
|
1038
|
-
function transformScalarOperation(schema, operation) {
|
|
1039
|
-
const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
|
|
1040
|
-
if (!rootType || !operation.selectionSet) {
|
|
1041
|
-
return operation;
|
|
1042
|
-
}
|
|
1043
|
-
const transformed = transformSelectionSet2(schema, operation.selectionSet, rootType.name);
|
|
1044
|
-
if (transformed === operation.selectionSet) {
|
|
1045
|
-
return operation;
|
|
1046
|
-
}
|
|
1047
|
-
return { ...operation, selectionSet: transformed };
|
|
1048
|
-
}
|
|
1049
|
-
function transformScalarFragment(schema, fragment) {
|
|
1050
|
-
const type = schema.getType(fragment.typeCondition.name.value);
|
|
1051
|
-
if (!type || !isCompositeType3(type)) {
|
|
1052
|
-
return fragment;
|
|
1053
|
-
}
|
|
1054
|
-
const transformed = transformSelectionSet2(schema, fragment.selectionSet, type.name);
|
|
1055
|
-
if (transformed === fragment.selectionSet) {
|
|
1056
|
-
return fragment;
|
|
1057
|
-
}
|
|
1058
|
-
return { ...fragment, selectionSet: transformed };
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
// src/generate/index.ts
|
|
1062
|
-
var ctrlSeq = "\x1B[";
|
|
1063
|
-
var styled = (s, pre, post) => `${ctrlSeq}${pre}${s}${ctrlSeq}${post}`;
|
|
1064
|
-
var dim = (s) => styled(s, "2m", "22m");
|
|
1065
|
-
var bold = (s) => styled(s, "1m", "22m");
|
|
1066
|
-
var green = (s) => styled(s, "32m", "39m");
|
|
1067
|
-
var yellow = (s) => styled(s, "33m", "39m");
|
|
1068
|
-
var cyan = (s) => styled(s, "36m", "39m");
|
|
1069
|
-
function collectFragmentSpreads(fragment) {
|
|
1070
|
-
const refs = /* @__PURE__ */ new Set();
|
|
1071
|
-
visit(fragment, {
|
|
1072
|
-
[Kind5.FRAGMENT_SPREAD](node) {
|
|
1073
|
-
refs.add(node.name.value);
|
|
1074
|
-
}
|
|
1075
|
-
});
|
|
1076
|
-
return refs;
|
|
1077
|
-
}
|
|
1078
|
-
async function main() {
|
|
1079
|
-
const cwd = process.cwd();
|
|
1080
|
-
const config = await loadConfig(cwd);
|
|
1081
|
-
console.log("");
|
|
1082
|
-
console.log(`${bold("@contello/client")} ${dim("generate")}`);
|
|
1083
|
-
console.log("");
|
|
1084
|
-
for (const project of config.projects) {
|
|
1085
|
-
const start = performance.now();
|
|
1086
|
-
console.log(`${cyan("\u25CF")} ${bold(project.project)}`);
|
|
1087
|
-
rmSync(resolve2(cwd, project.output), { force: true });
|
|
1088
|
-
const schema = await introspectSchema(project.url, project.project, project.token);
|
|
1089
|
-
const patterns = Array.isArray(project.documents) ? project.documents : [project.documents];
|
|
1090
|
-
const resolvedPaths = await Promise.all(patterns.map((p) => Array.fromAsync(glob(p, { cwd }))));
|
|
1091
|
-
const documentPaths = resolvedPaths.flat().toSorted();
|
|
1092
|
-
if (documentPaths.length === 0) {
|
|
1093
|
-
console.warn(` ${yellow("\u26A0")} no documents found matching "${project.documents}"`);
|
|
1094
|
-
continue;
|
|
1095
|
-
}
|
|
1096
|
-
const documents = documentPaths.map((p) => parse2(new Source(readFileSync(resolve2(cwd, p), "utf8"), p)));
|
|
1097
|
-
const fragments = collectFragments(documents);
|
|
1098
|
-
const operations = collectOperations(documents);
|
|
1099
|
-
validateDocuments(schema, fragments, operations);
|
|
1100
|
-
const transformedFragments = new Map(
|
|
1101
|
-
[...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)])
|
|
1102
|
-
);
|
|
1103
|
-
const transformedOperations = operations.map((op) => transformOperation(schema, op, transformedFragments));
|
|
1104
|
-
for (const [name, frag] of transformedFragments) {
|
|
1105
|
-
transformedFragments.set(name, transformScalarFragment(schema, frag));
|
|
1106
|
-
}
|
|
1107
|
-
for (let i = 0; i < transformedOperations.length; i++) {
|
|
1108
|
-
transformedOperations[i] = transformScalarOperation(schema, transformedOperations[i]);
|
|
1109
|
-
}
|
|
1110
|
-
const entityBindings = indexEntitySources(schema);
|
|
1111
|
-
const builtInBindings = indexBuiltInSources(schema);
|
|
1112
|
-
const sourceEntries = [];
|
|
1113
|
-
for (const [name, fragment] of fragments) {
|
|
1114
|
-
const entityBinding = entityBindings.get(fragment.typeCondition.name.value);
|
|
1115
|
-
if (!entityBinding) {
|
|
1116
|
-
continue;
|
|
1117
|
-
}
|
|
1118
|
-
const transformed = transformedFragments.get(name);
|
|
1119
|
-
if (!transformed) {
|
|
1120
|
-
continue;
|
|
1121
|
-
}
|
|
1122
|
-
sourceEntries.push({
|
|
1123
|
-
fragmentName: name,
|
|
1124
|
-
binding: {
|
|
1125
|
-
cardinality: entityBinding.cardinality,
|
|
1126
|
-
fieldName: entityBinding.fieldName,
|
|
1127
|
-
sourceKey: entityBinding.model
|
|
1128
|
-
},
|
|
1129
|
-
fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
|
|
1130
|
-
});
|
|
1131
|
-
}
|
|
1132
|
-
for (const [typeName, builtInBinding] of builtInBindings) {
|
|
1133
|
-
const candidates = [];
|
|
1134
|
-
for (const [name, fragment] of fragments) {
|
|
1135
|
-
if (fragment.typeCondition.name.value === typeName) {
|
|
1136
|
-
candidates.push({ name, fragment });
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
if (candidates.length === 0) {
|
|
1140
|
-
continue;
|
|
1141
|
-
}
|
|
1142
|
-
const candidateNames = new Set(candidates.map((c) => c.name));
|
|
1143
|
-
const spreadByOther = /* @__PURE__ */ new Set();
|
|
1144
|
-
for (const { name, fragment } of candidates) {
|
|
1145
|
-
for (const ref of collectFragmentSpreads(fragment)) {
|
|
1146
|
-
if (ref !== name && candidateNames.has(ref)) {
|
|
1147
|
-
spreadByOther.add(ref);
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
}
|
|
1151
|
-
const roots = candidates.filter((c) => !spreadByOther.has(c.name));
|
|
1152
|
-
const picked = roots.length === 1 ? roots[0] : void 0;
|
|
1153
|
-
if (!picked) {
|
|
1154
|
-
throw new Error(
|
|
1155
|
-
`multiple fragments target the built-in type "${typeName}" without a clear root: ${candidates.map((c) => `"${c.name}"`).join(", ")}. Either have one fragment spread the others, or remove the extras.`
|
|
1156
|
-
);
|
|
1157
|
-
}
|
|
1158
|
-
const transformed = transformedFragments.get(picked.name);
|
|
1159
|
-
if (!transformed) {
|
|
1160
|
-
continue;
|
|
1161
|
-
}
|
|
1162
|
-
sourceEntries.push({
|
|
1163
|
-
fragmentName: picked.name,
|
|
1164
|
-
binding: {
|
|
1165
|
-
cardinality: builtInBinding.cardinality,
|
|
1166
|
-
fieldName: builtInBinding.fieldName,
|
|
1167
|
-
sourceKey: uncapitalize(picked.name)
|
|
1168
|
-
},
|
|
1169
|
-
fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
|
|
1170
|
-
});
|
|
1171
|
-
}
|
|
1172
|
-
const entityModels = extractEntityModels(schema);
|
|
1173
|
-
const parts = ["/* eslint-disable */", "// @ts-nocheck", "/* this file is generated by contello-client \u2014 do not edit */", ""];
|
|
1174
|
-
const typeMap = schema.getTypeMap();
|
|
1175
|
-
const clientImports = ["SourceDef"];
|
|
1176
|
-
for (const scalar of MANAGED_SCALARS) {
|
|
1177
|
-
if (typeMap[scalar]) {
|
|
1178
|
-
clientImports.push(scalar);
|
|
1179
|
-
}
|
|
1180
|
-
}
|
|
1181
|
-
parts.push(
|
|
1182
|
-
`import type { ${clientImports.toSorted().join(", ")} } from '@contello/client';`,
|
|
1183
|
-
"",
|
|
1184
|
-
generateSchemaTypes(schema),
|
|
1185
|
-
generateFragmentTypes(schema, fragments),
|
|
1186
|
-
generateOperationTypes(schema, operations, fragments)
|
|
1187
|
-
);
|
|
1188
|
-
if (transformedFragments.size > 0) {
|
|
1189
|
-
parts.push(generateFragmentSchemas(transformedFragments), "");
|
|
1190
|
-
}
|
|
1191
|
-
for (const [i, operation] of operations.entries()) {
|
|
1192
|
-
const camelName = uncapitalize(operation.name.value);
|
|
1193
|
-
const docExpr = operationDocumentExpression(transformedOperations[i], transformedFragments);
|
|
1194
|
-
parts.push(`export const ${camelName}Document = ${docExpr};`);
|
|
1195
|
-
}
|
|
1196
|
-
if (operations.length > 0) {
|
|
1197
|
-
parts.push("");
|
|
1198
|
-
}
|
|
1199
|
-
parts.push(generateOperationsType(operations), "");
|
|
1200
|
-
const sourcesTypeSrc = generateSourcesType(sourceEntries);
|
|
1201
|
-
if (sourcesTypeSrc) {
|
|
1202
|
-
parts.push(sourcesTypeSrc, "");
|
|
1203
|
-
}
|
|
1204
|
-
parts.push(generateOperationsConst(operations), "");
|
|
1205
|
-
const sourcesConstSrc = generateSourcesConst(sourceEntries);
|
|
1206
|
-
if (sourcesConstSrc) {
|
|
1207
|
-
parts.push(sourcesConstSrc, "");
|
|
1208
|
-
}
|
|
1209
|
-
if (entityModels.size > 0) {
|
|
1210
|
-
const sorted = [...entityModels.entries()].toSorted(([a], [b]) => a.localeCompare(b));
|
|
1211
|
-
parts.push("const models = {");
|
|
1212
|
-
for (const [model, typeName] of sorted) {
|
|
1213
|
-
parts.push(` ${model}: '${typeName}',`);
|
|
1214
|
-
}
|
|
1215
|
-
parts.push("} as const;", "");
|
|
1216
|
-
} else {
|
|
1217
|
-
parts.push("const models = {} as const;", "");
|
|
1218
|
-
}
|
|
1219
|
-
const sourcesPart = sourcesConstSrc ? ", sources" : ", sources: {}";
|
|
1220
|
-
parts.push(`export const schema = { operations${sourcesPart}, models };`, "export type Schema = typeof schema;");
|
|
1221
|
-
let output = parts.join("\n");
|
|
1222
|
-
if (project.namespace) {
|
|
1223
|
-
const indented = output.split("\n").map((line) => line ? ` ${line}` : "").join("\n");
|
|
1224
|
-
output = `export namespace ${project.namespace} {
|
|
1225
|
-
${indented}
|
|
1226
|
-
}
|
|
1227
|
-
`;
|
|
1228
|
-
}
|
|
1229
|
-
const outputPath = resolve2(cwd, project.output);
|
|
1230
|
-
mkdirSync(dirname(outputPath), { recursive: true });
|
|
1231
|
-
writeFileSync(outputPath, output, "utf8");
|
|
1232
|
-
const elapsed = Math.round(performance.now() - start);
|
|
1233
|
-
console.log(` ${green("\u2713")} ${relative(cwd, outputPath)} ${dim(`${elapsed}ms`)}`);
|
|
1234
|
-
console.log(` ${dim("operations")} ${operations.length} ${dim("fragments")} ${fragments.size}`);
|
|
1235
|
-
console.log("");
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
main().catch((error) => {
|
|
1239
|
-
console.error(error);
|
|
1240
|
-
process.exit(1);
|
|
1241
|
-
});
|