@contractkit/plugin-python 0.9.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.
Files changed (39) hide show
  1. package/.turbo/turbo-build$colon$ci.log +35 -0
  2. package/.turbo/turbo-build.log +15 -0
  3. package/.turbo/turbo-test$colon$ci.log +59 -0
  4. package/.turbo/turbo-test.log +15 -0
  5. package/CHANGELOG.md +118 -0
  6. package/README.md +86 -0
  7. package/coverage/base.css +224 -0
  8. package/coverage/block-navigation.js +87 -0
  9. package/coverage/clover.xml +559 -0
  10. package/coverage/coverage-final.json +4 -0
  11. package/coverage/favicon.png +0 -0
  12. package/coverage/index.html +131 -0
  13. package/coverage/prettify.css +1 -0
  14. package/coverage/prettify.js +2 -0
  15. package/coverage/sort-arrow-sprite.png +0 -0
  16. package/coverage/sorter.js +210 -0
  17. package/coverage/src/codegen-client.ts.html +2071 -0
  18. package/coverage/src/codegen-models.ts.html +1360 -0
  19. package/coverage/src/index.html +131 -0
  20. package/coverage/tests/helpers.ts.html +667 -0
  21. package/coverage/tests/index.html +116 -0
  22. package/dist/codegen-client.d.ts +30 -0
  23. package/dist/codegen-client.d.ts.map +1 -0
  24. package/dist/codegen-models.d.ts +19 -0
  25. package/dist/codegen-models.d.ts.map +1 -0
  26. package/dist/index.d.ts +17 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +1046 -0
  29. package/dist/index.js.map +1 -0
  30. package/eslint.config.js +6 -0
  31. package/package.json +45 -0
  32. package/src/codegen-client.ts +662 -0
  33. package/src/codegen-models.ts +425 -0
  34. package/src/index.ts +143 -0
  35. package/tests/codegen-client.test.ts +361 -0
  36. package/tests/codegen-models.test.ts +295 -0
  37. package/tests/helpers.ts +194 -0
  38. package/tsconfig.json +9 -0
  39. package/vitest.config.ts +14 -0
@@ -0,0 +1,662 @@
1
+ import type { OpRootNode, OpRouteNode, OpOperationNode, OpResponseHeaderNode, ContractTypeNode, ParamSource } from '@contractkit/core';
2
+ import { resolveModifiers, classifyContentType } from '@contractkit/core';
3
+ import { renderPyType, toPythonFieldName } from './codegen-models.js';
4
+
5
+ // ─── Public entry point ────────────────────────────────────────────────────
6
+
7
+ export interface ClientCodegenOptions {
8
+ /** Map from model name → Python module path (e.g. "._models_payments") */
9
+ modelModulePaths?: Map<string, string>;
10
+ /** Current client's module name (e.g. "_client_payments") — used to avoid self-imports */
11
+ currentModule?: string;
12
+ /** Set of model names that have Input variants */
13
+ modelsWithInput?: Set<string>;
14
+ /**
15
+ * Whether to emit client methods for operations marked `internal`. Defaults to `false` —
16
+ * internal ops are omitted so consumers don't pick them up. Set to `true` for an
17
+ * internal-use SDK that should expose them.
18
+ */
19
+ includeInternal?: boolean;
20
+ }
21
+
22
+ /**
23
+ * Returns true if the root contains at least one operation eligible for client emission.
24
+ * With `includeInternal: false` (default) that means at least one non-internal op; with
25
+ * `includeInternal: true` any op qualifies.
26
+ */
27
+ export function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {
28
+ for (const route of root.routes) {
29
+ for (const op of route.operations) {
30
+ if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+
36
+ /**
37
+ * Generate a Pydantic/httpx async Python client class from an OpRootNode.
38
+ */
39
+ export function generatePythonClient(root: OpRootNode, opts: ClientCodegenOptions = {}): string {
40
+ const clientClassName = deriveClientClassName(root.file);
41
+ const { modelsWithInput } = opts;
42
+ const includeInternal = opts.includeInternal ?? false;
43
+
44
+ // Collect all model types referenced in public ops
45
+ const referencedModels = collectReferencedModels(root, modelsWithInput, includeInternal);
46
+
47
+ const lines: string[] = [];
48
+ lines.push('# Auto-generated by contractkit-plugin-python-sdk. Do not edit manually.');
49
+ lines.push('from __future__ import annotations');
50
+ lines.push('');
51
+
52
+ // stdlib imports
53
+ const needsDatetime = referencedModels.has('__datetime__');
54
+ const needsDate = referencedModels.has('__date__');
55
+ const needsTime = referencedModels.has('__time__');
56
+ const needsUUID = referencedModels.has('__uuid__');
57
+ const needsAny = referencedModels.has('__any__');
58
+
59
+ if (needsDatetime || needsDate || needsTime) {
60
+ const dtParts: string[] = [];
61
+ if (needsDate) dtParts.push('date');
62
+ if (needsDatetime) dtParts.push('datetime');
63
+ if (needsTime) dtParts.push('time');
64
+ lines.push(`from datetime import ${dtParts.join(', ')}`);
65
+ }
66
+ if (needsUUID) lines.push('from uuid import UUID');
67
+
68
+ // Collect public ops once — used both for TypedDict emission and method generation.
69
+ const publicOps: Array<{ route: OpRouteNode; op: OpOperationNode }> = [];
70
+ for (const route of root.routes) {
71
+ for (const op of route.operations) {
72
+ if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
73
+ publicOps.push({ route, op });
74
+ }
75
+ }
76
+ const opsWithRespHeaders = publicOps.filter(({ op }) => {
77
+ const primary = op.responses.find(r => r.bodyType) ?? op.responses[0];
78
+ return (primary?.headers?.length ?? 0) > 0;
79
+ });
80
+
81
+ if (needsAny || opsWithRespHeaders.length > 0) {
82
+ const typingImports: string[] = [];
83
+ if (needsAny) typingImports.push('Any');
84
+ if (opsWithRespHeaders.length > 0) typingImports.push('TypedDict');
85
+ lines.push(`from typing import ${typingImports.join(', ')}`);
86
+ }
87
+ lines.push('from ._base_client import BaseClient, SdkError # noqa: F401');
88
+
89
+ // Model imports grouped by module
90
+ const modelImportsByModule = new Map<string, Set<string>>();
91
+ for (const name of referencedModels) {
92
+ if (name.startsWith('__')) continue; // sentinel keys
93
+ const modulePath = opts.modelModulePaths?.get(name);
94
+ if (modulePath) {
95
+ let s = modelImportsByModule.get(modulePath);
96
+ if (!s) {
97
+ s = new Set();
98
+ modelImportsByModule.set(modulePath, s);
99
+ }
100
+ s.add(name);
101
+ }
102
+ }
103
+ for (const [mod, names] of [...modelImportsByModule].sort((a, b) => a[0].localeCompare(b[0]))) {
104
+ const sorted = [...names].sort().join(', ');
105
+ lines.push(`from ${mod} import ${sorted}`);
106
+ }
107
+
108
+ // Per-method response-header TypedDicts.
109
+ for (const { route, op } of opsWithRespHeaders) {
110
+ const primary = op.responses.find(r => r.bodyType) ?? op.responses[0]!;
111
+ const className = `${snakeToPascal(deriveMethodName(op, route))}Headers`;
112
+ lines.push('');
113
+ lines.push('');
114
+ lines.push(`class ${className}(TypedDict, total=False):`);
115
+ for (const h of primary.headers!) {
116
+ const pyName = toPythonFieldName(h.name);
117
+ const tag = h.optional ? 'optional' : 'required';
118
+ lines.push(` ${pyName}: str # ${h.name} (${tag})`);
119
+ }
120
+ }
121
+
122
+ lines.push('');
123
+ lines.push('');
124
+ lines.push(`class ${clientClassName}(BaseClient):`);
125
+
126
+ let hasAnyMethod = false;
127
+ for (const route of root.routes) {
128
+ for (const op of route.operations) {
129
+ const mods = resolveModifiers(route, op);
130
+ if (!includeInternal && mods.includes('internal')) continue;
131
+ hasAnyMethod = true;
132
+ lines.push('');
133
+ if (mods.includes('deprecated')) lines.push(' # @deprecated');
134
+ lines.push(...generateMethod(route, op, opts));
135
+ }
136
+ }
137
+
138
+ if (!hasAnyMethod) {
139
+ lines.push(' pass');
140
+ }
141
+
142
+ lines.push('');
143
+
144
+ return lines.join('\n');
145
+ }
146
+
147
+ // ─── Method generation ────────────────────────────────────────────────────
148
+
149
+ interface MethodParam {
150
+ name: string;
151
+ type: string;
152
+ optional: boolean;
153
+ isModel: boolean; // Pydantic BaseModel → use .model_dump(mode="json")
154
+ }
155
+
156
+ function generateMethod(route: OpRouteNode, op: OpOperationNode, opts: ClientCodegenOptions): string[] {
157
+ const lines: string[] = [];
158
+ const { modelsWithInput } = opts;
159
+ const methodName = deriveMethodName(op, route);
160
+ const httpMethod = op.method.toUpperCase();
161
+
162
+ const params = buildMethodParams(route, op, modelsWithInput);
163
+ const selfParam = 'self';
164
+ const allParams = params.map(p => {
165
+ if (p.optional) return `${p.name}: ${p.type} | None = None`;
166
+ return `${p.name}: ${p.type}`;
167
+ });
168
+ const paramStr = allParams.length > 0 ? `, ${allParams.join(', ')}` : '';
169
+
170
+ // Return type — non-JSON responses ignore the schema and return raw bytes/str.
171
+ const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];
172
+ const isVoid = !primaryResponse?.bodyType;
173
+ const respCategory = primaryResponse?.contentType ? classifyContentType(primaryResponse.contentType) : 'json';
174
+ const dataType = isVoid
175
+ ? 'None'
176
+ : respCategory === 'text'
177
+ ? 'str'
178
+ : respCategory === 'binary'
179
+ ? 'bytes'
180
+ : renderPyType(primaryResponse!.bodyType!, modelsWithInput);
181
+ const isModelReturn = !isVoid && respCategory === 'json' && isModelRef(primaryResponse!.bodyType!, modelsWithInput);
182
+ const isListModelReturn = !isVoid && respCategory === 'json' && isListModelRef(primaryResponse!.bodyType!, modelsWithInput);
183
+ const respHeaders = primaryResponse?.headers ?? [];
184
+ const hasRespHeaders = respHeaders.length > 0;
185
+ const headersTypeName = hasRespHeaders ? `${snakeToPascal(methodName)}Headers` : '';
186
+ const returnType = hasRespHeaders ? (isVoid ? headersTypeName : `tuple[${dataType}, ${headersTypeName}]`) : dataType;
187
+
188
+ // Description
189
+ const desc = op.description ?? route.description;
190
+ if (op.name || desc) {
191
+ lines.push(` async def ${methodName}(${selfParam}${paramStr}) -> ${returnType}:`);
192
+ lines.push(` """`);
193
+ if (op.name) lines.push(` ${op.name}`);
194
+ if (desc) lines.push(` ${desc}`);
195
+ lines.push(` """`);
196
+ } else {
197
+ lines.push(` async def ${methodName}(${selfParam}${paramStr}) -> ${returnType}:`);
198
+ }
199
+
200
+ // Build URL
201
+ const urlExpr = buildUrlExpression(route.path);
202
+
203
+ // Query params
204
+ const hasQuery = !!op.query;
205
+ const primaryBody = op.request?.bodies[0];
206
+ const hasBody = !!primaryBody;
207
+ const isMultipart = primaryBody?.contentType === 'multipart/form-data';
208
+ const hasCustomHeaders = !!op.headers;
209
+
210
+ // Build kwargs for _fetch
211
+ const fetchKwargs: string[] = [];
212
+ fetchKwargs.push(`method="${httpMethod}"`);
213
+
214
+ const reqCategory = primaryBody?.contentType ? classifyContentType(primaryBody.contentType) : 'json';
215
+ if (hasBody) {
216
+ const bodyParam = params.find(p => p.name === 'body');
217
+ if (isMultipart) {
218
+ fetchKwargs.push('body=body');
219
+ } else if (reqCategory === 'text' || reqCategory === 'binary') {
220
+ // Pass-through: caller supplies a str / bytes payload that goes on the wire as-is.
221
+ fetchKwargs.push('body=body');
222
+ } else if (bodyParam?.isModel) {
223
+ fetchKwargs.push('body=body.model_dump(mode="json")');
224
+ } else {
225
+ fetchKwargs.push('body=body');
226
+ }
227
+ // Forward the declared content-type so `_fetch` sets the correct Content-Type header
228
+ // (vendor JSON types like `application/vnd.api+json` still serialize as JSON but need
229
+ // their literal mime on the wire).
230
+ if (primaryBody.contentType !== 'application/json') {
231
+ fetchKwargs.push(`content_type=${JSON.stringify(primaryBody.contentType)}`);
232
+ }
233
+ if (reqCategory === 'text' || reqCategory === 'binary') {
234
+ fetchKwargs.push(`body_kind="${reqCategory}"`);
235
+ }
236
+ }
237
+ if (respCategory === 'text' || respCategory === 'binary') {
238
+ fetchKwargs.push(`response_kind="${respCategory}"`);
239
+ }
240
+
241
+ if (hasQuery) {
242
+ fetchKwargs.push('params=query');
243
+ }
244
+
245
+ if (hasCustomHeaders) {
246
+ fetchKwargs.push('extra_headers=custom_headers');
247
+ }
248
+
249
+ const kwargsStr = fetchKwargs.length > 1 ? fetchKwargs.join(', ') : (fetchKwargs[0] ?? '');
250
+
251
+ if (hasRespHeaders) {
252
+ lines.push(` result, _response_headers = await self._fetch_with_headers(${urlExpr}, ${kwargsStr})`);
253
+ lines.push(...buildHeadersDictLines(respHeaders, headersTypeName));
254
+ } else {
255
+ lines.push(` result = await self._fetch(${urlExpr}, ${kwargsStr})`);
256
+ }
257
+
258
+ if (isVoid) {
259
+ if (hasRespHeaders) {
260
+ lines.push(` return headers`);
261
+ } else {
262
+ lines.push(` return None`);
263
+ }
264
+ } else {
265
+ let dataExpr: string;
266
+ if (isListModelReturn) {
267
+ const innerType = getListItemType(primaryResponse!.bodyType!, modelsWithInput);
268
+ dataExpr = `[${innerType}.model_validate(item) for item in result]`;
269
+ } else if (isModelReturn) {
270
+ dataExpr = `${dataType}.model_validate(result)`;
271
+ } else {
272
+ dataExpr = 'result';
273
+ }
274
+ if (hasRespHeaders) {
275
+ lines.push(` return ${dataExpr}, headers`);
276
+ } else {
277
+ lines.push(` return ${dataExpr}`);
278
+ }
279
+ }
280
+
281
+ return lines;
282
+ }
283
+
284
+ /** Build the lines that construct a TypedDict literal of declared response headers. */
285
+ function buildHeadersDictLines(headers: OpResponseHeaderNode[], typeName: string): string[] {
286
+ const lines: string[] = [];
287
+ lines.push(` headers: ${typeName} = {}`);
288
+ for (const h of headers) {
289
+ const pyName = toPythonFieldName(h.name);
290
+ lines.push(` if ${JSON.stringify(h.name.toLowerCase())} in _response_headers:`);
291
+ lines.push(` headers[${JSON.stringify(pyName)}] = _response_headers[${JSON.stringify(h.name.toLowerCase())}]`);
292
+ }
293
+ return lines;
294
+ }
295
+
296
+ /** snake_case → PascalCase. */
297
+ function snakeToPascal(s: string): string {
298
+ return s
299
+ .split('_')
300
+ .filter(Boolean)
301
+ .map(p => p.charAt(0).toUpperCase() + p.slice(1))
302
+ .join('');
303
+ }
304
+
305
+ // ─── URL building ─────────────────────────────────────────────────────────
306
+
307
+ function buildUrlExpression(path: string): string {
308
+ // Replace {paramName} with Python f-string interpolation
309
+ const hasBraces = /\{[a-zA-Z_][a-zA-Z0-9_]*\}/.test(path);
310
+ if (!hasBraces) return `"${path}"`;
311
+ const interpolated = path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_m, name) => `{${name}}`);
312
+ return `f"${interpolated}"`;
313
+ }
314
+
315
+ // ─── Parameter building ───────────────────────────────────────────────────
316
+
317
+ function buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {
318
+ const params: MethodParam[] = [];
319
+
320
+ // Path params
321
+ if (route.params) {
322
+ if (route.params.kind === 'params') {
323
+ for (const p of route.params.nodes) {
324
+ params.push({
325
+ name: toPythonFieldName(p.name),
326
+ type: renderPyType(p.type, modelsWithInput),
327
+ optional: false,
328
+ isModel: false,
329
+ });
330
+ }
331
+ } else if (route.params.kind === 'ref') {
332
+ const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;
333
+ params.push({ name: 'params', type: typeName, optional: false, isModel: true });
334
+ } else {
335
+ params.push({ name: 'params', type: renderPyType(route.params.node, modelsWithInput), optional: false, isModel: false });
336
+ }
337
+ }
338
+
339
+ // Body — use the first declared MIME's body type as the parameter type.
340
+ // Multi-MIME support in Python collapses to a single signature using the primary body.
341
+ const primaryBody = op.request?.bodies[0];
342
+ if (primaryBody) {
343
+ const cat = classifyContentType(primaryBody.contentType);
344
+ if (cat === 'multipart' || cat === 'binary') {
345
+ params.push({ name: 'body', type: 'bytes', optional: false, isModel: false });
346
+ } else if (cat === 'text') {
347
+ params.push({ name: 'body', type: 'str', optional: false, isModel: false });
348
+ } else {
349
+ const bodyType = renderInputPyType(primaryBody.bodyType, modelsWithInput);
350
+ const isModel = isModelRef(primaryBody.bodyType, modelsWithInput);
351
+ params.push({ name: 'body', type: bodyType, optional: false, isModel });
352
+ }
353
+ }
354
+
355
+ // Query
356
+ if (op.query) {
357
+ const queryType = renderParamSourceType(op.query, modelsWithInput, true);
358
+ params.push({ name: 'query', type: queryType, optional: true, isModel: false });
359
+ }
360
+
361
+ // Headers
362
+ if (op.headers) {
363
+ const headersType = renderParamSourceType(op.headers, modelsWithInput, true);
364
+ params.push({ name: 'custom_headers', type: headersType, optional: true, isModel: false });
365
+ }
366
+
367
+ return params;
368
+ }
369
+
370
+ function renderParamSourceType(source: ParamSource, modelsWithInput?: Set<string>, forInput = false): string {
371
+ if (source.kind === 'ref') {
372
+ const typeName = forInput && modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;
373
+ return typeName;
374
+ }
375
+ if (source.kind === 'params') {
376
+ // const fields = source.nodes.map(p => {
377
+ // const pyName = toPythonFieldName(p.name);
378
+ // return `"${pyName}": ${renderPyType(p.type, modelsWithInput, forInput)}`;
379
+ // });
380
+ return `dict`; // simplified — inline dicts are hard to type concisely in Python signatures
381
+ }
382
+ return renderPyType(source.node, modelsWithInput, forInput);
383
+ }
384
+
385
+ function renderInputPyType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {
386
+ return renderPyType(type, modelsWithInput, true);
387
+ }
388
+
389
+ // ─── Model reference detection ────────────────────────────────────────────
390
+
391
+ function isModelRef(type: ContractTypeNode, modelsWithInput?: Set<string>): boolean {
392
+ if (type.kind === 'ref') return /^[A-Z]/.test(type.name);
393
+ if (type.kind === 'lazy') return isModelRef(type.inner, modelsWithInput);
394
+ return false;
395
+ }
396
+
397
+ function isListModelRef(type: ContractTypeNode, modelsWithInput?: Set<string>): boolean {
398
+ if (type.kind === 'array') return isModelRef(type.item, modelsWithInput);
399
+ if (type.kind === 'lazy') return isListModelRef(type.inner, modelsWithInput);
400
+ return false;
401
+ }
402
+
403
+ function getListItemType(type: ContractTypeNode, modelsWithInput?: Set<string>): string {
404
+ if (type.kind === 'array') return renderPyType(type.item, modelsWithInput);
405
+ return 'dict';
406
+ }
407
+
408
+ // ─── Referenced model collection ─────────────────────────────────────────
409
+
410
+ /**
411
+ * Collect all model names and scalar sentinels referenced in public operations.
412
+ * Sentinels: __datetime__, __date__, __time__, __uuid__, __any__
413
+ */
414
+ function collectReferencedModels(root: OpRootNode, modelsWithInput?: Set<string>, includeInternal = false): Set<string> {
415
+ const refs = new Set<string>();
416
+
417
+ for (const route of root.routes) {
418
+ for (const op of route.operations) {
419
+ if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
420
+
421
+ if (route.params) collectParamSourceRefs(route.params, refs, modelsWithInput);
422
+ if (op.request) {
423
+ for (const body of op.request.bodies) collectTypeRefs(body.bodyType, refs, modelsWithInput, true);
424
+ }
425
+ for (const resp of op.responses) {
426
+ if (resp.bodyType) collectTypeRefs(resp.bodyType, refs, modelsWithInput, false);
427
+ }
428
+ if (op.query) collectParamSourceRefs(op.query, refs, modelsWithInput);
429
+ if (op.headers) collectParamSourceRefs(op.headers, refs, modelsWithInput);
430
+ }
431
+ }
432
+
433
+ return refs;
434
+ }
435
+
436
+ function collectParamSourceRefs(source: ParamSource, out: Set<string>, modelsWithInput?: Set<string>): void {
437
+ if (source.kind === 'ref') {
438
+ addModelRef(source.name, out, modelsWithInput);
439
+ } else if (source.kind === 'params') {
440
+ for (const p of source.nodes) collectTypeRefs(p.type, out, modelsWithInput);
441
+ } else {
442
+ collectTypeRefs(source.node, out, modelsWithInput);
443
+ }
444
+ }
445
+
446
+ function addModelRef(name: string, out: Set<string>, modelsWithInput?: Set<string>): void {
447
+ if (/^[A-Z]/.test(name)) {
448
+ out.add(name);
449
+ if (modelsWithInput?.has(name)) out.add(`${name}Input`);
450
+ }
451
+ }
452
+
453
+ function collectTypeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>, forInput = false): void {
454
+ switch (type.kind) {
455
+ case 'scalar':
456
+ switch (type.name) {
457
+ case 'date':
458
+ out.add('__date__');
459
+ break;
460
+ case 'time':
461
+ out.add('__time__');
462
+ break;
463
+ case 'datetime':
464
+ out.add('__datetime__');
465
+ break;
466
+ case 'uuid':
467
+ out.add('__uuid__');
468
+ break;
469
+ case 'unknown':
470
+ case 'json':
471
+ case 'object':
472
+ out.add('__any__');
473
+ break;
474
+ }
475
+ break;
476
+ case 'ref':
477
+ if (forInput && modelsWithInput?.has(type.name)) {
478
+ out.add(`${type.name}Input`);
479
+ } else {
480
+ addModelRef(type.name, out, modelsWithInput);
481
+ }
482
+ break;
483
+ case 'array':
484
+ collectTypeRefs(type.item, out, modelsWithInput, forInput);
485
+ break;
486
+ case 'tuple':
487
+ type.items.forEach(t => collectTypeRefs(t, out, modelsWithInput, forInput));
488
+ break;
489
+ case 'record':
490
+ collectTypeRefs(type.key, out, modelsWithInput, forInput);
491
+ collectTypeRefs(type.value, out, modelsWithInput, forInput);
492
+ break;
493
+ case 'union':
494
+ type.members.forEach(m => collectTypeRefs(m, out, modelsWithInput, forInput));
495
+ break;
496
+ case 'discriminatedUnion':
497
+ type.members.forEach(m => collectTypeRefs(m, out, modelsWithInput, forInput));
498
+ break;
499
+ case 'intersection':
500
+ out.add('__any__');
501
+ break;
502
+ case 'lazy':
503
+ collectTypeRefs(type.inner, out, modelsWithInput, forInput);
504
+ break;
505
+ case 'inlineObject':
506
+ out.add('__any__');
507
+ break;
508
+ }
509
+ }
510
+
511
+ // ─── Naming helpers ───────────────────────────────────────────────────────
512
+
513
+ function deriveBaseName(file: string): string {
514
+ const base =
515
+ file
516
+ .split('/')
517
+ .pop()
518
+ ?.replace(/\.(op\.)?ck$/, '') ?? 'Resource';
519
+ return base
520
+ .split('.')
521
+ .map(s => s.charAt(0).toUpperCase() + s.slice(1))
522
+ .join('');
523
+ }
524
+
525
+ export function deriveClientClassName(file: string): string {
526
+ return `${deriveBaseName(file)}Client`;
527
+ }
528
+
529
+ export function deriveClientModuleName(file: string): string {
530
+ const base =
531
+ file
532
+ .split('/')
533
+ .pop()
534
+ ?.replace(/\.(op\.)?ck$/, '') ?? 'client';
535
+ const clean = base.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
536
+ return `_client_${clean}`;
537
+ }
538
+
539
+ export function deriveClientPropertyName(file: string): string {
540
+ const base = deriveBaseName(file);
541
+ return base.charAt(0).toLowerCase() + base.slice(1);
542
+ }
543
+
544
+ function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {
545
+ if (op.sdk) return toSnakeCase(op.sdk);
546
+ if (op.name) return toSnakeCase(op.name);
547
+ return inferMethodName(op.method, route.path);
548
+ }
549
+
550
+ function inferMethodName(method: string, path: string): string {
551
+ const segments = path.split('/').filter(s => s.length > 0);
552
+ const parts: string[] = [method.toLowerCase()];
553
+
554
+ for (const seg of segments) {
555
+ if (seg.startsWith('{')) {
556
+ const paramName = seg.slice(1, -1);
557
+ parts.push('by_' + toSnakeCase(paramName));
558
+ } else {
559
+ parts.push(toSnakeCase(seg.replace(/[.-]/g, '_')));
560
+ }
561
+ }
562
+
563
+ return parts.join('_').replace(/_+/g, '_');
564
+ }
565
+
566
+ function toSnakeCase(s: string): string {
567
+ return s
568
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
569
+ .replace(/[^a-zA-Z0-9]/g, '_')
570
+ .toLowerCase()
571
+ .replace(/_+/g, '_')
572
+ .replace(/^_|_$/g, '');
573
+ }
574
+
575
+ // ─── Shared base client content ───────────────────────────────────────────
576
+
577
+ export const BASE_CLIENT_PY = `# Auto-generated by contractkit-plugin-python-sdk. Do not edit manually.
578
+ from __future__ import annotations
579
+
580
+ import httpx
581
+ from typing import Any
582
+
583
+
584
+ class SdkError(Exception):
585
+ def __init__(self, status: int, status_text: str, body: Any):
586
+ super().__init__(f"{status} {status_text}")
587
+ self.status = status
588
+ self.status_text = status_text
589
+ self.body = body
590
+
591
+
592
+ class BaseClient:
593
+ def __init__(self, base_url: str, headers: dict[str, str] | None = None):
594
+ self._base_url = base_url.rstrip("/")
595
+ self._headers = headers or {}
596
+ self._http = httpx.AsyncClient()
597
+
598
+ async def _fetch(
599
+ self,
600
+ path: str,
601
+ *,
602
+ method: str,
603
+ body: Any = None,
604
+ params: dict | None = None,
605
+ extra_headers: dict | None = None,
606
+ content_type: str | None = None,
607
+ body_kind: str = "json",
608
+ response_kind: str = "json",
609
+ ) -> Any:
610
+ result, _ = await self._fetch_with_headers(
611
+ path,
612
+ method=method,
613
+ body=body,
614
+ params=params,
615
+ extra_headers=extra_headers,
616
+ content_type=content_type,
617
+ body_kind=body_kind,
618
+ response_kind=response_kind,
619
+ )
620
+ return result
621
+
622
+ async def _fetch_with_headers(
623
+ self,
624
+ path: str,
625
+ *,
626
+ method: str,
627
+ body: Any = None,
628
+ params: dict | None = None,
629
+ extra_headers: dict | None = None,
630
+ content_type: str | None = None,
631
+ body_kind: str = "json",
632
+ response_kind: str = "json",
633
+ ) -> tuple[Any, dict[str, str]]:
634
+ headers = {**self._headers, **(extra_headers or {})}
635
+ if body is not None:
636
+ headers["Content-Type"] = content_type or "application/json"
637
+ # body_kind controls how httpx serializes the request body:
638
+ # "json" — body is a JSON-serializable object, sent via httpx's json= kwarg
639
+ # "text"/"binary" — body is a raw str/bytes payload, sent via content= unchanged
640
+ request_kwargs: dict[str, Any] = {"method": method, "url": f"{self._base_url}{path}", "params": params, "headers": headers}
641
+ if body is not None:
642
+ if body_kind == "json":
643
+ request_kwargs["json"] = body
644
+ else:
645
+ request_kwargs["content"] = body
646
+ response = await self._http.request(**request_kwargs)
647
+ if not response.is_success:
648
+ try:
649
+ error_body = response.json()
650
+ except Exception:
651
+ error_body = response.text
652
+ raise SdkError(response.status_code, response.reason_phrase, error_body)
653
+ # HTTP headers are case-insensitive — normalize to lowercase keys for stable lookup.
654
+ response_headers = {k.lower(): v for k, v in response.headers.items()}
655
+ if response.status_code == 204 or not response.content:
656
+ return None, response_headers
657
+ if response_kind == "text":
658
+ return response.text, response_headers
659
+ if response_kind == "binary":
660
+ return response.content, response_headers
661
+ return response.json(), response_headers
662
+ `;