@constructive-io/graphql-codegen 2.26.0 → 2.27.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.
@@ -0,0 +1,68 @@
1
+ /**
2
+ * ORM Client - Type stub for compile-time type checking
3
+ *
4
+ * This is a stub file that provides type definitions for query-builder.ts
5
+ * during compilation. The actual client.ts is generated at codegen time
6
+ * from the generateOrmClientFile() function in client-generator.ts.
7
+ *
8
+ * @internal This file is NOT part of the generated output
9
+ */
10
+ export class GraphQLRequestError extends Error {
11
+ errors;
12
+ data;
13
+ constructor(errors, data = null) {
14
+ const messages = errors.map((e) => e.message).join('; ');
15
+ super(`GraphQL Error: ${messages}`);
16
+ this.errors = errors;
17
+ this.data = data;
18
+ this.name = 'GraphQLRequestError';
19
+ }
20
+ }
21
+ export class OrmClient {
22
+ endpoint;
23
+ headers;
24
+ constructor(config) {
25
+ this.endpoint = config.endpoint;
26
+ this.headers = config.headers ?? {};
27
+ }
28
+ async execute(document, variables) {
29
+ const response = await fetch(this.endpoint, {
30
+ method: 'POST',
31
+ headers: {
32
+ 'Content-Type': 'application/json',
33
+ Accept: 'application/json',
34
+ ...this.headers,
35
+ },
36
+ body: JSON.stringify({
37
+ query: document,
38
+ variables: variables ?? {},
39
+ }),
40
+ });
41
+ if (!response.ok) {
42
+ return {
43
+ ok: false,
44
+ data: null,
45
+ errors: [{ message: `HTTP ${response.status}: ${response.statusText}` }],
46
+ };
47
+ }
48
+ const json = (await response.json());
49
+ if (json.errors && json.errors.length > 0) {
50
+ return {
51
+ ok: false,
52
+ data: null,
53
+ errors: json.errors,
54
+ };
55
+ }
56
+ return {
57
+ ok: true,
58
+ data: json.data,
59
+ errors: undefined,
60
+ };
61
+ }
62
+ setHeaders(headers) {
63
+ this.headers = { ...this.headers, ...headers };
64
+ }
65
+ getEndpoint() {
66
+ return this.endpoint;
67
+ }
68
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Query Builder - Builds and executes GraphQL operations
3
+ *
4
+ * This is the RUNTIME code that gets copied to generated output.
5
+ * It uses gql-ast to build GraphQL documents programmatically.
6
+ *
7
+ * NOTE: This file is read at codegen time and written to output.
8
+ * Any changes here will affect all generated ORM clients.
9
+ */
10
+ import type { FieldNode } from 'graphql';
11
+ import { OrmClient, QueryResult } from './client';
12
+ export interface QueryBuilderConfig {
13
+ client: OrmClient;
14
+ operation: 'query' | 'mutation';
15
+ operationName: string;
16
+ fieldName: string;
17
+ document: string;
18
+ variables?: Record<string, unknown>;
19
+ }
20
+ export declare class QueryBuilder<TResult> {
21
+ private config;
22
+ constructor(config: QueryBuilderConfig);
23
+ /**
24
+ * Execute the query and return a discriminated union result
25
+ * Use result.ok to check success, or .unwrap() to throw on error
26
+ */
27
+ execute(): Promise<QueryResult<TResult>>;
28
+ /**
29
+ * Execute and unwrap the result, throwing GraphQLRequestError on failure
30
+ * @throws {GraphQLRequestError} If the query returns errors
31
+ */
32
+ unwrap(): Promise<TResult>;
33
+ /**
34
+ * Execute and unwrap, returning defaultValue on error instead of throwing
35
+ */
36
+ unwrapOr<D>(defaultValue: D): Promise<TResult | D>;
37
+ /**
38
+ * Execute and unwrap, calling onError callback on failure
39
+ */
40
+ unwrapOrElse<D>(onError: (errors: import('./client').GraphQLError[]) => D): Promise<TResult | D>;
41
+ toGraphQL(): string;
42
+ getVariables(): Record<string, unknown> | undefined;
43
+ }
44
+ export declare function buildSelections(select: Record<string, unknown> | undefined): FieldNode[];
45
+ export declare function buildFindManyDocument<TSelect, TWhere>(operationName: string, queryField: string, select: TSelect, args: {
46
+ where?: TWhere;
47
+ orderBy?: string[];
48
+ first?: number;
49
+ last?: number;
50
+ after?: string;
51
+ before?: string;
52
+ offset?: number;
53
+ }, filterTypeName: string, orderByTypeName: string): {
54
+ document: string;
55
+ variables: Record<string, unknown>;
56
+ };
57
+ export declare function buildFindFirstDocument<TSelect, TWhere>(operationName: string, queryField: string, select: TSelect, args: {
58
+ where?: TWhere;
59
+ }, filterTypeName: string): {
60
+ document: string;
61
+ variables: Record<string, unknown>;
62
+ };
63
+ export declare function buildCreateDocument<TSelect, TData>(operationName: string, mutationField: string, entityField: string, select: TSelect, data: TData, inputTypeName: string): {
64
+ document: string;
65
+ variables: Record<string, unknown>;
66
+ };
67
+ export declare function buildUpdateDocument<TSelect, TWhere extends {
68
+ id: string;
69
+ }, TData>(operationName: string, mutationField: string, entityField: string, select: TSelect, where: TWhere, data: TData, inputTypeName: string): {
70
+ document: string;
71
+ variables: Record<string, unknown>;
72
+ };
73
+ export declare function buildDeleteDocument<TWhere extends {
74
+ id: string;
75
+ }>(operationName: string, mutationField: string, entityField: string, where: TWhere, inputTypeName: string): {
76
+ document: string;
77
+ variables: Record<string, unknown>;
78
+ };
79
+ export declare function buildCustomDocument<TSelect, TArgs>(operationType: 'query' | 'mutation', operationName: string, fieldName: string, select: TSelect, args: TArgs, variableDefinitions: Array<{
80
+ name: string;
81
+ type: string;
82
+ }>): {
83
+ document: string;
84
+ variables: Record<string, unknown>;
85
+ };
@@ -0,0 +1,441 @@
1
+ /**
2
+ * Query Builder - Builds and executes GraphQL operations
3
+ *
4
+ * This is the RUNTIME code that gets copied to generated output.
5
+ * It uses gql-ast to build GraphQL documents programmatically.
6
+ *
7
+ * NOTE: This file is read at codegen time and written to output.
8
+ * Any changes here will affect all generated ORM clients.
9
+ */
10
+ import * as t from 'gql-ast';
11
+ import { parseType, print } from 'graphql';
12
+ import { GraphQLRequestError } from './client';
13
+ export class QueryBuilder {
14
+ config;
15
+ constructor(config) {
16
+ this.config = config;
17
+ }
18
+ /**
19
+ * Execute the query and return a discriminated union result
20
+ * Use result.ok to check success, or .unwrap() to throw on error
21
+ */
22
+ async execute() {
23
+ return this.config.client.execute(this.config.document, this.config.variables);
24
+ }
25
+ /**
26
+ * Execute and unwrap the result, throwing GraphQLRequestError on failure
27
+ * @throws {GraphQLRequestError} If the query returns errors
28
+ */
29
+ async unwrap() {
30
+ const result = await this.execute();
31
+ if (!result.ok) {
32
+ throw new GraphQLRequestError(result.errors, result.data);
33
+ }
34
+ return result.data;
35
+ }
36
+ /**
37
+ * Execute and unwrap, returning defaultValue on error instead of throwing
38
+ */
39
+ async unwrapOr(defaultValue) {
40
+ const result = await this.execute();
41
+ if (!result.ok) {
42
+ return defaultValue;
43
+ }
44
+ return result.data;
45
+ }
46
+ /**
47
+ * Execute and unwrap, calling onError callback on failure
48
+ */
49
+ async unwrapOrElse(onError) {
50
+ const result = await this.execute();
51
+ if (!result.ok) {
52
+ return onError(result.errors);
53
+ }
54
+ return result.data;
55
+ }
56
+ toGraphQL() {
57
+ return this.config.document;
58
+ }
59
+ getVariables() {
60
+ return this.config.variables;
61
+ }
62
+ }
63
+ // ============================================================================
64
+ // Selection Builders
65
+ // ============================================================================
66
+ export function buildSelections(select) {
67
+ if (!select) {
68
+ return [];
69
+ }
70
+ const fields = [];
71
+ for (const [key, value] of Object.entries(select)) {
72
+ if (value === false || value === undefined) {
73
+ continue;
74
+ }
75
+ if (value === true) {
76
+ fields.push(t.field({ name: key }));
77
+ continue;
78
+ }
79
+ if (typeof value === 'object' && value !== null) {
80
+ const nested = value;
81
+ if (nested.select) {
82
+ const nestedSelections = buildSelections(nested.select);
83
+ const isConnection = nested.connection === true ||
84
+ nested.first !== undefined ||
85
+ nested.filter !== undefined;
86
+ const args = buildArgs([
87
+ buildOptionalArg('first', nested.first),
88
+ nested.filter
89
+ ? t.argument({ name: 'filter', value: buildValueAst(nested.filter) })
90
+ : null,
91
+ buildEnumListArg('orderBy', nested.orderBy),
92
+ ]);
93
+ if (isConnection) {
94
+ fields.push(t.field({
95
+ name: key,
96
+ args,
97
+ selectionSet: t.selectionSet({
98
+ selections: buildConnectionSelections(nestedSelections),
99
+ }),
100
+ }));
101
+ }
102
+ else {
103
+ fields.push(t.field({
104
+ name: key,
105
+ args,
106
+ selectionSet: t.selectionSet({ selections: nestedSelections }),
107
+ }));
108
+ }
109
+ }
110
+ }
111
+ }
112
+ return fields;
113
+ }
114
+ // ============================================================================
115
+ // Document Builders
116
+ // ============================================================================
117
+ export function buildFindManyDocument(operationName, queryField, select, args, filterTypeName, orderByTypeName) {
118
+ const selections = select
119
+ ? buildSelections(select)
120
+ : [t.field({ name: 'id' })];
121
+ const variableDefinitions = [];
122
+ const queryArgs = [];
123
+ const variables = {};
124
+ addVariable({ varName: 'where', argName: 'filter', typeName: filterTypeName, value: args.where }, variableDefinitions, queryArgs, variables);
125
+ addVariable({
126
+ varName: 'orderBy',
127
+ typeName: '[' + orderByTypeName + '!]',
128
+ value: args.orderBy?.length ? args.orderBy : undefined,
129
+ }, variableDefinitions, queryArgs, variables);
130
+ addVariable({ varName: 'first', typeName: 'Int', value: args.first }, variableDefinitions, queryArgs, variables);
131
+ addVariable({ varName: 'last', typeName: 'Int', value: args.last }, variableDefinitions, queryArgs, variables);
132
+ addVariable({ varName: 'after', typeName: 'Cursor', value: args.after }, variableDefinitions, queryArgs, variables);
133
+ addVariable({ varName: 'before', typeName: 'Cursor', value: args.before }, variableDefinitions, queryArgs, variables);
134
+ addVariable({ varName: 'offset', typeName: 'Int', value: args.offset }, variableDefinitions, queryArgs, variables);
135
+ const document = t.document({
136
+ definitions: [
137
+ t.operationDefinition({
138
+ operation: 'query',
139
+ name: operationName + 'Query',
140
+ variableDefinitions: variableDefinitions.length ? variableDefinitions : undefined,
141
+ selectionSet: t.selectionSet({
142
+ selections: [
143
+ t.field({
144
+ name: queryField,
145
+ args: queryArgs.length ? queryArgs : undefined,
146
+ selectionSet: t.selectionSet({
147
+ selections: buildConnectionSelections(selections),
148
+ }),
149
+ }),
150
+ ],
151
+ }),
152
+ }),
153
+ ],
154
+ });
155
+ return { document: print(document), variables };
156
+ }
157
+ export function buildFindFirstDocument(operationName, queryField, select, args, filterTypeName) {
158
+ const selections = select
159
+ ? buildSelections(select)
160
+ : [t.field({ name: 'id' })];
161
+ const variableDefinitions = [];
162
+ const queryArgs = [];
163
+ const variables = {};
164
+ // Always add first: 1 for findFirst
165
+ addVariable({ varName: 'first', typeName: 'Int', value: 1 }, variableDefinitions, queryArgs, variables);
166
+ addVariable({ varName: 'where', argName: 'filter', typeName: filterTypeName, value: args.where }, variableDefinitions, queryArgs, variables);
167
+ const document = t.document({
168
+ definitions: [
169
+ t.operationDefinition({
170
+ operation: 'query',
171
+ name: operationName + 'Query',
172
+ variableDefinitions,
173
+ selectionSet: t.selectionSet({
174
+ selections: [
175
+ t.field({
176
+ name: queryField,
177
+ args: queryArgs,
178
+ selectionSet: t.selectionSet({
179
+ selections: [
180
+ t.field({
181
+ name: 'nodes',
182
+ selectionSet: t.selectionSet({ selections }),
183
+ }),
184
+ ],
185
+ }),
186
+ }),
187
+ ],
188
+ }),
189
+ }),
190
+ ],
191
+ });
192
+ return { document: print(document), variables };
193
+ }
194
+ export function buildCreateDocument(operationName, mutationField, entityField, select, data, inputTypeName) {
195
+ const selections = select
196
+ ? buildSelections(select)
197
+ : [t.field({ name: 'id' })];
198
+ return {
199
+ document: buildInputMutationDocument({
200
+ operationName,
201
+ mutationField,
202
+ inputTypeName,
203
+ resultSelections: [
204
+ t.field({
205
+ name: entityField,
206
+ selectionSet: t.selectionSet({ selections }),
207
+ }),
208
+ ],
209
+ }),
210
+ variables: {
211
+ input: {
212
+ [entityField]: data,
213
+ },
214
+ },
215
+ };
216
+ }
217
+ export function buildUpdateDocument(operationName, mutationField, entityField, select, where, data, inputTypeName) {
218
+ const selections = select
219
+ ? buildSelections(select)
220
+ : [t.field({ name: 'id' })];
221
+ return {
222
+ document: buildInputMutationDocument({
223
+ operationName,
224
+ mutationField,
225
+ inputTypeName,
226
+ resultSelections: [
227
+ t.field({
228
+ name: entityField,
229
+ selectionSet: t.selectionSet({ selections }),
230
+ }),
231
+ ],
232
+ }),
233
+ variables: {
234
+ input: {
235
+ id: where.id,
236
+ patch: data,
237
+ },
238
+ },
239
+ };
240
+ }
241
+ export function buildDeleteDocument(operationName, mutationField, entityField, where, inputTypeName) {
242
+ return {
243
+ document: buildInputMutationDocument({
244
+ operationName,
245
+ mutationField,
246
+ inputTypeName,
247
+ resultSelections: [
248
+ t.field({
249
+ name: entityField,
250
+ selectionSet: t.selectionSet({
251
+ selections: [t.field({ name: 'id' })],
252
+ }),
253
+ }),
254
+ ],
255
+ }),
256
+ variables: {
257
+ input: {
258
+ id: where.id,
259
+ },
260
+ },
261
+ };
262
+ }
263
+ export function buildCustomDocument(operationType, operationName, fieldName, select, args, variableDefinitions) {
264
+ let actualSelect = select;
265
+ let isConnection = false;
266
+ if (select && typeof select === 'object' && 'select' in select) {
267
+ const wrapper = select;
268
+ if (wrapper.select) {
269
+ actualSelect = wrapper.select;
270
+ isConnection = wrapper.connection === true;
271
+ }
272
+ }
273
+ const selections = actualSelect
274
+ ? buildSelections(actualSelect)
275
+ : [];
276
+ const variableDefs = variableDefinitions.map((definition) => t.variableDefinition({
277
+ variable: t.variable({ name: definition.name }),
278
+ type: parseType(definition.type),
279
+ }));
280
+ const fieldArgs = variableDefinitions.map((definition) => t.argument({
281
+ name: definition.name,
282
+ value: t.variable({ name: definition.name }),
283
+ }));
284
+ const fieldSelections = isConnection
285
+ ? buildConnectionSelections(selections)
286
+ : selections;
287
+ const document = t.document({
288
+ definitions: [
289
+ t.operationDefinition({
290
+ operation: operationType,
291
+ name: operationName,
292
+ variableDefinitions: variableDefs.length ? variableDefs : undefined,
293
+ selectionSet: t.selectionSet({
294
+ selections: [
295
+ t.field({
296
+ name: fieldName,
297
+ args: fieldArgs.length ? fieldArgs : undefined,
298
+ selectionSet: fieldSelections.length
299
+ ? t.selectionSet({ selections: fieldSelections })
300
+ : undefined,
301
+ }),
302
+ ],
303
+ }),
304
+ }),
305
+ ],
306
+ });
307
+ return {
308
+ document: print(document),
309
+ variables: (args ?? {}),
310
+ };
311
+ }
312
+ // ============================================================================
313
+ // Helper Functions
314
+ // ============================================================================
315
+ function buildArgs(args) {
316
+ return args.filter((arg) => arg !== null);
317
+ }
318
+ function buildOptionalArg(name, value) {
319
+ if (value === undefined) {
320
+ return null;
321
+ }
322
+ const valueNode = typeof value === 'number'
323
+ ? t.intValue({ value: value.toString() })
324
+ : t.stringValue({ value });
325
+ return t.argument({ name, value: valueNode });
326
+ }
327
+ function buildEnumListArg(name, values) {
328
+ if (!values || values.length === 0) {
329
+ return null;
330
+ }
331
+ return t.argument({
332
+ name,
333
+ value: t.listValue({
334
+ values: values.map((value) => buildEnumValue(value)),
335
+ }),
336
+ });
337
+ }
338
+ function buildEnumValue(value) {
339
+ return {
340
+ kind: 'EnumValue',
341
+ value,
342
+ };
343
+ }
344
+ function buildPageInfoSelections() {
345
+ return [
346
+ t.field({ name: 'hasNextPage' }),
347
+ t.field({ name: 'hasPreviousPage' }),
348
+ t.field({ name: 'startCursor' }),
349
+ t.field({ name: 'endCursor' }),
350
+ ];
351
+ }
352
+ function buildConnectionSelections(nodeSelections) {
353
+ return [
354
+ t.field({
355
+ name: 'nodes',
356
+ selectionSet: t.selectionSet({ selections: nodeSelections }),
357
+ }),
358
+ t.field({ name: 'totalCount' }),
359
+ t.field({
360
+ name: 'pageInfo',
361
+ selectionSet: t.selectionSet({ selections: buildPageInfoSelections() }),
362
+ }),
363
+ ];
364
+ }
365
+ function buildInputMutationDocument(config) {
366
+ const document = t.document({
367
+ definitions: [
368
+ t.operationDefinition({
369
+ operation: 'mutation',
370
+ name: config.operationName + 'Mutation',
371
+ variableDefinitions: [
372
+ t.variableDefinition({
373
+ variable: t.variable({ name: 'input' }),
374
+ type: parseType(config.inputTypeName + '!'),
375
+ }),
376
+ ],
377
+ selectionSet: t.selectionSet({
378
+ selections: [
379
+ t.field({
380
+ name: config.mutationField,
381
+ args: [
382
+ t.argument({
383
+ name: 'input',
384
+ value: t.variable({ name: 'input' }),
385
+ }),
386
+ ],
387
+ selectionSet: t.selectionSet({
388
+ selections: config.resultSelections,
389
+ }),
390
+ }),
391
+ ],
392
+ }),
393
+ }),
394
+ ],
395
+ });
396
+ return print(document);
397
+ }
398
+ function addVariable(spec, definitions, args, variables) {
399
+ if (spec.value === undefined)
400
+ return;
401
+ definitions.push(t.variableDefinition({
402
+ variable: t.variable({ name: spec.varName }),
403
+ type: parseType(spec.typeName),
404
+ }));
405
+ args.push(t.argument({
406
+ name: spec.argName ?? spec.varName,
407
+ value: t.variable({ name: spec.varName }),
408
+ }));
409
+ variables[spec.varName] = spec.value;
410
+ }
411
+ function buildValueAst(value) {
412
+ if (value === null) {
413
+ return t.nullValue();
414
+ }
415
+ if (typeof value === 'boolean') {
416
+ return t.booleanValue({ value });
417
+ }
418
+ if (typeof value === 'number') {
419
+ return Number.isInteger(value)
420
+ ? t.intValue({ value: value.toString() })
421
+ : t.floatValue({ value: value.toString() });
422
+ }
423
+ if (typeof value === 'string') {
424
+ return t.stringValue({ value });
425
+ }
426
+ if (Array.isArray(value)) {
427
+ return t.listValue({
428
+ values: value.map((item) => buildValueAst(item)),
429
+ });
430
+ }
431
+ if (typeof value === 'object' && value !== null) {
432
+ const obj = value;
433
+ return t.objectValue({
434
+ fields: Object.entries(obj).map(([key, val]) => t.objectField({
435
+ name: key,
436
+ value: buildValueAst(val),
437
+ })),
438
+ });
439
+ }
440
+ throw new Error('Unsupported value type: ' + typeof value);
441
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constructive-io/graphql-codegen",
3
- "version": "2.26.0",
3
+ "version": "2.27.1",
4
4
  "description": "CLI-based GraphQL SDK generator for PostGraphile endpoints with React Query hooks",
5
5
  "keywords": [
6
6
  "graphql",
@@ -47,16 +47,16 @@
47
47
  "example:codegen:orm": "tsx src/cli/index.ts generate-orm --config examples/multi-target.config.ts",
48
48
  "example:codegen:sdk:schema": "node dist/cli/index.js generate --schema examples/example.schema.graphql --output examples/output/generated-sdk-schema",
49
49
  "example:codegen:orm:schema": "node dist/cli/index.js generate-orm --schema examples/example.schema.graphql --output examples/output/generated-orm-schema",
50
- "example:sdk": "tsx examples/react-query-sdk.ts",
51
- "example:orm": "tsx examples/orm-sdk.ts",
52
- "example:sdk:typecheck": "tsc --noEmit --jsx react --esModuleInterop --skipLibCheck --moduleResolution node examples/react-hooks-test.tsx"
50
+ "example:sdk": "tsx examples/react-hooks-sdk-test.tsx",
51
+ "example:orm": "tsx examples/orm-sdk-test.ts",
52
+ "example:sdk:typecheck": "tsc --noEmit --jsx react --esModuleInterop --skipLibCheck --moduleResolution node examples/react-hooks-sdk-test.tsx"
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/generator": "^7.28.5",
56
56
  "@babel/types": "^7.28.5",
57
57
  "ajv": "^8.17.1",
58
58
  "commander": "^12.1.0",
59
- "gql-ast": "^2.5.0",
59
+ "gql-ast": "^2.6.0",
60
60
  "graphql": "15.10.1",
61
61
  "inflekt": "^0.2.0",
62
62
  "jiti": "^2.6.1",
@@ -86,5 +86,5 @@
86
86
  "tsx": "^4.21.0",
87
87
  "typescript": "^5.9.3"
88
88
  },
89
- "gitHead": "b7abf2fdaf0a827d79a80c9c0a29e5c960f227df"
89
+ "gitHead": "1da9596c2e7b9445466626b7b809339361aa0b65"
90
90
  }