@contello/client 3.2.0 → 3.2.1

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.
@@ -1,1338 +0,0 @@
1
- #!/usr/bin/env node
2
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
- import { glob } from "node:fs/promises";
4
- import { dirname, relative, resolve } from "node:path";
5
- import { Kind, NoFragmentCyclesRule, NoUnusedFragmentsRule, Source, buildClientSchema, doTypesOverlap, getIntrospectionQuery, getLocation, isCompositeType, isEnumType, isInputObjectType, isInterfaceType, isListType, isNonNullType, isObjectType, isRequiredArgument, isScalarType, isUnionType, parse, print, specifiedRules, typeFromAST, validate, visit } from "graphql";
6
- import { pathToFileURL } from "node:url";
7
- //#region src/generate/config.ts
8
- const CONFIG_NAMES = [
9
- "contello.config.ts",
10
- "contello.config.js",
11
- "contello.config.mjs"
12
- ];
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)) throw new Error(`${name}: expected "projects" to be an array`);
20
- for (const [i, project] of config.projects.entries()) {
21
- if (!project.url) throw new Error(`${name}: projects[${i}].url is required`);
22
- if (!project.project) throw new Error(`${name}: projects[${i}].project is required`);
23
- if (!project.token) throw new Error(`${name}: projects[${i}].token is required`);
24
- if (!project.documents) throw new Error(`${name}: projects[${i}].documents is required`);
25
- if (!project.output) throw new Error(`${name}: projects[${i}].output is required`);
26
- }
27
- return config;
28
- } catch (error) {
29
- if (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "ENOENT") continue;
30
- throw error;
31
- }
32
- }
33
- throw new Error(`no config file found (tried: ${CONFIG_NAMES.join(", ")})`);
34
- }
35
- //#endregion
36
- //#region src/generate/documents.ts
37
- const SUPPRESSED_RULE_NAMES = /* @__PURE__ */ new Set([NoFragmentCyclesRule.name, NoUnusedFragmentsRule.name]);
38
- const VALIDATION_RULES = specifiedRules.filter((rule) => !SUPPRESSED_RULE_NAMES.has(rule.name));
39
- function collectFragments(documents) {
40
- const fragments = /* @__PURE__ */ new Map();
41
- for (const doc of documents) for (const def of doc.definitions) if (def.kind === Kind.FRAGMENT_DEFINITION) fragments.set(def.name.value, def);
42
- return fragments;
43
- }
44
- function collectOperations(documents) {
45
- const operations = [];
46
- const seen = /* @__PURE__ */ new Set();
47
- const definitions = documents.flatMap((doc) => doc.definitions);
48
- for (const def of definitions) {
49
- if (def.kind !== Kind.OPERATION_DEFINITION) continue;
50
- if (!def.name) throw new Error(`unnamed operations are not supported:\n\n${print(def)}`);
51
- if (seen.has(def.name.value)) throw new Error(`duplicate operation name: "${def.name.value}"`);
52
- seen.add(def.name.value);
53
- operations.push(def);
54
- }
55
- return operations;
56
- }
57
- function collectUsedFragments(node, allFragments, collected) {
58
- const selections = [...node.selectionSet?.selections ?? []];
59
- while (selections.length > 0) {
60
- const sel = selections.pop();
61
- if (sel.kind === Kind.FRAGMENT_SPREAD) {
62
- const name = sel.name.value;
63
- if (!collected.has(name)) {
64
- const fragment = allFragments.get(name);
65
- if (!fragment) throw new Error(`unknown fragment: "${name}"`);
66
- collected.set(name, fragment);
67
- collectUsedFragments(fragment, allFragments, collected);
68
- }
69
- } else if ("selectionSet" in sel && sel.selectionSet) selections.push(...sel.selectionSet.selections);
70
- }
71
- }
72
- function sortFragmentsByDependency(fragments) {
73
- const sorted = [];
74
- const visited = /* @__PURE__ */ new Set();
75
- function visit(name) {
76
- if (visited.has(name)) return;
77
- visited.add(name);
78
- const fragment = fragments.get(name);
79
- if (!fragment) return;
80
- const deps = /* @__PURE__ */ new Map();
81
- collectUsedFragments(fragment, fragments, deps);
82
- for (const [depName] of deps) if (depName !== name) visit(depName);
83
- sorted.push(fragment);
84
- }
85
- for (const [name] of fragments) visit(name);
86
- return sorted;
87
- }
88
- function validateDocuments(schema, fragments, operations) {
89
- const combined = {
90
- kind: Kind.DOCUMENT,
91
- definitions: [...fragments.values(), ...operations]
92
- };
93
- const errors = validate(schema, combined, VALIDATION_RULES);
94
- if (errors.length === 0) return;
95
- const formatted = errors.map((err) => {
96
- const locations = (err.nodes ?? []).map((node) => {
97
- if (!node.loc) return null;
98
- const { source, start } = node.loc;
99
- const { line, column } = getLocation(source, start);
100
- return ` at ${source.name}:${line}:${column}`;
101
- }).filter((s) => s !== null);
102
- return locations.length > 0 ? ` ${err.message}\n${locations.join("\n")}` : ` ${err.message}`;
103
- });
104
- throw new Error(`graphql validation failed:\n\n${formatted.join("\n\n")}\n`);
105
- }
106
- /**
107
- * Returns the TS-source expression for an operation's document — a template literal
108
- * interpolating each used fragment's `<Name>FragmentSchema` const on a single line
109
- * (refs joined by escaped `\n`), followed by the inlined operation body on its own
110
- * lines. The atomic schema consts are shared with sources, so the fragment text
111
- * appears once in the generated file even if reused across operations.
112
- */
113
- function operationDocumentExpression(operation, allFragments) {
114
- const usedFragments = /* @__PURE__ */ new Map();
115
- collectUsedFragments(operation, allFragments, usedFragments);
116
- const refs = sortFragmentsByDependency(usedFragments).map((f) => `\${${f.name.value}FragmentSchema}`);
117
- return `\`${(refs.length > 0 ? [refs.join(String.raw`\n`), print(operation)] : [print(operation)]).join("\n")}\``;
118
- }
119
- /**
120
- * Returns the TS-source expression for a fragment's "bundle" — the fragment plus
121
- * its transitive deps, each referenced via its shared `<Name>FragmentSchema` const.
122
- * If the fragment has no deps, returns the bare const identifier (no template wrap).
123
- */
124
- function fragmentBundleExpression(fragment, allFragments) {
125
- const usedFragments = /* @__PURE__ */ new Map();
126
- collectUsedFragments(fragment, allFragments, usedFragments);
127
- usedFragments.set(fragment.name.value, fragment);
128
- const sortedFragments = sortFragmentsByDependency(usedFragments);
129
- if (sortedFragments.length === 1) return `${sortedFragments[0].name.value}FragmentSchema`;
130
- return `\`${sortedFragments.map((f) => `\${${f.name.value}FragmentSchema}`).join(String.raw`\n`)}\``;
131
- }
132
- /** Emits `const <Name>FragmentSchema = \`...\`;` for each (transformed) fragment. */
133
- function generateFragmentSchemas(fragments) {
134
- return fragments.values().toArray().toSorted((a, b) => a.name.value.localeCompare(b.name.value)).map((fragment) => `const ${fragment.name.value}FragmentSchema = \`${print(fragment)}\`;`).join("\n");
135
- }
136
- //#endregion
137
- //#region src/generate/introspect.ts
138
- async function introspectSchema(url, project, token) {
139
- const endpoint = `${url}/graphql/projects/${project}`;
140
- const response = await fetch(endpoint, {
141
- method: "POST",
142
- headers: {
143
- "content-type": "application/json",
144
- token
145
- },
146
- body: JSON.stringify({ query: getIntrospectionQuery() })
147
- });
148
- if (!response.ok) throw new Error(`introspection failed: ${response.status} ${response.statusText} (${endpoint})`);
149
- const json = await response.json();
150
- if (json.errors?.length) throw new Error(`introspection errors: ${json.errors.map((e) => e.message).join(", ")}`);
151
- if (!json.data) throw new Error(`introspection returned no data (${endpoint})`);
152
- return buildClientSchema(json.data);
153
- }
154
- //#endregion
155
- //#region src/generate/scalar-types.ts
156
- const SCALAR_MAP = {
157
- String: "string",
158
- Int: "number",
159
- Float: "number",
160
- Boolean: "boolean",
161
- ID: "string",
162
- DateTime: "string",
163
- LocalDateTime: "LocalDateTime",
164
- LocalDate: "LocalDate"
165
- };
166
- const MANAGED_SCALARS = ["LocalDateTime", "LocalDate"];
167
- const DEFAULT_CUSTOM_SCALAR = "unknown";
168
- function resolveScalarType(name) {
169
- return SCALAR_MAP[name] ?? "unknown";
170
- }
171
- //#endregion
172
- //#region src/generate/utils.ts
173
- /** standard sorting stub */
174
- function compareCodeUnits(a, b) {
175
- if (a < b) return -1;
176
- if (a > b) return 1;
177
- return 0;
178
- }
179
- function uncapitalize(name) {
180
- return name.charAt(0).toLowerCase() + name.slice(1);
181
- }
182
- function pascalCase(name) {
183
- return name.charAt(0).toUpperCase() + name.slice(1);
184
- }
185
- function deriveModelName(typeName) {
186
- for (const suffix of ["Entity", "Component"]) if (typeName.endsWith(suffix)) return uncapitalize(typeName.slice(0, -suffix.length));
187
- }
188
- function isContelloModel(schema, typeName) {
189
- for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
190
- const union = schema.getType(unionName);
191
- if (union && typeof union === "object" && "getTypes" in union) {
192
- if (union.getTypes().some((m) => m.name === typeName)) return true;
193
- }
194
- }
195
- return false;
196
- }
197
- //#endregion
198
- //#region src/generate/operation-types.ts
199
- function unwrapType(type) {
200
- let isList = false;
201
- let isNonNull = false;
202
- let current = type;
203
- if (isNonNullType(current)) {
204
- isNonNull = true;
205
- current = current.ofType;
206
- }
207
- if (isListType(current)) {
208
- isList = true;
209
- current = current.ofType;
210
- if (isNonNullType(current)) current = current.ofType;
211
- }
212
- return {
213
- namedType: current,
214
- isList,
215
- isNonNull
216
- };
217
- }
218
- function resolveSelectionSet(schema, selectionSet, parentType, fragments, indent) {
219
- const fields = [];
220
- const inlineUnions = [];
221
- const fragmentRefs = [];
222
- let hasTypenameField = false;
223
- for (const selection of selectionSet.selections) {
224
- const contribution = resolveSelection(schema, selection, parentType, fragments, indent);
225
- fields.push(...contribution.fields);
226
- inlineUnions.push(...contribution.inlineUnions);
227
- fragmentRefs.push(...contribution.fragmentRefs);
228
- if (contribution.hasTypenameField) hasTypenameField = true;
229
- }
230
- return {
231
- fields,
232
- inlineUnions,
233
- fragmentRefs,
234
- hasTypenameField
235
- };
236
- }
237
- function resolveSelection(schema, selection, parentType, fragments, indent) {
238
- const fields = [];
239
- const inlineUnions = [];
240
- const fragmentRefs = [];
241
- switch (selection.kind) {
242
- case Kind.FIELD: {
243
- if (selection.name.value === "__typename") return {
244
- fields,
245
- inlineUnions,
246
- fragmentRefs,
247
- hasTypenameField: true
248
- };
249
- const fieldName = selection.alias?.value ?? selection.name.value;
250
- const schemaField = isObjectType(parentType) || isInterfaceType(parentType) ? parentType.getFields()[selection.name.value] : void 0;
251
- if (!schemaField) throw new Error(`field "${selection.name.value}" does not exist on type "${parentType.name}"`);
252
- const { namedType, isList, isNonNull } = unwrapType(schemaField.type);
253
- let tsType;
254
- if (selection.selectionSet && isCompositeType(namedType)) tsType = resolveSelectionSetType(schema, selection.selectionSet, namedType, fragments, `${indent} `);
255
- else if (isScalarType(namedType)) tsType = resolveScalarType(namedType.name);
256
- else if (isEnumType(namedType)) tsType = namedType.name;
257
- else tsType = namedType.toString();
258
- if (isList) tsType = `${/[ |&]/.test(tsType) ? `(${tsType})` : tsType}[]`;
259
- if (isNonNull) fields.push(`${indent} ${fieldName}: ${tsType};`);
260
- else fields.push(`${indent} ${fieldName}?: ${tsType} | undefined;`);
261
- break;
262
- }
263
- case Kind.INLINE_FRAGMENT:
264
- if (selection.typeCondition && selection.selectionSet) {
265
- const typeName = selection.typeCondition.name.value;
266
- const conditionalType = schema.getType(typeName);
267
- if (!conditionalType) throw new Error(`unknown type "${typeName}" in inline fragment`);
268
- if (isCompositeType(conditionalType)) {
269
- if (isInterfaceType(conditionalType)) {
270
- const inner = resolveSelectionSet(schema, selection.selectionSet, conditionalType, fragments, indent);
271
- fields.push(...inner.fields);
272
- fragmentRefs.push(...inner.fragmentRefs);
273
- } else if (isObjectType(conditionalType)) {
274
- const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
275
- const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
276
- if (nested.startsWith("{")) {
277
- const discriminant = model ? `${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.name}';`;
278
- inlineUnions.push(`{\n${discriminant}\n${nested.slice(2)}`);
279
- } else {
280
- const discriminant = model ? `{\n${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';\n${indent}}` : `{\n${indent} __typename: '${conditionalType.name}';\n${indent}}`;
281
- inlineUnions.push(`${discriminant} & ${nested}`);
282
- }
283
- } else {
284
- const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
285
- inlineUnions.push(nested);
286
- }
287
- }
288
- }
289
- break;
290
- case Kind.FRAGMENT_SPREAD: {
291
- const fragmentName = selection.name.value;
292
- const fragment = fragments.get(fragmentName);
293
- if (fragment?.selectionSet) {
294
- const fragmentType = schema.getType(fragment.typeCondition.name.value);
295
- if (fragmentType && isCompositeType(fragmentType)) {
296
- if (!doTypesOverlap(schema, parentType, fragmentType)) throw new Error(`fragment "${fragmentName}" (on ${fragmentType.name}) cannot be spread on type "${parentType.name}"`);
297
- fragmentRefs.push(`${fragmentName}Fragment`);
298
- }
299
- }
300
- break;
301
- }
302
- }
303
- return {
304
- fields,
305
- inlineUnions,
306
- fragmentRefs,
307
- hasTypenameField: false
308
- };
309
- }
310
- function resolveSelectionSetType(schema, selectionSet, parentType, fragments, indent) {
311
- const { fields, inlineUnions, fragmentRefs, hasTypenameField } = resolveSelectionSet(schema, selectionSet, parentType, fragments, indent);
312
- if (hasTypenameField && inlineUnions.length === 0) {
313
- const typenameField = isObjectType(parentType) ? `${indent} __typename: '${parentType.name}';` : `${indent} __typename: string;`;
314
- fields.unshift(typenameField);
315
- }
316
- if (fields.length === 0 && fragmentRefs.length === 0 && inlineUnions.length > 0) return inlineUnions.join(" | ");
317
- const parts = [];
318
- if (fields.length > 0) parts.push(`{\n${fields.join("\n")}\n${indent}}`);
319
- parts.push(...fragmentRefs);
320
- if (inlineUnions.length > 0) parts.push(`(${inlineUnions.join(" | ")})`);
321
- if (parts.length === 0) return "{}";
322
- return parts.join(" & ");
323
- }
324
- function generateVariablesType(schema, operation) {
325
- const vars = operation.variableDefinitions ?? [];
326
- if (vars.length === 0) return "Record<string, never>";
327
- const fields = [];
328
- for (const v of vars) {
329
- const varType = typeFromAST(schema, v.type);
330
- if (!varType) throw new Error(`cannot resolve type for variable "$${v.variable.name.value}"`);
331
- const isRequired = isNonNullType(varType) && !v.defaultValue;
332
- const tsType = graphqlTypeToTs(varType);
333
- if (isRequired) fields.push(` ${v.variable.name.value}: ${tsType};`);
334
- else fields.push(` ${v.variable.name.value}?: ${tsType} | undefined;`);
335
- }
336
- return `{\n${fields.join("\n")}\n}`;
337
- }
338
- function graphqlTypeToTs(type) {
339
- let current = type;
340
- while (isNonNullType(current)) current = current.ofType;
341
- if (isListType(current)) return `${graphqlTypeToTs(current.ofType)}[]`;
342
- if (isScalarType(current)) return resolveScalarType(current.name);
343
- if (isEnumType(current)) return current.name;
344
- return current.name;
345
- }
346
- function generateFragmentTypes(schema, fragments) {
347
- const lines = [];
348
- for (const [name, fragment] of fragments) {
349
- const typeName = `${name}Fragment`;
350
- const parentType = schema.getType(fragment.typeCondition.name.value);
351
- if (parentType && isCompositeType(parentType)) {
352
- const resultType = resolveSelectionSetType(schema, fragment.selectionSet, parentType, fragments, "");
353
- lines.push(`export type ${typeName} = ${resultType};`);
354
- } else lines.push(`export type ${typeName} = {};`);
355
- lines.push("");
356
- }
357
- return lines.join("\n");
358
- }
359
- function generateOperationTypes(schema, operations, fragments) {
360
- const lines = [];
361
- for (const op of operations) {
362
- const resultTypeName = `${op.name.value}${pascalCase(op.operation)}`;
363
- const variablesTypeName = `${resultTypeName}Variables`;
364
- const rootType = op.operation === "query" ? schema.getQueryType() : op.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
365
- if (rootType && op.selectionSet) {
366
- const resultType = resolveSelectionSetType(schema, op.selectionSet, rootType, fragments, "");
367
- lines.push(`export type ${resultTypeName} = ${resultType};`);
368
- } else lines.push(`export type ${resultTypeName} = {};`);
369
- lines.push("");
370
- const variablesType = generateVariablesType(schema, op);
371
- lines.push(`export type ${variablesTypeName} = ${variablesType};`, "");
372
- }
373
- return lines.join("\n");
374
- }
375
- //#endregion
376
- //#region src/generate/operations.ts
377
- /** Emits `export type Operations = { ... }`. */
378
- function generateOperationsType(operations) {
379
- const lines = ["export type Operations = {"];
380
- for (const op of operations) {
381
- const name = op.name.value;
382
- const camelName = uncapitalize(name);
383
- const resultType = `${name}${pascalCase(op.operation)}`;
384
- const variablesType = `${resultType}Variables`;
385
- lines.push(` ${camelName}: {`, ` document: string;`, ` kind: '${op.operation}';`, ` __result?: ${resultType} | undefined;`, ` __variables?: ${variablesType} | undefined;`, " };");
386
- }
387
- lines.push("};");
388
- return lines.join("\n");
389
- }
390
- /**
391
- * Emits the typed `operations` const body for inclusion in the schema bundle:
392
- * const operations: Operations = { getProducts: { document: getProductsDocument, kind: 'query' }, ... };
393
- */
394
- function generateOperationsConst(operations) {
395
- const lines = ["const operations: Operations = {"];
396
- for (const op of operations) {
397
- const camelName = uncapitalize(op.name.value);
398
- lines.push(` ${camelName}: { document: ${camelName}Document, kind: '${op.operation}' },`);
399
- }
400
- lines.push("};");
401
- return lines.join("\n");
402
- }
403
- //#endregion
404
- //#region src/generate/schema-types.ts
405
- function typeToTs(type, nonNull = false) {
406
- let current = type;
407
- let isNonNullWrapped = nonNull;
408
- while (isNonNullType(current)) {
409
- current = current.ofType;
410
- isNonNullWrapped = true;
411
- }
412
- if (isListType(current)) {
413
- const inner = typeToTs(current.ofType);
414
- const wrapped = inner.includes(" | ") ? `(${inner})` : inner;
415
- return isNonNullWrapped ? `${wrapped}[]` : `${wrapped}[] | undefined`;
416
- }
417
- const name = isScalarType(current) ? resolveScalarType(current.name) : current.name;
418
- return isNonNullWrapped ? name : `${name} | undefined`;
419
- }
420
- function inputTypeToTs(type, nonNull = false) {
421
- return typeToTs(type, nonNull);
422
- }
423
- function generateEnum(type) {
424
- const values = type.getValues().map((v) => `'${v.value}'`).toSorted(compareCodeUnits).join(" | ");
425
- return `export type ${type.name} = ${values};`;
426
- }
427
- function sortedFields(type) {
428
- return Object.values(type.getFields()).toSorted((a, b) => a.name.localeCompare(b.name));
429
- }
430
- function generateObjectType(type, modelNames) {
431
- const fields = sortedFields(type);
432
- const lines = [];
433
- const model = modelNames.get(type.name);
434
- lines.push(`export type ${type.name} = {`, ` __typename?: '${type.name}' | undefined;`);
435
- if (model) lines.push(` __model?: '${model}' | undefined;`);
436
- for (const field of fields) {
437
- if (isTransportField(field.name)) continue;
438
- lines.push(` ${field.name}${isNonNullType(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
439
- }
440
- lines.push("};");
441
- return lines.join("\n");
442
- }
443
- function generateInputType(type) {
444
- const fields = sortedFields(type);
445
- const lines = [`export type ${type.name} = {`];
446
- for (const field of fields) lines.push(` ${field.name}${isNonNullType(field.type) ? "" : "?"}: ${inputTypeToTs(field.type)};`);
447
- lines.push("};");
448
- return lines.join("\n");
449
- }
450
- function generateUnion(type) {
451
- const members = type.getTypes().map((t) => t.name).toSorted(compareCodeUnits);
452
- return `export type ${type.name} = ${members.join(" | ")};`;
453
- }
454
- function isInternalType(name) {
455
- return name.startsWith("__");
456
- }
457
- const FLAT_PREFIX$1 = "_flat_";
458
- function isTransportField(name) {
459
- return name.startsWith(FLAT_PREFIX$1);
460
- }
461
- function generateSchemaTypes(schema) {
462
- const typeMap = schema.getTypeMap();
463
- const lines = [];
464
- const byName = (a, b) => a.name.localeCompare(b.name);
465
- const customScalars = Object.values(typeMap).filter((t) => isScalarType(t) && !isInternalType(t.name) && !Object.hasOwn(SCALAR_MAP, t.name)).toSorted(byName);
466
- if (customScalars.length > 0) {
467
- for (const scalar of customScalars) lines.push(`export type ${scalar.name} = ${DEFAULT_CUSTOM_SCALAR};`);
468
- lines.push("");
469
- }
470
- const enums = Object.values(typeMap).filter((t) => isEnumType(t) && !isInternalType(t.name)).toSorted(byName);
471
- for (const e of enums) lines.push(generateEnum(e));
472
- if (enums.length > 0) lines.push("");
473
- const inputs = Object.values(typeMap).filter((t) => isInputObjectType(t) && !isInternalType(t.name)).toSorted(byName);
474
- for (const input of inputs) lines.push(generateInputType(input), "");
475
- const modelNames = /* @__PURE__ */ new Map();
476
- const entityModelNames = /* @__PURE__ */ new Map();
477
- for (const unionName of ["ContelloEntity", "ContelloComponent"]) {
478
- const union = typeMap[unionName];
479
- if (union && isUnionType(union)) for (const member of union.getTypes()) {
480
- const model = deriveModelName(member.name);
481
- if (model) {
482
- modelNames.set(member.name, model);
483
- if (unionName === "ContelloEntity") entityModelNames.set(member.name, model);
484
- }
485
- }
486
- }
487
- const objects = Object.values(typeMap).filter((t) => isObjectType(t) && !isInternalType(t.name)).toSorted(byName);
488
- for (const obj of objects) lines.push(generateObjectType(obj, modelNames), "");
489
- const interfaces = Object.values(typeMap).filter((t) => isInterfaceType(t) && !isInternalType(t.name)).toSorted(byName);
490
- for (const iface of interfaces) {
491
- const fields = Object.values(iface.getFields()).filter((field) => !isTransportField(field.name)).toSorted((a, b) => a.name.localeCompare(b.name));
492
- const fieldLines = [`export type ${iface.name} = {`, ` __typename?: string | undefined;`];
493
- for (const field of fields) fieldLines.push(` ${field.name}${isNonNullType(field.type) ? "" : "?"}: ${typeToTs(field.type)};`);
494
- fieldLines.push("};");
495
- lines.push(fieldLines.join("\n"), "");
496
- }
497
- const unions = Object.values(typeMap).filter((t) => isUnionType(t) && !isInternalType(t.name)).toSorted(byName);
498
- for (const union of unions) lines.push(generateUnion(union));
499
- if (unions.length > 0) lines.push("");
500
- return lines.join("\n");
501
- }
502
- /**
503
- * Returns the model-reference-name → typename map for entities in `ContelloEntity`.
504
- * Used by the schema bundle assembly to emit `models: { category: 'CategoryEntity', ... }`.
505
- */
506
- function extractEntityModels(schema) {
507
- const map = /* @__PURE__ */ new Map();
508
- const union = schema.getTypeMap()["ContelloEntity"];
509
- if (!union || !isUnionType(union)) return map;
510
- for (const member of union.getTypes()) {
511
- const model = deriveModelName(member.name);
512
- if (model) map.set(model, member.name);
513
- }
514
- return map;
515
- }
516
- //#endregion
517
- //#region src/built-in-mutations.ts
518
- /**
519
- * Write bindings for the built-in sources. Unlike entity mutations these are not derived — their
520
- * field and argument names are fixed parts of every Contello schema — but the generator still
521
- * checks each one against the introspected schema before emitting it, so a server without them
522
- * (or with a different shape) simply yields a read-only source.
523
- *
524
- * Routes are the odd ones: `updateContelloRoute` is keyed by the `path` inside its input rather
525
- * than by an id, and it replaces the route rather than patching it. `deleteContelloRoute` takes a
526
- * bare `id` and answers with a bare id string.
527
- *
528
- * Assets have no `create` — an asset comes into being through `client.upload()`, not a mutation.
529
- */
530
- const BUILT_IN_MUTATIONS = {
531
- route: {
532
- create: {
533
- field: "createContelloRoute",
534
- arguments: [{
535
- name: "route",
536
- type: "ContelloRouteInput!",
537
- from: "input"
538
- }],
539
- result: "entity"
540
- },
541
- update: {
542
- field: "updateContelloRoute",
543
- arguments: [{
544
- name: "route",
545
- type: "ContelloRouteInput!",
546
- from: "input"
547
- }],
548
- result: "entity"
549
- },
550
- delete: {
551
- field: "deleteContelloRoute",
552
- arguments: [{
553
- name: "id",
554
- type: "String",
555
- from: "id"
556
- }],
557
- result: "idScalar"
558
- }
559
- },
560
- asset: {
561
- update: {
562
- field: "updateContelloAsset",
563
- arguments: [{
564
- name: "request",
565
- type: "ContelloAssetUpdateInput!",
566
- from: "input"
567
- }],
568
- result: "entity"
569
- },
570
- delete: {
571
- field: "deleteContelloAsset",
572
- arguments: [{
573
- name: "id",
574
- type: "String!",
575
- from: "id"
576
- }],
577
- result: "idObject"
578
- }
579
- }
580
- };
581
- //#endregion
582
- //#region src/generate/sources.ts
583
- /** Built-in (non-entity) types that are source-able through dedicated Subscription fields. */
584
- const BUILT_IN_SOURCES = [
585
- {
586
- typeName: "ContelloRoute",
587
- cardinality: "route",
588
- fieldName: "contelloRoutesBatch"
589
- },
590
- {
591
- typeName: "ContelloAsset",
592
- cardinality: "asset",
593
- fieldName: "contelloAssetsBatch"
594
- },
595
- {
596
- typeName: "ContelloI18nMessage",
597
- cardinality: "i18nMessage",
598
- fieldName: "contelloI18nMessagesBatch"
599
- }
600
- ];
601
- /**
602
- * Walks Subscription fields once and indexes, for each contello-entity type, the
603
- * subscription that feeds the store (a `[Entity!]!` field → entity-collection; a non-list
604
- * `Entity` field → singleton). Types without a matching Subscription field don't
605
- * appear in the map and stay non-source-able.
606
- */
607
- function indexEntitySources(schema) {
608
- const result = /* @__PURE__ */ new Map();
609
- const subscription = schema.getSubscriptionType();
610
- if (!subscription) return result;
611
- const singletonCandidates = /* @__PURE__ */ new Map();
612
- for (const field of Object.values(subscription.getFields())) {
613
- const { entityType, isList } = unwrapEntity(field.type);
614
- if (!entityType || !isContelloModel(schema, entityType.name)) continue;
615
- const model = deriveModelName(entityType.name);
616
- if (!model) continue;
617
- if (isList) result.set(entityType.name, {
618
- cardinality: "entity",
619
- fieldName: field.name,
620
- model
621
- });
622
- else if (!singletonCandidates.has(entityType.name)) singletonCandidates.set(entityType.name, { fieldName: field.name });
623
- }
624
- for (const [typeName, { fieldName }] of singletonCandidates) {
625
- if (result.has(typeName)) continue;
626
- const model = deriveModelName(typeName);
627
- if (!model) continue;
628
- result.set(typeName, {
629
- cardinality: "singleton",
630
- fieldName,
631
- model
632
- });
633
- }
634
- return result;
635
- }
636
- /**
637
- * Indexes the built-in (route/asset/i18nMessage) types that the schema actually exposes
638
- * as batch subscriptions. A type is included only when both the GraphQL type and the
639
- * matching subscription field are present.
640
- */
641
- function indexBuiltInSources(schema) {
642
- const result = /* @__PURE__ */ new Map();
643
- const subscription = schema.getSubscriptionType();
644
- if (!subscription) return result;
645
- const fields = subscription.getFields();
646
- for (const builtIn of BUILT_IN_SOURCES) {
647
- if (!schema.getType(builtIn.typeName) || !Object.hasOwn(fields, builtIn.fieldName)) continue;
648
- result.set(builtIn.typeName, {
649
- cardinality: builtIn.cardinality,
650
- fieldName: builtIn.fieldName
651
- });
652
- }
653
- return result;
654
- }
655
- const MUTATION_KINDS = [
656
- "create",
657
- "update",
658
- "delete"
659
- ];
660
- /**
661
- * A create/update mutation answers with the entity itself; a delete answers with a response
662
- * object. Both are only ever selected down to `id`, so the requirement is structural: the
663
- * return type must be an object type carrying an `id` field, and for create/update it must be
664
- * the entity type the source is bound to.
665
- */
666
- function returnsEntityId(type, entityTypeName) {
667
- const { entityType, isList } = unwrapEntity(type);
668
- if (!entityType || isList) return false;
669
- if (entityTypeName !== void 0 && entityType.name !== entityTypeName) return false;
670
- return Object.hasOwn(entityType.getFields(), "id");
671
- }
672
- /**
673
- * Unwraps a one-field envelope argument (`CreateCategoryRequestInput { entity: ... }`) so the
674
- * accessor takes the entity input directly. Only a single non-null input-object field is
675
- * unwrapped — anything else (lists, scalars, several fields) is passed through as-is.
676
- */
677
- function resolveArgumentInput(type) {
678
- const fields = Object.values(type.getFields());
679
- const only = fields.length === 1 ? fields[0] : void 0;
680
- if (only && isNonNullType(only.type) && isInputObjectType(only.type.ofType)) return {
681
- envelope: only.name,
682
- inputTypeName: only.type.ofType.name
683
- };
684
- return {
685
- envelope: void 0,
686
- inputTypeName: type.name
687
- };
688
- }
689
- function indexMutationsForModel(mutationType, model, entityTypeName) {
690
- const fields = mutationType.getFields();
691
- const result = {};
692
- for (const kind of MUTATION_KINDS) {
693
- const field = fields[`${kind}${pascalCase(model)}`];
694
- if (!field || field.args.length !== 1) continue;
695
- if (!returnsEntityId(field.type, kind === "delete" ? void 0 : entityTypeName)) continue;
696
- const argument = field.args[0];
697
- const argumentNamedType = isNonNullType(argument.type) ? argument.type.ofType : argument.type;
698
- if (!isInputObjectType(argumentNamedType)) continue;
699
- const { envelope, inputTypeName } = resolveArgumentInput(argumentNamedType);
700
- result[kind] = {
701
- field: field.name,
702
- arguments: [{
703
- name: argument.name,
704
- type: argument.type.toString(),
705
- from: "input",
706
- ...envelope !== void 0 && { envelope }
707
- }],
708
- result: kind === "delete" ? "idObject" : "entity",
709
- inputType: inputTypeName
710
- };
711
- }
712
- return result;
713
- }
714
- /**
715
- * TS input types for the built-in write bindings. Route and asset inputs are fixed schema types;
716
- * a delete is addressed by id alone, so its input type is spelled out rather than named.
717
- */
718
- const BUILT_IN_INPUT_TYPES = {
719
- route: {
720
- create: "ContelloRouteInput",
721
- update: "ContelloRouteInput",
722
- delete: "{ id: string }"
723
- },
724
- asset: {
725
- update: "ContelloAssetUpdateInput",
726
- delete: "{ id: string }"
727
- }
728
- };
729
- /**
730
- * Checks one built-in binding against the introspected schema: the field must exist, carry every
731
- * bound argument, leave no required argument unbound, and answer with the shape the binding
732
- * declares. A server that renamed, dropped or added to any of it yields no binding at all rather
733
- * than a document that fails at request time.
734
- */
735
- function verifyBuiltInMutation(mutationType, binding, typeName) {
736
- const field = mutationType.getFields()[binding.field];
737
- if (!field) return;
738
- const args = binding.arguments.map((argument) => {
739
- const schemaArgument = field.args.find((a) => a.name === argument.name);
740
- return schemaArgument ? {
741
- ...argument,
742
- type: schemaArgument.type.toString()
743
- } : void 0;
744
- });
745
- if (args.includes(void 0)) return;
746
- const bound = new Set(binding.arguments.map((argument) => argument.name));
747
- if (field.args.some((argument) => !bound.has(argument.name) && isRequiredArgument(argument))) return;
748
- const answersWithEntity = returnsEntityId(field.type, typeName);
749
- if (!(binding.result === "entity" ? answersWithEntity : binding.result === "idObject" ? returnsEntityId(field.type, void 0) : isScalarResult(field.type))) return;
750
- return {
751
- ...binding,
752
- arguments: args
753
- };
754
- }
755
- function isScalarResult(type) {
756
- return isScalarType(isNonNullType(type) ? type.ofType : type);
757
- }
758
- function verifyBuiltInMutations(mutationType, typeName, declared, inputTypes) {
759
- const bindings = {};
760
- for (const kind of MUTATION_KINDS) {
761
- const binding = declared[kind];
762
- const inputType = inputTypes[kind];
763
- const verified = binding && inputType ? verifyBuiltInMutation(mutationType, binding, typeName) : void 0;
764
- if (verified && inputType) bindings[kind] = {
765
- ...verified,
766
- inputType
767
- };
768
- }
769
- return bindings;
770
- }
771
- /**
772
- * Indexes the write mutations of the built-in sources the schema actually exposes, keyed by
773
- * cardinality. Bindings are fixed (their field names are part of every Contello schema) but each
774
- * one is verified before it is emitted.
775
- */
776
- function indexBuiltInMutations(schema, builtInBindings) {
777
- const result = /* @__PURE__ */ new Map();
778
- const mutationType = schema.getMutationType();
779
- if (!mutationType) return result;
780
- for (const [typeName, { cardinality }] of builtInBindings) {
781
- const declared = BUILT_IN_MUTATIONS[cardinality];
782
- const inputTypes = BUILT_IN_INPUT_TYPES[cardinality];
783
- if (!declared || !inputTypes) continue;
784
- const bindings = verifyBuiltInMutations(mutationType, typeName, declared, inputTypes);
785
- if (Object.keys(bindings).length > 0) result.set(cardinality, bindings);
786
- }
787
- return result;
788
- }
789
- /**
790
- * Indexes the write mutations each entity source can bind to, keyed by model reference name.
791
- * A model with no mutations at all is left out of the map; a model missing one kind gets the
792
- * others — singletons, for one, have no `create`.
793
- */
794
- function indexEntityMutations(schema, entityBindings) {
795
- const result = /* @__PURE__ */ new Map();
796
- const mutationType = schema.getMutationType();
797
- if (!mutationType) return result;
798
- for (const [entityTypeName, binding] of entityBindings) {
799
- const bindings = indexMutationsForModel(mutationType, binding.model, entityTypeName);
800
- if (Object.keys(bindings).length > 0) result.set(binding.model, bindings);
801
- }
802
- return result;
803
- }
804
- function unwrapEntity(type) {
805
- let current = type;
806
- let isList = false;
807
- if (isNonNullType(current)) current = current.ofType;
808
- if (isListType(current)) {
809
- isList = true;
810
- current = current.ofType;
811
- if (isNonNullType(current)) current = current.ofType;
812
- }
813
- return {
814
- entityType: isObjectType(current) ? current : void 0,
815
- isList
816
- };
817
- }
818
- /**
819
- * Dedupe + sort entries by source key. Throws on duplicates.
820
- */
821
- function organize(entries) {
822
- const byKey = /* @__PURE__ */ new Map();
823
- for (const entry of entries) {
824
- const existing = byKey.get(entry.binding.sourceKey);
825
- if (existing) throw new Error(`multiple fragments target the same source key "${entry.binding.sourceKey}": "${existing.fragmentName}" and "${entry.fragmentName}". A source key can have at most one fragment — merge the fragments or use the raw client for the alternative shape.`);
826
- byKey.set(entry.binding.sourceKey, entry);
827
- }
828
- return byKey.values().toArray().toSorted((a, b) => a.binding.sourceKey.localeCompare(b.binding.sourceKey));
829
- }
830
- /** Emits `export type Sources = { ... }`. */
831
- function generateSourcesType(entries) {
832
- const sorted = organize(entries);
833
- if (sorted.length === 0) return "";
834
- const lines = ["export type Sources = {"];
835
- for (const { fragmentName, binding, mutations } of sorted) {
836
- const writes = generateWritesType(mutations);
837
- const args = [
838
- `'${binding.sourceKey}'`,
839
- `'${binding.cardinality}'`,
840
- `${fragmentName}Fragment`
841
- ];
842
- if (writes) args.push(writes);
843
- lines.push(` ${binding.sourceKey}: SourceDef<${args.join(", ")}>;`);
844
- }
845
- lines.push("};");
846
- return lines.join("\n");
847
- }
848
- /** Emits `const sources: Sources = { ... }` for inclusion in the schema bundle. */
849
- function generateSourcesConst(entries) {
850
- const sorted = organize(entries);
851
- if (sorted.length === 0) return "";
852
- const lines = ["const sources: Sources = {"];
853
- for (const { fragmentName, binding, fragmentExpression, mutations } of sorted) {
854
- lines.push(` ${binding.sourceKey}: {`, ` document: ${fragmentExpression},`, ` fragment: '${fragmentName}',`, ` subscription: '${binding.fieldName}',`);
855
- for (const line of generateMutationsConst(mutations)) lines.push(line);
856
- lines.push(` __model: '${binding.sourceKey}',`, ` __cardinality: '${binding.cardinality}',`, ` },`);
857
- }
858
- lines.push("};");
859
- return lines.join("\n");
860
- }
861
- /** The phantom write shape — `{ create: CreateCategoryEntityInput; ... }`, omitted when there are no mutations. */
862
- function generateWritesType(mutations) {
863
- const entries = mutationEntries(mutations);
864
- if (entries.length === 0) return;
865
- return `{ ${entries.map(([kind, binding]) => `${kind}: ${binding.inputType}`).join("; ")} }`;
866
- }
867
- /** The runtime `mutations` object of a source const. */
868
- function generateMutationsConst(mutations) {
869
- const entries = mutationEntries(mutations);
870
- if (entries.length === 0) return [];
871
- const lines = [" mutations: {"];
872
- for (const [kind, binding] of entries) {
873
- const args = binding.arguments.map((argument) => {
874
- const parts = [
875
- `name: '${argument.name}'`,
876
- `type: '${argument.type}'`,
877
- `from: '${argument.from}'`
878
- ];
879
- if (argument.envelope) parts.push(`envelope: '${argument.envelope}'`);
880
- return `{ ${parts.join(", ")} }`;
881
- }).join(", ");
882
- lines.push(` ${kind}: { field: '${binding.field}', arguments: [${args}], result: '${binding.result}' },`);
883
- }
884
- lines.push(" },");
885
- return lines;
886
- }
887
- function mutationEntries(mutations) {
888
- return MUTATION_KINDS.flatMap((kind) => {
889
- const binding = mutations?.[kind];
890
- return binding ? [[kind, binding]] : [];
891
- });
892
- }
893
- //#endregion
894
- //#region src/generate/transform-components.ts
895
- const FLAT_PREFIX = "_flat_";
896
- const FLAT_COMPONENT_TYPE = "ContelloFlatComponent";
897
- const COMPONENT_UNION = "ContelloComponent";
898
- /**
899
- * checks if a schema type (unwrapped from list/non-null) is the ContelloComponent union.
900
- */
901
- function isComponentUnion(schema, typeName) {
902
- const type = schema.getType(typeName);
903
- return !!type && isUnionType(type) && type.name === COMPONENT_UNION;
904
- }
905
- /**
906
- * checks if a named object type is a member of the ContelloComponent union
907
- * (i.e. a concrete component type like `TextComponent`, `SectionComponent`, `ContelloFlatComponent`).
908
- */
909
- function isComponentSubtype(schema, typeName) {
910
- const union = schema.getType(COMPONENT_UNION);
911
- if (!union || !isUnionType(union)) return false;
912
- return union.getTypes().some((t) => t.name === typeName);
913
- }
914
- /**
915
- * unwraps NonNull and List wrappers to get the named type.
916
- */
917
- function getNamedTypeName(type) {
918
- let current = type;
919
- while (isNonNullType(current) || isListType(current)) current = current.ofType;
920
- return current?.name;
921
- }
922
- /**
923
- * the flat ref selection for the `_flat_*` companion: `{ __typename ... on ContelloFlatComponent { _flatId } }`.
924
- * `__typename` is kept here because the companion carries the full components and the runtime derives
925
- * `__model` from it.
926
- */
927
- const FLAT_REF_SELECTIONS = parse(`{ __typename ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
928
- /**
929
- * the lightweight ref selection for the inline component field: `{ ... on ContelloFlatComponent { _flatId } }`.
930
- * only `_flatId` is needed — the runtime resolves these refs against the `_flat_*` companion by id and never
931
- * reads their `__typename`, so it is omitted to keep the wire payload small.
932
- */
933
- const FLAT_REF_ONLY_SELECTIONS = parse(`{ ... on ${FLAT_COMPONENT_TYPE} { _flatId } }`).definitions.flatMap((d) => "selectionSet" in d ? [d.selectionSet] : [])[0];
934
- /**
935
- * checks if a fragment on ContelloComponent already has the FlatComponent pattern
936
- * (i.e. already has `... on ContelloFlatComponent { _flatId }`)
937
- */
938
- function hasExistingFlatSpread(selectionSet) {
939
- return selectionSet.selections.some((s) => s.kind === Kind.INLINE_FRAGMENT && s.typeCondition?.name.value === FLAT_COMPONENT_TYPE);
940
- }
941
- /**
942
- * adds flat ref selections (__typename + ... on ContelloFlatComponent { _flatId })
943
- * to a selection set, if not already present.
944
- */
945
- function addFlatRefSelections(selectionSet) {
946
- if (hasExistingFlatSpread(selectionSet)) return selectionSet;
947
- return {
948
- ...selectionSet,
949
- selections: [...FLAT_REF_SELECTIONS.selections, ...selectionSet.selections]
950
- };
951
- }
952
- /**
953
- * transforms a selection set by rewriting ContelloComponent fields:
954
- * - the original field gets flat ref selections only
955
- * - a `_flat_{fieldName}` sibling is added with the original selections + flat refs
956
- */
957
- function transformSelectionSet$1(schema, selectionSet, parentTypeName, fragments, refsOnly = false) {
958
- const parentType = schema.getType(parentTypeName);
959
- if (!parentType || !isObjectType(parentType)) return selectionSet;
960
- const parentFields = parentType.getFields();
961
- const newSelections = [];
962
- let changed = false;
963
- function recurse(node, typeName) {
964
- if (!node.selectionSet) {
965
- newSelections.push(node);
966
- return;
967
- }
968
- const transformed = transformSelectionSet$1(schema, node.selectionSet, typeName, fragments, refsOnly);
969
- if (transformed === node.selectionSet) newSelections.push(node);
970
- else {
971
- changed = true;
972
- newSelections.push({
973
- ...node,
974
- selectionSet: transformed
975
- });
976
- }
977
- }
978
- for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
979
- const fieldName = selection.name.value;
980
- const schemaField = parentFields[fieldName];
981
- if (!schemaField) {
982
- newSelections.push(selection);
983
- continue;
984
- }
985
- const namedTypeName = getNamedTypeName(schemaField.type);
986
- if (namedTypeName && isComponentUnion(schema, namedTypeName) && selection.selectionSet) {
987
- const flatFieldName = `${FLAT_PREFIX}${fieldName}`;
988
- if (!Object.hasOwn(parentFields, flatFieldName)) {
989
- newSelections.push(selection);
990
- continue;
991
- }
992
- changed = true;
993
- newSelections.push({
994
- ...selection,
995
- selectionSet: FLAT_REF_ONLY_SELECTIONS
996
- });
997
- if (!refsOnly) newSelections.push({
998
- kind: Kind.FIELD,
999
- name: {
1000
- kind: Kind.NAME,
1001
- value: flatFieldName
1002
- },
1003
- selectionSet: addFlatRefSelections(selection.selectionSet)
1004
- });
1005
- } else if (namedTypeName) recurse(selection, namedTypeName);
1006
- else newSelections.push(selection);
1007
- } else if (selection.kind === Kind.INLINE_FRAGMENT) {
1008
- const typeName = selection.typeCondition?.name.value;
1009
- const type = typeName ? schema.getType(typeName) : void 0;
1010
- if (typeName && type && isCompositeType(type) && isObjectType(type)) recurse(selection, typeName);
1011
- else newSelections.push(selection);
1012
- } else newSelections.push(selection);
1013
- if (!changed) return selectionSet;
1014
- return {
1015
- ...selectionSet,
1016
- selections: newSelections
1017
- };
1018
- }
1019
- /**
1020
- * transforms an operation by rewriting ContelloComponent fields in the query.
1021
- * returns the original operation if no transform was needed.
1022
- */
1023
- function transformOperation(schema, operation, fragments) {
1024
- const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
1025
- if (!rootType || !operation.selectionSet) return operation;
1026
- const transformed = transformSelectionSet$1(schema, operation.selectionSet, rootType.name, fragments);
1027
- if (transformed === operation.selectionSet) return operation;
1028
- return {
1029
- ...operation,
1030
- selectionSet: transformed
1031
- };
1032
- }
1033
- /**
1034
- * transforms a fragment definition by rewriting ContelloComponent fields.
1035
- * also ensures fragments on ContelloComponent include flat ref selections.
1036
- */
1037
- function transformFragment(schema, fragment, fragments) {
1038
- const typeName = fragment.typeCondition.name.value;
1039
- const type = schema.getType(typeName);
1040
- if (!type || !isCompositeType(type)) return fragment;
1041
- let selectionSet = fragment.selectionSet;
1042
- if (typeName === COMPONENT_UNION) selectionSet = addFlatRefSelections(selectionSet);
1043
- if (isObjectType(type)) {
1044
- const refsOnly = isComponentSubtype(schema, typeName);
1045
- selectionSet = transformSelectionSet$1(schema, selectionSet, typeName, fragments, refsOnly);
1046
- } else if (isUnionType(type)) {
1047
- const newSelections = selectionSet.selections.map((sel) => {
1048
- if (sel.kind === Kind.INLINE_FRAGMENT && sel.typeCondition && sel.selectionSet) {
1049
- const inlineTypeName = sel.typeCondition.name.value;
1050
- const inlineType = schema.getType(inlineTypeName);
1051
- if (inlineType && isObjectType(inlineType)) {
1052
- const transformed = transformSelectionSet$1(schema, sel.selectionSet, inlineTypeName, fragments, true);
1053
- if (transformed !== sel.selectionSet) return {
1054
- ...sel,
1055
- selectionSet: transformed
1056
- };
1057
- }
1058
- }
1059
- return sel;
1060
- });
1061
- selectionSet = {
1062
- ...selectionSet,
1063
- selections: newSelections
1064
- };
1065
- }
1066
- if (selectionSet === fragment.selectionSet) return fragment;
1067
- return {
1068
- ...fragment,
1069
- selectionSet
1070
- };
1071
- }
1072
- //#endregion
1073
- //#region src/generate/transform-scalars.ts
1074
- const SCALAR_PREFIX = {
1075
- LocalDateTime: "_ldt_",
1076
- LocalDate: "_ld_"
1077
- };
1078
- function namedTypeName(type) {
1079
- let current = type;
1080
- while (isNonNullType(current) || isListType(current)) current = current.ofType;
1081
- return isScalarType(current) ? current.name : void 0;
1082
- }
1083
- function prefixFor(typeName) {
1084
- return SCALAR_PREFIX[typeName];
1085
- }
1086
- /**
1087
- * walks a selection set and aliases scalar fields whose type is a managed scalar
1088
- * (LocalDateTime, LocalDate) with a marker prefix. the runtime transform reads the
1089
- * prefix, decodes the wire string to a struct, and renames the key back.
1090
- *
1091
- * recurses through nested object selections and inline fragments — fragment spreads
1092
- * are left intact (their definitions are transformed separately).
1093
- */
1094
- function transformSelectionSet(schema, selectionSet, parentTypeName) {
1095
- const parentType = schema.getType(parentTypeName);
1096
- if (!parentType || !isObjectType(parentType) && !isInterfaceType(parentType)) return selectionSet;
1097
- const parentFields = parentType.getFields();
1098
- const newSelections = [];
1099
- let changed = false;
1100
- for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
1101
- const schemaField = parentFields[selection.name.value];
1102
- if (!schemaField) {
1103
- newSelections.push(selection);
1104
- continue;
1105
- }
1106
- const scalarName = namedTypeName(schemaField.type);
1107
- const prefix = scalarName ? prefixFor(scalarName) : void 0;
1108
- if (prefix) {
1109
- const aliasValue = selection.alias?.value ?? selection.name.value;
1110
- if (aliasValue.startsWith(prefix)) newSelections.push(selection);
1111
- else {
1112
- changed = true;
1113
- newSelections.push({
1114
- ...selection,
1115
- alias: {
1116
- kind: Kind.NAME,
1117
- value: `${prefix}${aliasValue}`
1118
- }
1119
- });
1120
- }
1121
- continue;
1122
- }
1123
- if (selection.selectionSet) {
1124
- const nestedTypeName = namedCompositeName(schemaField.type);
1125
- if (nestedTypeName) {
1126
- const transformed = transformSelectionSet(schema, selection.selectionSet, nestedTypeName);
1127
- if (transformed !== selection.selectionSet) {
1128
- changed = true;
1129
- newSelections.push({
1130
- ...selection,
1131
- selectionSet: transformed
1132
- });
1133
- continue;
1134
- }
1135
- }
1136
- }
1137
- newSelections.push(selection);
1138
- } else if (selection.kind === Kind.INLINE_FRAGMENT) {
1139
- const typeName = selection.typeCondition?.name.value;
1140
- if (typeName && selection.selectionSet) {
1141
- const type = schema.getType(typeName);
1142
- if (type && isCompositeType(type)) {
1143
- const transformed = transformSelectionSet(schema, selection.selectionSet, typeName);
1144
- if (transformed !== selection.selectionSet) {
1145
- changed = true;
1146
- newSelections.push({
1147
- ...selection,
1148
- selectionSet: transformed
1149
- });
1150
- continue;
1151
- }
1152
- }
1153
- }
1154
- newSelections.push(selection);
1155
- } else newSelections.push(selection);
1156
- if (!changed) return selectionSet;
1157
- return {
1158
- ...selectionSet,
1159
- selections: newSelections
1160
- };
1161
- }
1162
- function namedCompositeName(type) {
1163
- let current = type;
1164
- while (isNonNullType(current) || isListType(current)) current = current.ofType;
1165
- return isCompositeType(current) ? current.name : void 0;
1166
- }
1167
- function transformScalarOperation(schema, operation) {
1168
- const rootType = operation.operation === "query" ? schema.getQueryType() : operation.operation === "mutation" ? schema.getMutationType() : schema.getSubscriptionType();
1169
- if (!rootType || !operation.selectionSet) return operation;
1170
- const transformed = transformSelectionSet(schema, operation.selectionSet, rootType.name);
1171
- if (transformed === operation.selectionSet) return operation;
1172
- return {
1173
- ...operation,
1174
- selectionSet: transformed
1175
- };
1176
- }
1177
- function transformScalarFragment(schema, fragment) {
1178
- const type = schema.getType(fragment.typeCondition.name.value);
1179
- if (!type || !isCompositeType(type)) return fragment;
1180
- const transformed = transformSelectionSet(schema, fragment.selectionSet, type.name);
1181
- if (transformed === fragment.selectionSet) return fragment;
1182
- return {
1183
- ...fragment,
1184
- selectionSet: transformed
1185
- };
1186
- }
1187
- //#endregion
1188
- //#region src/generate/index.ts
1189
- const ctrlSeq = "\x1B[";
1190
- const styled = (s, pre, post) => `${ctrlSeq}${pre}${s}${ctrlSeq}${post}`;
1191
- const dim = (s) => styled(s, "2m", "22m");
1192
- const bold = (s) => styled(s, "1m", "22m");
1193
- const green = (s) => styled(s, "32m", "39m");
1194
- const yellow = (s) => styled(s, "33m", "39m");
1195
- const cyan = (s) => styled(s, "36m", "39m");
1196
- function collectFragmentSpreads(fragment) {
1197
- const refs = /* @__PURE__ */ new Set();
1198
- visit(fragment, { [Kind.FRAGMENT_SPREAD](node) {
1199
- refs.add(node.name.value);
1200
- } });
1201
- return refs;
1202
- }
1203
- function collectEntitySourceEntries(fragments, entityBindings, transformedFragments, mutationBindings) {
1204
- const entries = [];
1205
- for (const [name, fragment] of fragments) {
1206
- const entityBinding = entityBindings.get(fragment.typeCondition.name.value);
1207
- if (!entityBinding) continue;
1208
- const transformed = transformedFragments.get(name);
1209
- if (!transformed) continue;
1210
- entries.push({
1211
- fragmentName: name,
1212
- binding: {
1213
- cardinality: entityBinding.cardinality,
1214
- fieldName: entityBinding.fieldName,
1215
- sourceKey: entityBinding.model
1216
- },
1217
- fragmentExpression: fragmentBundleExpression(transformed, transformedFragments),
1218
- mutations: mutationBindings.get(entityBinding.model)
1219
- });
1220
- }
1221
- return entries;
1222
- }
1223
- function collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments, mutationBindings) {
1224
- const entries = [];
1225
- for (const [typeName, builtInBinding] of builtInBindings) {
1226
- const candidates = [];
1227
- for (const [name, fragment] of fragments) if (fragment.typeCondition.name.value === typeName) candidates.push({
1228
- name,
1229
- fragment
1230
- });
1231
- if (candidates.length === 0) continue;
1232
- const candidateNames = new Set(candidates.map((c) => c.name));
1233
- const spreadByOther = /* @__PURE__ */ new Set();
1234
- for (const { name, fragment } of candidates) for (const ref of collectFragmentSpreads(fragment)) if (ref !== name && candidateNames.has(ref)) spreadByOther.add(ref);
1235
- const roots = candidates.filter((c) => !spreadByOther.has(c.name));
1236
- const picked = roots.length === 1 ? roots[0] : void 0;
1237
- if (!picked) throw new Error(`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.`);
1238
- const transformed = transformedFragments.get(picked.name);
1239
- if (!transformed) continue;
1240
- entries.push({
1241
- fragmentName: picked.name,
1242
- binding: {
1243
- cardinality: builtInBinding.cardinality,
1244
- fieldName: builtInBinding.fieldName,
1245
- sourceKey: uncapitalize(picked.name)
1246
- },
1247
- fragmentExpression: fragmentBundleExpression(transformed, transformedFragments),
1248
- mutations: mutationBindings.get(builtInBinding.cardinality)
1249
- });
1250
- }
1251
- return entries;
1252
- }
1253
- async function main() {
1254
- const cwd = process.cwd();
1255
- const config = await loadConfig(cwd);
1256
- console.log("");
1257
- console.log(`${bold("@contello/client")} ${dim("generate")}`);
1258
- console.log("");
1259
- for (const project of config.projects) {
1260
- const start = performance.now();
1261
- console.log(`${cyan("●")} ${bold(project.project)}`);
1262
- rmSync(resolve(cwd, project.output), { force: true });
1263
- const schema = await introspectSchema(project.url, project.project, project.token);
1264
- const patterns = Array.isArray(project.documents) ? project.documents : [project.documents];
1265
- const documentPaths = (await Promise.all(patterns.map((p) => Array.fromAsync(glob(p, { cwd }))))).flat().toSorted(compareCodeUnits);
1266
- if (documentPaths.length === 0) {
1267
- console.warn(` ${yellow("⚠")} no documents found matching "${project.documents}"`);
1268
- continue;
1269
- }
1270
- const documents = documentPaths.map((p) => parse(new Source(readFileSync(resolve(cwd, p), "utf8"), p)));
1271
- const fragments = collectFragments(documents);
1272
- const operations = collectOperations(documents);
1273
- validateDocuments(schema, fragments, operations);
1274
- const transformedFragments = new Map([...fragments].map(([name, frag]) => [name, transformFragment(schema, frag, fragments)]));
1275
- const transformedOperations = operations.map((op) => transformOperation(schema, op, transformedFragments));
1276
- for (const [name, frag] of transformedFragments) transformedFragments.set(name, transformScalarFragment(schema, frag));
1277
- for (let i = 0; i < transformedOperations.length; i++) transformedOperations[i] = transformScalarOperation(schema, transformedOperations[i]);
1278
- const entityBindings = indexEntitySources(schema);
1279
- const builtInBindings = indexBuiltInSources(schema);
1280
- const entityMutations = indexEntityMutations(schema, entityBindings);
1281
- const builtInMutations = indexBuiltInMutations(schema, builtInBindings);
1282
- const sourceEntries = [...collectEntitySourceEntries(fragments, entityBindings, transformedFragments, entityMutations), ...collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments, builtInMutations)];
1283
- const entityModels = extractEntityModels(schema);
1284
- const parts = [
1285
- "/* eslint-disable */",
1286
- "// @ts-nocheck",
1287
- "/* this file is generated by contello-client — do not edit */",
1288
- ""
1289
- ];
1290
- const typeMap = schema.getTypeMap();
1291
- const clientImports = ["SourceDef"];
1292
- for (const scalar of MANAGED_SCALARS) if (Object.hasOwn(typeMap, scalar)) clientImports.push(scalar);
1293
- parts.push(`import type { ${clientImports.toSorted(compareCodeUnits).join(", ")} } from '@contello/client';`, "", generateSchemaTypes(schema), generateFragmentTypes(schema, fragments), generateOperationTypes(schema, operations, fragments));
1294
- if (transformedFragments.size > 0) parts.push(generateFragmentSchemas(transformedFragments), "");
1295
- for (const [i, operation] of operations.entries()) {
1296
- const camelName = uncapitalize(operation.name.value);
1297
- const docExpr = operationDocumentExpression(transformedOperations[i], transformedFragments);
1298
- parts.push(`export const ${camelName}Document = ${docExpr};`);
1299
- }
1300
- if (operations.length > 0) parts.push("");
1301
- parts.push(generateOperationsType(operations), "");
1302
- const sourcesTypeSrc = generateSourcesType(sourceEntries);
1303
- if (sourcesTypeSrc) parts.push(sourcesTypeSrc, "");
1304
- parts.push(generateOperationsConst(operations), "");
1305
- const sourcesConstSrc = generateSourcesConst(sourceEntries);
1306
- if (sourcesConstSrc) parts.push(sourcesConstSrc, "");
1307
- if (entityModels.size > 0) {
1308
- const sorted = entityModels.entries().toArray().toSorted(([a], [b]) => a.localeCompare(b));
1309
- parts.push("const models = {");
1310
- for (const [model, typeName] of sorted) parts.push(` ${model}: '${typeName}',`);
1311
- parts.push("} as const;", "");
1312
- } else parts.push("const models = {} as const;", "");
1313
- const sourcesPart = sourcesConstSrc ? ", sources" : ", sources: {}";
1314
- parts.push(`export const schema = { operations${sourcesPart}, models };`, "export type Schema = typeof schema;");
1315
- let output = parts.join("\n");
1316
- if (project.namespace) {
1317
- const indented = output.split("\n").map((line) => line ? ` ${line}` : "").join("\n");
1318
- output = `export namespace ${project.namespace} {\n${indented}\n}\n`;
1319
- }
1320
- const outputPath = resolve(cwd, project.output);
1321
- mkdirSync(dirname(outputPath), { recursive: true });
1322
- writeFileSync(outputPath, output, "utf8");
1323
- const elapsed = Math.round(performance.now() - start);
1324
- console.log(` ${green("✓")} ${relative(cwd, outputPath)} ${dim(`${elapsed}ms`)}`);
1325
- console.log(` ${dim("operations")} ${operations.length} ${dim("fragments")} ${fragments.size}`);
1326
- console.log("");
1327
- }
1328
- }
1329
- try {
1330
- await main();
1331
- } catch (error) {
1332
- console.error(error);
1333
- process.exit(1);
1334
- }
1335
- //#endregion
1336
- export {};
1337
-
1338
- //# sourceMappingURL=generate-CqlYWWhF.js.map