All files / src codegen-models.ts

82.04% Statements 201/245
75.97% Branches 117/154
79.31% Functions 23/29
85.32% Lines 186/218

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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