@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.
- package/.turbo/turbo-build$colon$ci.log +35 -0
- package/.turbo/turbo-build.log +15 -0
- package/.turbo/turbo-test$colon$ci.log +59 -0
- package/.turbo/turbo-test.log +15 -0
- package/CHANGELOG.md +118 -0
- package/README.md +86 -0
- package/coverage/base.css +224 -0
- package/coverage/block-navigation.js +87 -0
- package/coverage/clover.xml +559 -0
- package/coverage/coverage-final.json +4 -0
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +131 -0
- package/coverage/prettify.css +1 -0
- package/coverage/prettify.js +2 -0
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +210 -0
- package/coverage/src/codegen-client.ts.html +2071 -0
- package/coverage/src/codegen-models.ts.html +1360 -0
- package/coverage/src/index.html +131 -0
- package/coverage/tests/helpers.ts.html +667 -0
- package/coverage/tests/index.html +116 -0
- package/dist/codegen-client.d.ts +30 -0
- package/dist/codegen-client.d.ts.map +1 -0
- package/dist/codegen-models.d.ts +19 -0
- package/dist/codegen-models.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1046 -0
- package/dist/index.js.map +1 -0
- package/eslint.config.js +6 -0
- package/package.json +45 -0
- package/src/codegen-client.ts +662 -0
- package/src/codegen-models.ts +425 -0
- package/src/index.ts +143 -0
- package/tests/codegen-client.test.ts +361 -0
- package/tests/codegen-models.test.ts +295 -0
- package/tests/helpers.ts +194 -0
- package/tsconfig.json +9 -0
- package/vitest.config.ts +14 -0
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
import type { ContractRootNode, ModelNode, FieldNode, ContractTypeNode } from '@contractkit/core';
|
|
2
|
+
import { computeModelsWithInput, topoSortModels, collectExternalRefs, collectExternalInputRefs } from '@contractkit/core';
|
|
3
|
+
|
|
4
|
+
// ─── Public entry point ────────────────────────────────────────────────────
|
|
5
|
+
|
|
6
|
+
export interface ModelCodegenOptions {
|
|
7
|
+
/** Map from model name → output module name (for cross-file imports) */
|
|
8
|
+
modelModulePaths?: Map<string, string>;
|
|
9
|
+
/** Current output module name (used to skip self-imports) */
|
|
10
|
+
currentModule?: string;
|
|
11
|
+
/** Set of model names that have Input variants (cross-file) */
|
|
12
|
+
modelsWithInput?: Set<string>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Generate Pydantic v2 model classes from a ContractRootNode.
|
|
17
|
+
*/
|
|
18
|
+
export function generatePydanticModels(root: ContractRootNode, opts: ModelCodegenOptions = {}): string {
|
|
19
|
+
const externalRefs = collectExternalRefs(root);
|
|
20
|
+
const externalModelsWithInput = opts.modelsWithInput ?? new Set<string>();
|
|
21
|
+
const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);
|
|
22
|
+
const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);
|
|
23
|
+
|
|
24
|
+
const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];
|
|
25
|
+
const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs])].sort();
|
|
26
|
+
|
|
27
|
+
// Track needed imports
|
|
28
|
+
const imports = new ImportTracker();
|
|
29
|
+
imports.add('pydantic', 'BaseModel');
|
|
30
|
+
|
|
31
|
+
// Pre-scan all models to determine what imports will be needed
|
|
32
|
+
for (const model of root.models) {
|
|
33
|
+
if (model.type) {
|
|
34
|
+
scanTypeImports(model.type, imports);
|
|
35
|
+
} else {
|
|
36
|
+
for (const f of model.fields) {
|
|
37
|
+
scanTypeImports(f.type, imports);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const lines: string[] = [];
|
|
43
|
+
lines.push('# Auto-generated by contractkit-plugin-python-sdk. Do not edit manually.');
|
|
44
|
+
lines.push('from __future__ import annotations');
|
|
45
|
+
|
|
46
|
+
// Cross-file imports for external model refs
|
|
47
|
+
const crossFileImports: string[] = [];
|
|
48
|
+
for (const ref of allExternalRefs) {
|
|
49
|
+
const modulePath = opts.modelModulePaths?.get(ref);
|
|
50
|
+
if (modulePath && modulePath !== opts.currentModule) {
|
|
51
|
+
crossFileImports.push(`from ${modulePath} import ${ref}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// We'll prepend stdlib/typing imports after, once we know what's needed
|
|
56
|
+
// Build model output first
|
|
57
|
+
const modelLines: string[] = [];
|
|
58
|
+
for (const model of topoSortModels(root.models)) {
|
|
59
|
+
modelLines.push('');
|
|
60
|
+
modelLines.push(...generateModel(model, allModelsWithInput, imports));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Now emit stdlib imports
|
|
64
|
+
const stdlibLines = imports.render();
|
|
65
|
+
lines.push(...stdlibLines);
|
|
66
|
+
if (crossFileImports.length > 0) {
|
|
67
|
+
lines.push('');
|
|
68
|
+
lines.push(...crossFileImports);
|
|
69
|
+
}
|
|
70
|
+
lines.push(...modelLines);
|
|
71
|
+
lines.push('');
|
|
72
|
+
|
|
73
|
+
return lines.join('\n');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ─── Import tracking ──────────────────────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
class ImportTracker {
|
|
79
|
+
private groups: Map<string, Set<string>> = new Map();
|
|
80
|
+
|
|
81
|
+
add(module: string, name: string): void {
|
|
82
|
+
let s = this.groups.get(module);
|
|
83
|
+
if (!s) {
|
|
84
|
+
s = new Set();
|
|
85
|
+
this.groups.set(module, s);
|
|
86
|
+
}
|
|
87
|
+
s.add(name);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
has(module: string, name: string): boolean {
|
|
91
|
+
return this.groups.get(module)?.has(name) ?? false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
render(): string[] {
|
|
95
|
+
// Order: stdlib → typing → pydantic
|
|
96
|
+
const ORDER = ['__future__', 'datetime', 'uuid', 'typing', 'pydantic'];
|
|
97
|
+
const lines: string[] = [];
|
|
98
|
+
lines.push('');
|
|
99
|
+
for (const mod of ORDER) {
|
|
100
|
+
const names = this.groups.get(mod);
|
|
101
|
+
if (!names || names.size === 0) continue;
|
|
102
|
+
const sorted = [...names].sort().join(', ');
|
|
103
|
+
lines.push(`from ${mod} import ${sorted}`);
|
|
104
|
+
}
|
|
105
|
+
// Any remaining
|
|
106
|
+
for (const [mod, names] of this.groups) {
|
|
107
|
+
if (ORDER.includes(mod)) continue;
|
|
108
|
+
const sorted = [...names].sort().join(', ');
|
|
109
|
+
lines.push(`from ${mod} import ${sorted}`);
|
|
110
|
+
}
|
|
111
|
+
return lines;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function scanTypeImports(type: ContractTypeNode, imports: ImportTracker): void {
|
|
116
|
+
switch (type.kind) {
|
|
117
|
+
case 'scalar':
|
|
118
|
+
switch (type.name) {
|
|
119
|
+
case 'date':
|
|
120
|
+
imports.add('datetime', 'date');
|
|
121
|
+
break;
|
|
122
|
+
case 'time':
|
|
123
|
+
imports.add('datetime', 'time');
|
|
124
|
+
break;
|
|
125
|
+
case 'datetime':
|
|
126
|
+
imports.add('datetime', 'datetime');
|
|
127
|
+
break;
|
|
128
|
+
case 'duration':
|
|
129
|
+
imports.add('datetime', 'timedelta');
|
|
130
|
+
break;
|
|
131
|
+
case 'uuid':
|
|
132
|
+
imports.add('uuid', 'UUID');
|
|
133
|
+
break;
|
|
134
|
+
case 'unknown':
|
|
135
|
+
case 'json':
|
|
136
|
+
case 'object':
|
|
137
|
+
imports.add('typing', 'Any');
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
break;
|
|
141
|
+
case 'enum':
|
|
142
|
+
imports.add('typing', 'Literal');
|
|
143
|
+
break;
|
|
144
|
+
case 'union':
|
|
145
|
+
type.members.forEach(m => scanTypeImports(m, imports));
|
|
146
|
+
break;
|
|
147
|
+
case 'discriminatedUnion':
|
|
148
|
+
imports.add('typing', 'Annotated');
|
|
149
|
+
imports.add('pydantic', 'Field');
|
|
150
|
+
type.members.forEach(m => scanTypeImports(m, imports));
|
|
151
|
+
break;
|
|
152
|
+
case 'intersection':
|
|
153
|
+
imports.add('typing', 'Any');
|
|
154
|
+
break;
|
|
155
|
+
case 'array':
|
|
156
|
+
scanTypeImports(type.item, imports);
|
|
157
|
+
break;
|
|
158
|
+
case 'tuple':
|
|
159
|
+
type.items.forEach(t => scanTypeImports(t, imports));
|
|
160
|
+
break;
|
|
161
|
+
case 'record':
|
|
162
|
+
scanTypeImports(type.key, imports);
|
|
163
|
+
scanTypeImports(type.value, imports);
|
|
164
|
+
break;
|
|
165
|
+
case 'lazy':
|
|
166
|
+
scanTypeImports(type.inner, imports);
|
|
167
|
+
break;
|
|
168
|
+
case 'inlineObject':
|
|
169
|
+
imports.add('typing', 'Any');
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ─── Type rendering ───────────────────────────────────────────────────────
|
|
175
|
+
|
|
176
|
+
export function renderPyType(type: ContractTypeNode, modelsWithInput?: Set<string>, forInput = false): string {
|
|
177
|
+
switch (type.kind) {
|
|
178
|
+
case 'scalar':
|
|
179
|
+
return renderScalar(type.name);
|
|
180
|
+
case 'enum':
|
|
181
|
+
return `Literal[${type.values.map(v => JSON.stringify(v)).join(', ')}]`;
|
|
182
|
+
case 'literal':
|
|
183
|
+
return typeof type.value === 'string' ? JSON.stringify(type.value) : String(type.value);
|
|
184
|
+
case 'array':
|
|
185
|
+
return `list[${renderPyType(type.item, modelsWithInput, forInput)}]`;
|
|
186
|
+
case 'tuple':
|
|
187
|
+
if (type.items.length === 0) return 'tuple[()]';
|
|
188
|
+
return `tuple[${type.items.map(t => renderPyType(t, modelsWithInput, forInput)).join(', ')}]`;
|
|
189
|
+
case 'record':
|
|
190
|
+
return `dict[${renderPyType(type.key, modelsWithInput, forInput)}, ${renderPyType(type.value, modelsWithInput, forInput)}]`;
|
|
191
|
+
case 'union':
|
|
192
|
+
return type.members.map(m => renderPyType(m, modelsWithInput, forInput)).join(' | ');
|
|
193
|
+
case 'discriminatedUnion': {
|
|
194
|
+
const inner = type.members.map(m => renderPyType(m, modelsWithInput, forInput)).join(' | ');
|
|
195
|
+
return `Annotated[${inner}, Field(discriminator=${JSON.stringify(type.discriminator)})]`;
|
|
196
|
+
}
|
|
197
|
+
case 'intersection':
|
|
198
|
+
return 'dict[str, Any]';
|
|
199
|
+
case 'ref': {
|
|
200
|
+
if (forInput && modelsWithInput?.has(type.name)) {
|
|
201
|
+
return `${type.name}Input`;
|
|
202
|
+
}
|
|
203
|
+
return type.name;
|
|
204
|
+
}
|
|
205
|
+
case 'inlineObject':
|
|
206
|
+
return 'dict[str, Any]';
|
|
207
|
+
case 'lazy':
|
|
208
|
+
return renderPyType(type.inner, modelsWithInput, forInput);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function renderScalar(name: string): string {
|
|
213
|
+
switch (name) {
|
|
214
|
+
case 'string':
|
|
215
|
+
case 'email':
|
|
216
|
+
case 'url':
|
|
217
|
+
return 'str';
|
|
218
|
+
case 'number':
|
|
219
|
+
return 'float';
|
|
220
|
+
case 'int':
|
|
221
|
+
return 'int';
|
|
222
|
+
case 'bigint':
|
|
223
|
+
return 'int';
|
|
224
|
+
case 'boolean':
|
|
225
|
+
return 'bool';
|
|
226
|
+
case 'date':
|
|
227
|
+
return 'date';
|
|
228
|
+
case 'time':
|
|
229
|
+
return 'time';
|
|
230
|
+
case 'datetime':
|
|
231
|
+
return 'datetime';
|
|
232
|
+
case 'duration':
|
|
233
|
+
return 'timedelta';
|
|
234
|
+
case 'uuid':
|
|
235
|
+
return 'UUID';
|
|
236
|
+
case 'null':
|
|
237
|
+
return 'None';
|
|
238
|
+
case 'binary':
|
|
239
|
+
return 'bytes';
|
|
240
|
+
case 'unknown':
|
|
241
|
+
case 'json':
|
|
242
|
+
case 'object':
|
|
243
|
+
return 'Any';
|
|
244
|
+
default:
|
|
245
|
+
return 'Any';
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// ─── Field name conversion ────────────────────────────────────────────────
|
|
250
|
+
|
|
251
|
+
/** Convert a field name to a valid Python identifier in snake_case. */
|
|
252
|
+
export function toPythonFieldName(name: string): string {
|
|
253
|
+
// Replace hyphens and non-alphanumeric chars (except underscore) with underscore
|
|
254
|
+
let result = name.replace(/[^a-zA-Z0-9_]/g, '_');
|
|
255
|
+
// camelCase → snake_case
|
|
256
|
+
result = result.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
|
|
257
|
+
// Collapse multiple underscores
|
|
258
|
+
result = result.replace(/_+/g, '_').replace(/^_|_$/g, '');
|
|
259
|
+
// Prefix if starts with digit
|
|
260
|
+
if (/^\d/.test(result)) result = 'f_' + result;
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ─── Model generation ─────────────────────────────────────────────────────
|
|
265
|
+
|
|
266
|
+
function generateModel(model: ModelNode, allModelsWithInput: Set<string>, imports: ImportTracker): string[] {
|
|
267
|
+
if (model.type) {
|
|
268
|
+
return generateTypeAlias(model, allModelsWithInput, imports);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const needsInputSplit = model.fields.some(f => f.visibility !== 'normal') || allModelsWithInput.has(model.name);
|
|
272
|
+
|
|
273
|
+
if (needsInputSplit) {
|
|
274
|
+
return generateSplitModel(model, allModelsWithInput, imports);
|
|
275
|
+
}
|
|
276
|
+
return generateSimpleModel(model, allModelsWithInput, imports);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function generateTypeAlias(model: ModelNode, allModelsWithInput: Set<string>, _: ImportTracker): string[] {
|
|
280
|
+
const lines: string[] = [];
|
|
281
|
+
if (model.description) lines.push(`# ${model.description}`);
|
|
282
|
+
if (model.deprecated) lines.push('# @deprecated');
|
|
283
|
+
lines.push(`${model.name} = ${renderPyType(model.type!, allModelsWithInput)}`);
|
|
284
|
+
if (allModelsWithInput.has(model.name)) {
|
|
285
|
+
lines.push(`${model.name}Input = ${renderPyType(model.type!, allModelsWithInput, true)}`);
|
|
286
|
+
}
|
|
287
|
+
return lines;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function generateSimpleModel(model: ModelNode, allModelsWithInput: Set<string>, imports: ImportTracker): string[] {
|
|
291
|
+
const lines: string[] = [];
|
|
292
|
+
if (model.description) lines.push(`# ${model.description}`);
|
|
293
|
+
if (model.deprecated) lines.push('# @deprecated');
|
|
294
|
+
|
|
295
|
+
const baseList = model.bases && model.bases.length > 0 ? model.bases.join(', ') : 'BaseModel';
|
|
296
|
+
lines.push(`class ${model.name}(${baseList}):`);
|
|
297
|
+
|
|
298
|
+
const fieldLines = renderFields(model.fields, allModelsWithInput, imports, false);
|
|
299
|
+
const needsConfig = model.fields.some(f => toPythonFieldName(f.name) !== f.name);
|
|
300
|
+
if (needsConfig) {
|
|
301
|
+
imports.add('pydantic', 'ConfigDict');
|
|
302
|
+
lines.push(` model_config = ConfigDict(populate_by_name=True)`);
|
|
303
|
+
lines.push('');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (fieldLines.length === 0) {
|
|
307
|
+
lines.push(' pass');
|
|
308
|
+
} else {
|
|
309
|
+
lines.push(...fieldLines);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return lines;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function generateSplitModel(model: ModelNode, allModelsWithInput: Set<string>, imports: ImportTracker): string[] {
|
|
316
|
+
const lines: string[] = [];
|
|
317
|
+
|
|
318
|
+
// Read model — omit writeonly fields
|
|
319
|
+
const readFields = model.fields.filter(f => f.visibility !== 'writeonly');
|
|
320
|
+
if (model.description) lines.push(`# ${model.description}`);
|
|
321
|
+
if (model.deprecated) lines.push('# @deprecated');
|
|
322
|
+
|
|
323
|
+
const readBaseList = model.bases && model.bases.length > 0 ? model.bases.join(', ') : 'BaseModel';
|
|
324
|
+
lines.push(`class ${model.name}(${readBaseList}):`);
|
|
325
|
+
const readNeedsConfig = readFields.some(f => toPythonFieldName(f.name) !== f.name);
|
|
326
|
+
if (readNeedsConfig) {
|
|
327
|
+
imports.add('pydantic', 'ConfigDict');
|
|
328
|
+
lines.push(` model_config = ConfigDict(populate_by_name=True)`);
|
|
329
|
+
lines.push('');
|
|
330
|
+
}
|
|
331
|
+
const readFieldLines = renderFields(readFields, allModelsWithInput, imports, false);
|
|
332
|
+
if (readFieldLines.length === 0) {
|
|
333
|
+
lines.push(' pass');
|
|
334
|
+
} else {
|
|
335
|
+
lines.push(...readFieldLines);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
lines.push('');
|
|
339
|
+
|
|
340
|
+
// Input model — omit readonly fields
|
|
341
|
+
const writeFields = model.fields.filter(f => f.visibility !== 'readonly');
|
|
342
|
+
const inputBaseList =
|
|
343
|
+
model.bases && model.bases.length > 0 ? model.bases.map(b => (allModelsWithInput.has(b) ? `${b}Input` : b)).join(', ') : 'BaseModel';
|
|
344
|
+
lines.push(`class ${model.name}Input(${inputBaseList}):`);
|
|
345
|
+
const writeNeedsConfig = writeFields.some(f => toPythonFieldName(f.name) !== f.name);
|
|
346
|
+
if (writeNeedsConfig) {
|
|
347
|
+
imports.add('pydantic', 'ConfigDict');
|
|
348
|
+
lines.push(` model_config = ConfigDict(populate_by_name=True)`);
|
|
349
|
+
lines.push('');
|
|
350
|
+
}
|
|
351
|
+
const writeFieldLines = renderFields(writeFields, allModelsWithInput, imports, true);
|
|
352
|
+
if (writeFieldLines.length === 0) {
|
|
353
|
+
lines.push(' pass');
|
|
354
|
+
} else {
|
|
355
|
+
lines.push(...writeFieldLines);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return lines;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function renderFields(fields: FieldNode[], allModelsWithInput: Set<string>, imports: ImportTracker, forInput: boolean): string[] {
|
|
362
|
+
const lines: string[] = [];
|
|
363
|
+
for (const f of fields) {
|
|
364
|
+
lines.push(...renderField(f, allModelsWithInput, imports, forInput));
|
|
365
|
+
}
|
|
366
|
+
return lines;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function renderField(field: FieldNode, allModelsWithInput: Set<string>, imports: ImportTracker, forInput: boolean): string[] {
|
|
370
|
+
const lines: string[] = [];
|
|
371
|
+
const pyName = toPythonFieldName(field.name);
|
|
372
|
+
const needsAlias = pyName !== field.name;
|
|
373
|
+
|
|
374
|
+
let typeStr = renderPyType(field.type, allModelsWithInput, forInput);
|
|
375
|
+
if (field.nullable) typeStr = `${typeStr} | None`;
|
|
376
|
+
|
|
377
|
+
const isOptional = field.optional || field.default !== undefined;
|
|
378
|
+
|
|
379
|
+
const fieldAnnotations: string[] = [];
|
|
380
|
+
if (needsAlias) {
|
|
381
|
+
imports.add('pydantic', 'Field');
|
|
382
|
+
fieldAnnotations.push(`alias=${JSON.stringify(field.name)}`);
|
|
383
|
+
}
|
|
384
|
+
if (field.default !== undefined) {
|
|
385
|
+
const def = typeof field.default === 'string' ? JSON.stringify(field.default) : String(field.default);
|
|
386
|
+
fieldAnnotations.push(`default=${def}`);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (field.deprecated) lines.push(` # @deprecated`);
|
|
390
|
+
if (field.description) lines.push(` # ${field.description}`);
|
|
391
|
+
|
|
392
|
+
let rhs: string;
|
|
393
|
+
if (fieldAnnotations.length > 0) {
|
|
394
|
+
imports.add('pydantic', 'Field');
|
|
395
|
+
rhs = `Field(${fieldAnnotations.join(', ')})`;
|
|
396
|
+
} else if (isOptional) {
|
|
397
|
+
rhs = 'None';
|
|
398
|
+
} else {
|
|
399
|
+
rhs = '';
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const optSuffix = isOptional && !field.nullable ? ` | None` : '';
|
|
403
|
+
const fullType = typeStr + optSuffix;
|
|
404
|
+
|
|
405
|
+
if (rhs) {
|
|
406
|
+
lines.push(` ${pyName}: ${fullType} = ${rhs}`);
|
|
407
|
+
} else {
|
|
408
|
+
lines.push(` ${pyName}: ${fullType}`);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
return lines;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// ─── Module name helpers ──────────────────────────────────────────────────
|
|
415
|
+
|
|
416
|
+
/** Derive a Python module name from a .ck file path, e.g. "ledger.categories.ck" → "_models_ledger_categories" */
|
|
417
|
+
export function deriveModelsModuleName(file: string): string {
|
|
418
|
+
const base =
|
|
419
|
+
file
|
|
420
|
+
.split('/')
|
|
421
|
+
.pop()
|
|
422
|
+
?.replace(/\.(op\.)?ck$/, '') ?? 'models';
|
|
423
|
+
const clean = base.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
|
|
424
|
+
return `_models_${clean}`;
|
|
425
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { resolve, join } from 'node:path';
|
|
2
|
+
import type { ContractKitPlugin } from '@contractkit/core';
|
|
3
|
+
import { generatePydanticModels, deriveModelsModuleName } from './codegen-models.js';
|
|
4
|
+
import {
|
|
5
|
+
generatePythonClient,
|
|
6
|
+
deriveClientClassName,
|
|
7
|
+
deriveClientModuleName,
|
|
8
|
+
deriveClientPropertyName,
|
|
9
|
+
hasPublicOperations,
|
|
10
|
+
BASE_CLIENT_PY,
|
|
11
|
+
} from './codegen-client.js';
|
|
12
|
+
|
|
13
|
+
export interface PythonSdkPluginConfig {
|
|
14
|
+
/** Output directory relative to rootDir (default: "python-sdk") */
|
|
15
|
+
baseDir?: string;
|
|
16
|
+
/** Python package name used in the aggregator class name (default: "Sdk") */
|
|
17
|
+
packageName?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Whether to emit client methods for operations marked `internal`. Defaults to `false` —
|
|
20
|
+
* internal ops are omitted so consumers don't pick them up. Set to `true` for an
|
|
21
|
+
* internal-use SDK that should expose them.
|
|
22
|
+
*/
|
|
23
|
+
includeInternal?: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ─── Default export: loaded via plugins array, reads config from ctx.options ─
|
|
27
|
+
|
|
28
|
+
const plugin: ContractKitPlugin = {
|
|
29
|
+
name: 'python-sdk',
|
|
30
|
+
cacheKey: 'python-sdk',
|
|
31
|
+
async generateTargets(inputs, ctx) {
|
|
32
|
+
const config = ctx.options as PythonSdkPluginConfig;
|
|
33
|
+
return createPythonSdkPlugin(config, ctx.rootDir).generateTargets!(inputs, ctx);
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export default plugin;
|
|
38
|
+
|
|
39
|
+
// ─── Factory: for programmatic use with explicit config ────────────────────
|
|
40
|
+
|
|
41
|
+
export function createPythonSdkPlugin(config: PythonSdkPluginConfig, rootDir: string): ContractKitPlugin {
|
|
42
|
+
return {
|
|
43
|
+
name: 'python-sdk',
|
|
44
|
+
cacheKey: `python-sdk:${JSON.stringify(config)}`,
|
|
45
|
+
async generateTargets({ contractRoots, opRoots, modelsWithInput: _modelsWithInput }, ctx) {
|
|
46
|
+
const modelsWithInput = _modelsWithInput as Set<string>;
|
|
47
|
+
const outDir = resolve(rootDir, config.baseDir ?? 'python-sdk');
|
|
48
|
+
|
|
49
|
+
// ── Build model module path map ──
|
|
50
|
+
// model name → importable Python module string, e.g. "._models_payment"
|
|
51
|
+
const modelModulePaths = new Map<string, string>();
|
|
52
|
+
const contractEntries: { moduleName: string; outPath: string; root: (typeof contractRoots)[number] }[] = [];
|
|
53
|
+
|
|
54
|
+
for (const contractRoot of contractRoots) {
|
|
55
|
+
const moduleName = deriveModelsModuleName(contractRoot.file);
|
|
56
|
+
const outPath = join(outDir, `${moduleName}.py`);
|
|
57
|
+
contractEntries.push({ moduleName, outPath, root: contractRoot });
|
|
58
|
+
|
|
59
|
+
for (const model of contractRoot.models) {
|
|
60
|
+
modelModulePaths.set(model.name, `.${moduleName}`);
|
|
61
|
+
if (modelsWithInput.has(model.name)) {
|
|
62
|
+
modelModulePaths.set(`${model.name}Input`, `.${moduleName}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ── Emit model files ──
|
|
68
|
+
for (const { moduleName, outPath, root } of contractEntries) {
|
|
69
|
+
const content = generatePydanticModels(root, {
|
|
70
|
+
modelModulePaths,
|
|
71
|
+
currentModule: `.${moduleName}`,
|
|
72
|
+
modelsWithInput,
|
|
73
|
+
});
|
|
74
|
+
ctx.emitFile(outPath, content);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ── Emit client files ──
|
|
78
|
+
const clientInfos: { moduleName: string; className: string; propertyName: string }[] = [];
|
|
79
|
+
for (const opRoot of opRoots) {
|
|
80
|
+
if (!hasPublicOperations(opRoot, config.includeInternal)) continue;
|
|
81
|
+
const moduleName = deriveClientModuleName(opRoot.file);
|
|
82
|
+
const outPath = join(outDir, `${moduleName}.py`);
|
|
83
|
+
clientInfos.push({
|
|
84
|
+
moduleName,
|
|
85
|
+
className: deriveClientClassName(opRoot.file),
|
|
86
|
+
propertyName: deriveClientPropertyName(opRoot.file),
|
|
87
|
+
});
|
|
88
|
+
ctx.emitFile(
|
|
89
|
+
outPath,
|
|
90
|
+
generatePythonClient(opRoot, {
|
|
91
|
+
modelModulePaths,
|
|
92
|
+
currentModule: `.${moduleName}`,
|
|
93
|
+
modelsWithInput,
|
|
94
|
+
includeInternal: config.includeInternal,
|
|
95
|
+
}),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── Emit shared _base_client.py ──
|
|
100
|
+
ctx.emitFile(join(outDir, '_base_client.py'), BASE_CLIENT_PY);
|
|
101
|
+
|
|
102
|
+
// ── Emit requirements.txt ──
|
|
103
|
+
ctx.emitFile(join(outDir, 'requirements.txt'), 'httpx\npydantic>=2.0\n');
|
|
104
|
+
|
|
105
|
+
// ── Emit __init__.py aggregator ──
|
|
106
|
+
const sdkClassName = config.packageName
|
|
107
|
+
? config.packageName
|
|
108
|
+
.split(/[-._\s]+/)
|
|
109
|
+
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
|
|
110
|
+
.join('') + 'Sdk'
|
|
111
|
+
: 'Sdk';
|
|
112
|
+
|
|
113
|
+
const initLines: string[] = [
|
|
114
|
+
'# Auto-generated by contractkit-plugin-python-sdk. Do not edit manually.',
|
|
115
|
+
'from ._base_client import BaseClient, SdkError',
|
|
116
|
+
];
|
|
117
|
+
for (const c of clientInfos) {
|
|
118
|
+
initLines.push(`from .${c.moduleName} import ${c.className}`);
|
|
119
|
+
}
|
|
120
|
+
initLines.push('');
|
|
121
|
+
initLines.push('');
|
|
122
|
+
if (clientInfos.length > 0) {
|
|
123
|
+
initLines.push(`class ${sdkClassName}(BaseClient):`);
|
|
124
|
+
initLines.push(` def __init__(self, base_url: str, headers: dict[str, str] | None = None):`);
|
|
125
|
+
initLines.push(` super().__init__(base_url, headers)`);
|
|
126
|
+
for (const c of clientInfos) {
|
|
127
|
+
initLines.push(` self.${c.propertyName} = ${c.className}(base_url, headers)`);
|
|
128
|
+
}
|
|
129
|
+
initLines.push('');
|
|
130
|
+
} else {
|
|
131
|
+
initLines.push(`class ${sdkClassName}(BaseClient):`);
|
|
132
|
+
initLines.push(` pass`);
|
|
133
|
+
initLines.push('');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const allNames = ['BaseClient', 'SdkError', sdkClassName, ...clientInfos.map(c => c.className)];
|
|
137
|
+
initLines.push(`__all__ = [${allNames.map(n => JSON.stringify(n)).join(', ')}]`);
|
|
138
|
+
initLines.push('');
|
|
139
|
+
|
|
140
|
+
ctx.emitFile(join(outDir, '__init__.py'), initLines.join('\n'));
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|