@graphql-codegen/python-operations 0.0.0-stage → 0.0.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.
package/README.md CHANGED
@@ -1,3 +1,106 @@
1
- # Temporary Holding Version
1
+ # @graphql-codegen/python-operations
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A **document-driven** [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) plugin that
4
+ emits **Python operation types**: for each operation in your documents it generates per-operation
5
+ result [pydantic](https://docs.pydantic.dev) `BaseModel` classes (named, nested classes for every
6
+ object selection) plus a `<Operation>Variables` `TypedDict` keyed by the wire (GraphQL) variable
7
+ names. Renamed response keys are pinned with `Field(alias=...)` and a
8
+ `model_config = ConfigDict(populate_by_name=True)`.
9
+
10
+ It is the operations counterpart to `@graphql-codegen/python` (which emits base schema types),
11
+ analogous to how `typescript-operations` complements `typescript`.
12
+
13
+ ## Example
14
+
15
+ Schema:
16
+
17
+ ```graphql
18
+ enum Role {
19
+ ADMIN
20
+ USER
21
+ }
22
+ type User {
23
+ id: ID!
24
+ name: String!
25
+ role: Role!
26
+ friends: [User!]!
27
+ }
28
+ type Query {
29
+ users(role: Role): [User!]!
30
+ }
31
+ ```
32
+
33
+ Operation:
34
+
35
+ ```graphql
36
+ query GetUsers($role: Role) {
37
+ users(role: $role) {
38
+ id
39
+ name
40
+ role
41
+ friends {
42
+ id
43
+ name
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ Output:
50
+
51
+ ```python
52
+ from typing import Optional, TypedDict
53
+ from pydantic import BaseModel
54
+
55
+
56
+ class GetUsersQueryUsersFriends(BaseModel):
57
+ id: 'str'
58
+ name: 'str'
59
+
60
+
61
+ class GetUsersQueryUsers(BaseModel):
62
+ id: 'str'
63
+ name: 'str'
64
+ role: 'Role'
65
+ friends: 'list[GetUsersQueryUsersFriends]'
66
+
67
+
68
+ class GetUsersQuery(BaseModel):
69
+ users: 'list[GetUsersQueryUsers]'
70
+
71
+
72
+ class GetUsersQueryVariables(TypedDict):
73
+ role: 'Optional[Role]'
74
+ ```
75
+
76
+ Result types are pydantic `BaseModel` subclasses; the `<Operation>Variables` type stays a
77
+ `TypedDict`. When a response key is renamed (snake_case or a reserved keyword), that attribute is
78
+ pinned with `Field(alias='<wireName>')` and the class gets
79
+ `model_config = ConfigDict(populate_by_name=True)`.
80
+
81
+ ## Config
82
+
83
+ | Option | Type | Default | Description |
84
+ | ------------------ | ----------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
85
+ | `namingConvention` | `'keep' \| 'snakeCase'` | `'snakeCase'` | How response keys become result-class attributes. `snakeCase` converts camelCase→snake*case, suffixes reserved keywords with `*`, and pins renamed keys via `Field(alias=...)`. `keep` uses keys verbatim. Variables always keep the wire name. |
86
+ | `baseModel` | `string` | `'BaseModel'` | Base class the generated result types extend. |
87
+ | `runtimeImport` | `string` | `'pydantic'` | Module the base model is imported from (`from {runtimeImport} import {baseModel}`, with `ConfigDict`/`Field` appended when aliases are used). |
88
+ | `typesImport` | `string` | – | If set, prepend `from {typesImport} import *` so base type names (enums, inputs) resolve at runtime. |
89
+
90
+ ## Behaviour / naming
91
+
92
+ - Result root type: `<OperationName><OperationType>` (e.g. `GetUsersQuery`).
93
+ - Nested object selections: `<ParentTypeName><PascalCase(responseFieldName)>`.
94
+ - Variables type: `<OperationName><OperationType>Variables`.
95
+ - Field names are `snake_case`; Python reserved keywords get a trailing `_`.
96
+ - Aliases use the alias as the response key; `__typename` becomes `__typename__`.
97
+ - Every annotation is quoted (forward reference), so emit order does not matter.
98
+
99
+ ## Not (yet) supported
100
+
101
+ Fragment spreads, inline fragments and union member (`... on Type`) selections are not yet
102
+ implemented. Rather than silently omitting their fields (which would produce a result type that
103
+ looks valid but is missing data), the plugin **throws a clear error** at generate time if an
104
+ operation contains one — inline the fields directly into the operation for now. See
105
+ `src/python-helpers.ts` for the duplicated naming helpers (TODO: extract to a shared
106
+ `@graphql-codegen/python-common` package).
package/dist/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # @graphql-codegen/python-operations
2
+
3
+ A **document-driven** [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) plugin that
4
+ emits **Python operation types**: for each operation in your documents it generates per-operation
5
+ result [pydantic](https://docs.pydantic.dev) `BaseModel` classes (named, nested classes for every
6
+ object selection) plus a `<Operation>Variables` `TypedDict` keyed by the wire (GraphQL) variable
7
+ names. Renamed response keys are pinned with `Field(alias=...)` and a
8
+ `model_config = ConfigDict(populate_by_name=True)`.
9
+
10
+ It is the operations counterpart to `@graphql-codegen/python` (which emits base schema types),
11
+ analogous to how `typescript-operations` complements `typescript`.
12
+
13
+ ## Example
14
+
15
+ Schema:
16
+
17
+ ```graphql
18
+ enum Role {
19
+ ADMIN
20
+ USER
21
+ }
22
+ type User {
23
+ id: ID!
24
+ name: String!
25
+ role: Role!
26
+ friends: [User!]!
27
+ }
28
+ type Query {
29
+ users(role: Role): [User!]!
30
+ }
31
+ ```
32
+
33
+ Operation:
34
+
35
+ ```graphql
36
+ query GetUsers($role: Role) {
37
+ users(role: $role) {
38
+ id
39
+ name
40
+ role
41
+ friends {
42
+ id
43
+ name
44
+ }
45
+ }
46
+ }
47
+ ```
48
+
49
+ Output:
50
+
51
+ ```python
52
+ from typing import Optional, TypedDict
53
+ from pydantic import BaseModel
54
+
55
+
56
+ class GetUsersQueryUsersFriends(BaseModel):
57
+ id: 'str'
58
+ name: 'str'
59
+
60
+
61
+ class GetUsersQueryUsers(BaseModel):
62
+ id: 'str'
63
+ name: 'str'
64
+ role: 'Role'
65
+ friends: 'list[GetUsersQueryUsersFriends]'
66
+
67
+
68
+ class GetUsersQuery(BaseModel):
69
+ users: 'list[GetUsersQueryUsers]'
70
+
71
+
72
+ class GetUsersQueryVariables(TypedDict):
73
+ role: 'Optional[Role]'
74
+ ```
75
+
76
+ Result types are pydantic `BaseModel` subclasses; the `<Operation>Variables` type stays a
77
+ `TypedDict`. When a response key is renamed (snake_case or a reserved keyword), that attribute is
78
+ pinned with `Field(alias='<wireName>')` and the class gets
79
+ `model_config = ConfigDict(populate_by_name=True)`.
80
+
81
+ ## Config
82
+
83
+ | Option | Type | Default | Description |
84
+ | ------------------ | ----------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
85
+ | `namingConvention` | `'keep' \| 'snakeCase'` | `'snakeCase'` | How response keys become result-class attributes. `snakeCase` converts camelCase→snake*case, suffixes reserved keywords with `*`, and pins renamed keys via `Field(alias=...)`. `keep` uses keys verbatim. Variables always keep the wire name. |
86
+ | `baseModel` | `string` | `'BaseModel'` | Base class the generated result types extend. |
87
+ | `runtimeImport` | `string` | `'pydantic'` | Module the base model is imported from (`from {runtimeImport} import {baseModel}`, with `ConfigDict`/`Field` appended when aliases are used). |
88
+ | `typesImport` | `string` | – | If set, prepend `from {typesImport} import *` so base type names (enums, inputs) resolve at runtime. |
89
+
90
+ ## Behaviour / naming
91
+
92
+ - Result root type: `<OperationName><OperationType>` (e.g. `GetUsersQuery`).
93
+ - Nested object selections: `<ParentTypeName><PascalCase(responseFieldName)>`.
94
+ - Variables type: `<OperationName><OperationType>Variables`.
95
+ - Field names are `snake_case`; Python reserved keywords get a trailing `_`.
96
+ - Aliases use the alias as the response key; `__typename` becomes `__typename__`.
97
+ - Every annotation is quoted (forward reference), so emit order does not matter.
98
+
99
+ ## Not (yet) supported
100
+
101
+ Fragment spreads, inline fragments and union member (`... on Type`) selections are not yet
102
+ implemented. Rather than silently omitting their fields (which would produce a result type that
103
+ looks valid but is missing data), the plugin **throws a clear error** at generate time if an
104
+ operation contains one — inline the fields directly into the operation for now. See
105
+ `src/python-helpers.ts` for the duplicated naming helpers (TODO: extract to a shared
106
+ `@graphql-codegen/python-common` package).
File without changes
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.plugin = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const graphql_1 = require("graphql");
6
+ const visitor_js_1 = require("./visitor.js");
7
+ tslib_1.__exportStar(require("./config.js"), exports);
8
+ tslib_1.__exportStar(require("./visitor.js"), exports);
9
+ tslib_1.__exportStar(require("./python-helpers.js"), exports);
10
+ /**
11
+ * Document-driven plugin: for each GraphQL operation in the provided documents,
12
+ * emit a per-operation result `TypedDict` (with named nested `TypedDict`s for
13
+ * every object selection) plus a `<Operation>Variables` `TypedDict`.
14
+ */
15
+ const plugin = (schema, documents, config) => {
16
+ const allAst = (0, graphql_1.concatAST)(documents.map(d => d.document).filter(Boolean));
17
+ const operations = allAst.definitions.filter((def) => def.kind === graphql_1.Kind.OPERATION_DEFINITION);
18
+ const visitor = new visitor_js_1.PythonOperationsVisitor(schema, config);
19
+ const definitions = operations.map(op => visitor.generateOperation(op));
20
+ return {
21
+ prepend: visitor.getImports(),
22
+ content: definitions.join('\n\n\n'),
23
+ };
24
+ };
25
+ exports.plugin = plugin;
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pyFieldName = exports.PYTHON_SCALARS = exports.isValidClassAttr = exports.isReservedField = void 0;
4
+ exports.resultFieldKey = resultFieldKey;
5
+ exports.fieldKey = fieldKey;
6
+ const python_common_1 = require("@graphql-codegen/python-common");
7
+ Object.defineProperty(exports, "isReservedField", { enumerable: true, get: function () { return python_common_1.isReservedField; } });
8
+ Object.defineProperty(exports, "isValidClassAttr", { enumerable: true, get: function () { return python_common_1.isValidClassAttr; } });
9
+ Object.defineProperty(exports, "pyFieldName", { enumerable: true, get: function () { return python_common_1.pythonFieldName; } });
10
+ Object.defineProperty(exports, "PYTHON_SCALARS", { enumerable: true, get: function () { return python_common_1.PYTHON_SCALARS; } });
11
+ /**
12
+ * Compute the attribute name for a `BaseModel` result class. Under `'snakeCase'`
13
+ * the key is snake-cased (keywords suffixed with `_`); under `'keep'` the wire
14
+ * name is used verbatim, but — because `BaseModel` classes cannot use functional
15
+ * `TypedDict` syntax — a keyword / non-identifier name still falls back to a
16
+ * trailing `_`.
17
+ */
18
+ function resultFieldKey(name, convention) {
19
+ if (convention === 'snakeCase') {
20
+ return (0, python_common_1.pythonFieldName)(name);
21
+ }
22
+ return (0, python_common_1.isValidClassAttr)(name) ? name : `${name}_`;
23
+ }
24
+ /**
25
+ * Compute the `TypedDict` key for a GraphQL response / variable name under the
26
+ * given naming convention. Under `'keep'` the raw name is returned verbatim
27
+ * (functional `TypedDict` syntax handles invalid keys); under `'snakeCase'` the
28
+ * legacy snake_case + `_`-suffix behavior is applied.
29
+ */
30
+ function fieldKey(name, convention) {
31
+ return convention === 'snakeCase' ? (0, python_common_1.pythonFieldName)(name) : name;
32
+ }
@@ -0,0 +1,306 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PythonOperationsVisitor = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const visitor_plugin_common_1 = require("@graphql-codegen/visitor-plugin-common");
6
+ const python_helpers_js_1 = require("./python-helpers.js");
7
+ const INDENT = ' ';
8
+ /**
9
+ * Walks GraphQL `OperationDefinition` nodes against the schema and recursively
10
+ * emits named, nested Python `TypedDict` classes for every object selection set,
11
+ * plus a `<Operation>Variables` `TypedDict` for the operation variables.
12
+ *
13
+ * Unlike the C-family `SelectionSetToObject`/`DeclarationBlock` approach (which
14
+ * emits inline anonymous objects), this mirrors the C#/Java strategy: every
15
+ * nested selection becomes its own named type referenced by its parent.
16
+ */
17
+ class PythonOperationsVisitor extends visitor_plugin_common_1.BaseVisitor {
18
+ constructor(schema, rawConfig) {
19
+ // Our `namingConvention` (`'keep'` | `'snakeCase'`) governs field-KEY naming
20
+ // only. It must NOT leak into the base visitor's `namingConvention`, which
21
+ // drives TYPE-name conversion (`convertName` / `pascal`) — those names must
22
+ // stay PascalCase (e.g. `GetUsersQueryUsers`).
23
+ super({ ...rawConfig, namingConvention: undefined }, {});
24
+ this._usesOptional = false;
25
+ this._usesAny = false;
26
+ this._usesLiteral = false;
27
+ this._usesBaseModel = false;
28
+ this._usesConfigDict = false;
29
+ this._usesField = false;
30
+ this._anonymousCount = 0;
31
+ this._schema = schema;
32
+ this._typesImport = rawConfig.typesImport;
33
+ this._namingConvention = (0, visitor_plugin_common_1.getConfigValue)(rawConfig.namingConvention, 'snakeCase');
34
+ this._baseModel = (0, visitor_plugin_common_1.getConfigValue)(rawConfig.baseModel, 'BaseModel');
35
+ this._runtimeImport = (0, visitor_plugin_common_1.getConfigValue)(rawConfig.runtimeImport, 'pydantic');
36
+ }
37
+ /** PascalCase a name segment without applying any prefix/suffix. */
38
+ pascal(name) {
39
+ return this.convertName(name, {
40
+ useTypesPrefix: false,
41
+ useTypesSuffix: false,
42
+ });
43
+ }
44
+ get operationRootTypes() {
45
+ return {
46
+ query: this._schema.getQueryType(),
47
+ mutation: this._schema.getMutationType(),
48
+ subscription: this._schema.getSubscriptionType(),
49
+ };
50
+ }
51
+ // --- Python annotation builders ----------------------------------------
52
+ /**
53
+ * Build a Python annotation from a (resolved) GraphQL output type. The
54
+ * `objectBaseName` is the generated nested type name used when the base type
55
+ * is an object/interface/union selection.
56
+ */
57
+ pyTypeFromGraphQL(type, objectBaseName) {
58
+ if ((0, graphql_1.isNonNullType)(type)) {
59
+ return this.innerFromGraphQL(type.ofType, objectBaseName);
60
+ }
61
+ this._usesOptional = true;
62
+ return `Optional[${this.innerFromGraphQL(type, objectBaseName)}]`;
63
+ }
64
+ innerFromGraphQL(type, objectBaseName) {
65
+ if ((0, graphql_1.isListType)(type)) {
66
+ return `list[${this.pyTypeFromGraphQL(type.ofType, objectBaseName)}]`;
67
+ }
68
+ const named = (0, graphql_1.getNamedType)(type);
69
+ if ((0, graphql_1.isScalarType)(named)) {
70
+ const mapped = python_helpers_js_1.PYTHON_SCALARS[named.name];
71
+ if (mapped) {
72
+ return mapped.output;
73
+ }
74
+ this._usesAny = true;
75
+ return 'Any';
76
+ }
77
+ if ((0, graphql_1.isEnumType)(named)) {
78
+ return named.name;
79
+ }
80
+ // object / interface / union selection -> generated nested type name
81
+ return objectBaseName;
82
+ }
83
+ /**
84
+ * Build a Python annotation from a variable `TypeNode`. Named types resolve
85
+ * to mapped scalars, or the bare base type name (enums / input objects).
86
+ */
87
+ pyTypeFromTypeNode(type) {
88
+ if (type.kind === graphql_1.Kind.NON_NULL_TYPE) {
89
+ return this.innerFromTypeNode(type.type);
90
+ }
91
+ this._usesOptional = true;
92
+ return `Optional[${this.innerFromTypeNode(type)}]`;
93
+ }
94
+ innerFromTypeNode(type) {
95
+ if (type.kind === graphql_1.Kind.LIST_TYPE) {
96
+ return `list[${this.pyTypeFromTypeNode(type.type)}]`;
97
+ }
98
+ if (type.kind === graphql_1.Kind.NON_NULL_TYPE) {
99
+ // Non-null base (e.g. inside a list) — no Optional wrapper.
100
+ return this.innerFromTypeNode(type.type);
101
+ }
102
+ // NamedType
103
+ const name = type.name.value;
104
+ const mapped = python_helpers_js_1.PYTHON_SCALARS[name];
105
+ if (mapped) {
106
+ return mapped.input;
107
+ }
108
+ const schemaType = this._schema.getType(name);
109
+ if (schemaType && (0, graphql_1.isScalarType)(schemaType)) {
110
+ this._usesAny = true;
111
+ return 'Any';
112
+ }
113
+ // enum or input object -> bare name (quoted forward ref by caller)
114
+ return name;
115
+ }
116
+ // --- Class builders ----------------------------------------------------
117
+ /**
118
+ * Build a variables `TypedDict`. Variable keys are ALWAYS the wire (GraphQL)
119
+ * name — they are sent to the server as-is. If every key is a valid Python
120
+ * attribute the readable class syntax is used; otherwise (a key is a keyword /
121
+ * non-identifier) the functional `TypedDict('Name', { 'key': '...' })` syntax
122
+ * is emitted so the offending keys remain valid.
123
+ */
124
+ buildVariablesClass(name, fields) {
125
+ if (fields.length === 0) {
126
+ return `class ${name}(TypedDict):\n${INDENT}pass`;
127
+ }
128
+ const needsFunctional = fields.some(f => !(0, python_helpers_js_1.isValidClassAttr)(f.key));
129
+ if (needsFunctional) {
130
+ const entries = fields.map(f => `${INDENT}'${f.key}': '${f.annotation}',`);
131
+ return [`${name} = TypedDict('${name}', {`, ...entries, '})'].join('\n');
132
+ }
133
+ const lines = fields.map(f => `${INDENT}${f.key}: '${f.annotation}'`);
134
+ return [`class ${name}(TypedDict):`, ...lines].join('\n');
135
+ }
136
+ /**
137
+ * Emit the per-class `__init__` that pre-maps wire keys to their escaped
138
+ * attribute names before delegating to the base model. Only emitted for result
139
+ * classes that contain keyword fields.
140
+ */
141
+ /**
142
+ * Render a single result field line: `key: 'annotation'`, with a pydantic
143
+ * `Field(alias=...)` when the Python attribute differs from the wire response
144
+ * key, and a `None` default for optional fields.
145
+ */
146
+ renderResultField(field) {
147
+ const optional = field.annotation.startsWith('Optional[');
148
+ let assignment = '';
149
+ if (field.wire !== undefined && field.key !== field.wire) {
150
+ this._usesField = true;
151
+ assignment = optional
152
+ ? ` = Field(default=None, alias='${field.wire}')`
153
+ : ` = Field(alias='${field.wire}')`;
154
+ }
155
+ else if (optional) {
156
+ assignment = ' = None';
157
+ }
158
+ return `${field.key}: '${field.annotation}'${assignment}`;
159
+ }
160
+ /**
161
+ * Build a result base-model subclass. A field whose Python attribute differs
162
+ * from the wire key is pinned with `Field(alias=...)`, and a
163
+ * `model_config = ConfigDict(populate_by_name=True)` line is prepended so such
164
+ * classes can also be built by attribute name.
165
+ */
166
+ buildResultClass(name, fields) {
167
+ this._usesBaseModel = true;
168
+ const header = `class ${name}(${this._baseModel}):`;
169
+ if (fields.length === 0) {
170
+ return `${header}\n${INDENT}pass`;
171
+ }
172
+ const lines = [header];
173
+ if (fields.some(f => f.wire !== undefined && f.key !== f.wire)) {
174
+ this._usesConfigDict = true;
175
+ lines.push(`${INDENT}model_config = ConfigDict(populate_by_name=True)`);
176
+ }
177
+ for (const field of fields) {
178
+ lines.push(`${INDENT}${this.renderResultField(field)}`);
179
+ }
180
+ return lines.join('\n');
181
+ }
182
+ // --- Selection set walking ---------------------------------------------
183
+ /**
184
+ * Emit a `TypedDict` for `selectionSet` (a selection against `parentType`),
185
+ * named `typeName`. Nested object selections are emitted FIRST (deepest
186
+ * first) so references resolve top-to-bottom. Returns nothing; classes are
187
+ * pushed onto `out`.
188
+ */
189
+ processSelectionSet(parentType, selectionSet, typeName, out) {
190
+ var _a, _b, _c, _d;
191
+ const fields = [];
192
+ const addField = (responseKey, annotation) => {
193
+ const key = (0, python_helpers_js_1.resultFieldKey)(responseKey, this._namingConvention);
194
+ // Record the wire (response) key so a `Field(alias=...)` is emitted when
195
+ // the Python attribute differs (snake_case conversion or keyword escape).
196
+ fields.push({ key, annotation, wire: responseKey });
197
+ };
198
+ for (const selection of selectionSet.selections) {
199
+ // Fragments (spread / inline) are not supported yet. Fail loudly instead
200
+ // of silently omitting their fields, which would otherwise produce a
201
+ // result type that looks valid but is missing data.
202
+ if (selection.kind === graphql_1.Kind.FRAGMENT_SPREAD) {
203
+ throw new Error(`@graphql-codegen/python-operations: fragment spread "...${selection.name.value}" on ` +
204
+ `"${parentType.name}" is not supported yet. Inline the fragment's fields directly into ` +
205
+ 'the operation for now.');
206
+ }
207
+ if (selection.kind === graphql_1.Kind.INLINE_FRAGMENT) {
208
+ const onType = (_b = (_a = selection.typeCondition) === null || _a === void 0 ? void 0 : _a.name.value) !== null && _b !== void 0 ? _b : parentType.name;
209
+ throw new Error(`@graphql-codegen/python-operations: inline fragment "... on ${onType}" on ` +
210
+ `"${parentType.name}" is not supported yet. Union/interface member selections cannot ` +
211
+ 'be generated; select only common fields for now.');
212
+ }
213
+ const fieldNode = selection;
214
+ const fieldName = fieldNode.name.value;
215
+ const responseKey = (_d = (_c = fieldNode.alias) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : fieldName;
216
+ if (fieldName === '__typename') {
217
+ // `__typename` selections become a `Literal["ParentType"]` attribute.
218
+ // pydantic forbids a leading-underscore field name, so the attribute is
219
+ // `typename__` with `Field(alias='__typename')` pinning the wire key.
220
+ this._usesLiteral = true;
221
+ fields.push({
222
+ key: 'typename__',
223
+ annotation: `Literal["${parentType.name}"]`,
224
+ wire: '__typename',
225
+ });
226
+ continue;
227
+ }
228
+ const fieldDef = parentType.getFields()[fieldName];
229
+ if (!fieldDef) {
230
+ // Unknown field (e.g. introspection on a type without it) — skip.
231
+ continue;
232
+ }
233
+ const fieldType = fieldDef.type;
234
+ const namedType = (0, graphql_1.getNamedType)(fieldType);
235
+ if (((0, graphql_1.isObjectType)(namedType) || (0, graphql_1.isInterfaceType)(namedType)) && fieldNode.selectionSet) {
236
+ const nestedName = `${typeName}${this.pascal(responseKey)}`;
237
+ // Recurse FIRST so deepest types are emitted before this one.
238
+ this.processSelectionSet(namedType, fieldNode.selectionSet, nestedName, out);
239
+ addField(responseKey, this.pyTypeFromGraphQL(fieldType, nestedName));
240
+ }
241
+ else {
242
+ // Scalar / enum leaf (or union without object handling).
243
+ addField(responseKey, this.pyTypeFromGraphQL(fieldType, namedType.name));
244
+ }
245
+ }
246
+ out.push(this.buildResultClass(typeName, fields));
247
+ }
248
+ buildVariables(variableDefinitions, variablesTypeName) {
249
+ const fields = variableDefinitions.map(def => {
250
+ // Variable keys are ALWAYS the wire name (sent to the server as-is).
251
+ const name = def.variable.name.value;
252
+ const annotation = this.pyTypeFromTypeNode(def.type);
253
+ return { key: name, annotation };
254
+ });
255
+ return this.buildVariablesClass(variablesTypeName, fields);
256
+ }
257
+ /** Generate all types for a single operation. Returns joined class blocks. */
258
+ generateOperation(operation) {
259
+ var _a, _b, _c;
260
+ const operationType = operation.operation; // 'query' | 'mutation' | 'subscription'
261
+ const operationTypeName = operationType.charAt(0).toUpperCase() + operationType.slice(1);
262
+ const operationName = (_b = (_a = operation.name) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : `Anonymous${this._anonymousCount++}`;
263
+ const baseName = `${this.pascal(operationName)}${operationTypeName}`;
264
+ const rootType = this.operationRootTypes[operationType];
265
+ const out = [];
266
+ if (rootType) {
267
+ this.processSelectionSet(rootType, operation.selectionSet, baseName, out);
268
+ }
269
+ out.push(this.buildVariables((_c = operation.variableDefinitions) !== null && _c !== void 0 ? _c : [], `${baseName}Variables`));
270
+ return out.join('\n\n\n');
271
+ }
272
+ /** Build the `prepend` import lines, emitting only what is referenced. */
273
+ getImports() {
274
+ const imports = [];
275
+ const typingParts = [];
276
+ if (this._usesOptional) {
277
+ typingParts.push('Optional');
278
+ }
279
+ // Every operation emits at least a variables TypedDict.
280
+ typingParts.push('TypedDict');
281
+ if (this._usesLiteral) {
282
+ typingParts.push('Literal');
283
+ }
284
+ if (this._usesAny) {
285
+ typingParts.push('Any');
286
+ }
287
+ imports.push(`from typing import ${typingParts.join(', ')}`);
288
+ if (this._usesBaseModel) {
289
+ // `ConfigDict` / `Field` are pydantic names; emit them from the same module
290
+ // as the base model, and only when the generated content uses them.
291
+ const parts = [this._baseModel];
292
+ if (this._usesConfigDict) {
293
+ parts.push('ConfigDict');
294
+ }
295
+ if (this._usesField) {
296
+ parts.push('Field');
297
+ }
298
+ imports.push(`from ${this._runtimeImport} import ${parts.join(', ')}`);
299
+ }
300
+ if (this._typesImport) {
301
+ imports.push(`from ${this._typesImport} import *`);
302
+ }
303
+ return imports;
304
+ }
305
+ }
306
+ exports.PythonOperationsVisitor = PythonOperationsVisitor;
File without changes
@@ -0,0 +1,20 @@
1
+ import { concatAST, Kind } from 'graphql';
2
+ import { PythonOperationsVisitor } from './visitor.js';
3
+ export * from './config.js';
4
+ export * from './visitor.js';
5
+ export * from './python-helpers.js';
6
+ /**
7
+ * Document-driven plugin: for each GraphQL operation in the provided documents,
8
+ * emit a per-operation result `TypedDict` (with named nested `TypedDict`s for
9
+ * every object selection) plus a `<Operation>Variables` `TypedDict`.
10
+ */
11
+ export const plugin = (schema, documents, config) => {
12
+ const allAst = concatAST(documents.map(d => d.document).filter(Boolean));
13
+ const operations = allAst.definitions.filter((def) => def.kind === Kind.OPERATION_DEFINITION);
14
+ const visitor = new PythonOperationsVisitor(schema, config);
15
+ const definitions = operations.map(op => visitor.generateOperation(op));
16
+ return {
17
+ prepend: visitor.getImports(),
18
+ content: definitions.join('\n\n\n'),
19
+ };
20
+ };
@@ -0,0 +1,24 @@
1
+ import { isReservedField, isValidClassAttr, pythonFieldName as pyFieldName, PYTHON_SCALARS, } from '@graphql-codegen/python-common';
2
+ export { isReservedField, isValidClassAttr, PYTHON_SCALARS, pyFieldName };
3
+ /**
4
+ * Compute the attribute name for a `BaseModel` result class. Under `'snakeCase'`
5
+ * the key is snake-cased (keywords suffixed with `_`); under `'keep'` the wire
6
+ * name is used verbatim, but — because `BaseModel` classes cannot use functional
7
+ * `TypedDict` syntax — a keyword / non-identifier name still falls back to a
8
+ * trailing `_`.
9
+ */
10
+ export function resultFieldKey(name, convention) {
11
+ if (convention === 'snakeCase') {
12
+ return pyFieldName(name);
13
+ }
14
+ return isValidClassAttr(name) ? name : `${name}_`;
15
+ }
16
+ /**
17
+ * Compute the `TypedDict` key for a GraphQL response / variable name under the
18
+ * given naming convention. Under `'keep'` the raw name is returned verbatim
19
+ * (functional `TypedDict` syntax handles invalid keys); under `'snakeCase'` the
20
+ * legacy snake_case + `_`-suffix behavior is applied.
21
+ */
22
+ export function fieldKey(name, convention) {
23
+ return convention === 'snakeCase' ? pyFieldName(name) : name;
24
+ }