All files / src type-utils.ts

12.96% Statements 52/401
9.23% Branches 18/195
12.28% Functions 7/57
14.19% Lines 45/317

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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605                                                                9x 9x   9x 1x     9x 23x 21x 21x 21x 1x 1x   20x 18x     9x 18x 18x 18x 30x 30x   29x 29x     18x 9x 11x     19x 18x     9x 9x 1x 5x   2x 2x 2x 5x 6x 6x   6x 6x       2x     1x       9x 9x         9x 20x 9x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import type { ContractTypeNode, ContractRootNode, FieldNode, ModelNode, OpRootNode, ParamSource } from './ast.js';
import { resolveModifiers } from './ast.js';
 
// ─── Effective-field resolution ────────────────────────────────────────────
 
/** Result of `resolveEffectiveFields` — the flattened field set plus any refs that
 * couldn't be resolved against the supplied model index. */
export interface EffectiveFields {
    fields: FieldNode[];
    /** Model names that the resolution touched but couldn't find in the index. */
    unresolved: string[];
}
 
/**
 * Flattens a type or model name into an effective field list, following all forms of
 * composition recognized by the contractkit language:
 *
 * - `contract Foo: { a: int }` → own fields
 * - `contract Foo: A & B & { c: int }` → bases (`A`, `B`) contribute, own fields appended
 * - `Foo: A & B` (no `{ ... }`) → type alias to intersection; both members contribute
 * - Alias chains (`Foo: SomeOther`), nested intersections, inline objects, and `lazy` wrappers
 * - Multi-base inheritance with diamond dedup (later declarations override earlier)
 * - Cycle protection (`A: B`, `B: A` → resolved once, no infinite loop)
 *
 * Shapes that can't contribute named fields (scalars, unions, enums, arrays, records,
 * tuples) yield an empty field list — they're meant to be rendered as their own thing,
 * not flattened. Unresolved refs are captured for the caller to surface as a diagnostic.
 */
export function resolveEffectiveFields(
    target: string | ContractTypeNode,
    modelIndex: ReadonlyMap<string, ModelNode>,
): EffectiveFields {
    const unresolved: string[] = [];
    const visited = new Set<string>();
 
    const recordUnresolved = (name: string): void => {
        Eif (!unresolved.includes(name)) unresolved.push(name);
    };
 
    const fromName = (name: string): FieldNode[] => {
        if (visited.has(name)) return [];
        visited.add(name);
        const model = modelIndex.get(name);
        if (!model) {
            recordUnresolved(name);
            return [];
        }
        if (model.type) return fromType(model.type);
        return collectModelFields(model);
    };
 
    const collectModelFields = (model: ModelNode): FieldNode[] => {
        const merged: FieldNode[] = [];
        const index = new Map<string, number>();
        const push = (f: FieldNode): void => {
            const existing = index.get(f.name);
            if (existing !== undefined) merged[existing] = f;
            else {
                index.set(f.name, merged.length);
                merged.push(f);
            }
        };
        if (model.bases) {
            for (const base of model.bases) {
                for (const f of fromName(base)) push(f);
            }
        }
        for (const f of model.fields) push(f);
        return merged;
    };
 
    const fromType = (type: ContractTypeNode): FieldNode[] => {
        switch (type.kind) {
            case 'inlineObject': return type.fields;
            case 'ref': return fromName(type.name);
            case 'intersection': {
                const merged: FieldNode[] = [];
                const index = new Map<string, number>();
                for (const member of type.members) {
                    for (const f of fromType(member)) {
                        const existing = index.get(f.name);
                        Iif (existing !== undefined) merged[existing] = f;
                        else {
                            index.set(f.name, merged.length);
                            merged.push(f);
                        }
                    }
                }
                return merged;
            }
            case 'lazy': return fromType(type.inner);
            default: return [];
        }
    };
 
    const fields = typeof target === 'string' ? fromName(target) : fromType(target);
    return { fields, unresolved };
}
 
/** Builds a lookup map suitable for {@link resolveEffectiveFields}. */
export function buildModelIndex(models: readonly ModelNode[]): Map<string, ModelNode> {
    const out = new Map<string, ModelNode>();
    for (const m of models) out.set(m.name, m);
    return out;
}
 
// ─── Type collection ──────────────────────────────────────────────────────
 
/**
 * Returns the set of type names directly referenced by public (non-internal)
 * operations in the root. Does not include transitive dependencies — callers
 * should expand these through the contract model graph if needed.
 */
export function collectPublicTypeNames(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): Set<string> {
    return new Set(collectTypes(root, modelsWithInput, modelsWithOutput));
}
 
function collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {
    const types = new Set<string>();
    for (const route of root.routes) {
        const publicOps = route.operations.filter(op => !resolveModifiers(route, op).includes('internal'));
        if (publicOps.length === 0) continue;
        // Only collect path-param types if there are public ops on this route
        collectParamSourceRefs(route.params, types);
        collectParamSourceInputRefs(route.params, types, modelsWithInput);
        for (const op of publicOps) {
            if (op.request) {
                for (const body of op.request.bodies) {
                    collectTypeNodeRefs(body.bodyType, types);
                    collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);
                }
            }
            for (const resp of op.responses) {
                if (resp.bodyType) {
                    collectTypeNodeRefs(resp.bodyType, types);
                    collectOutputTypeNodeRefs(resp.bodyType, types, modelsWithOutput);
                }
            }
            collectParamSourceRefs(op.query, types);
            collectParamSourceInputRefs(op.query, types, modelsWithInput);
            collectParamSourceRefs(op.headers, types);
            collectParamSourceInputRefs(op.headers, types, modelsWithInput);
        }
    }
    return [...types].sort();
}
 
/** Collect Output variant refs for response-side ContractTypeNode types. */
function collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {
    if (!modelsWithOutput) return;
    switch (type.kind) {
        case 'ref':
            if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);
            break;
        case 'array':
            collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);
            break;
        case 'intersection':
        case 'union':
        case 'discriminatedUnion':
            type.members.forEach(m => collectOutputTypeNodeRefs(m, out, modelsWithOutput));
            break;
        case 'inlineObject':
            type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));
            break;
        case 'lazy':
            collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);
            break;
    }
}
 
/** Collect Input variant refs for request-side ParamSource types. */
function collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {
    if (!source || !modelsWithInput) return;
    if (source.kind === 'ref') {
        if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);
    } else if (source.kind === 'params') {
        for (const param of source.nodes) {
            collectInputTypeNodeRefs(param.type, out, modelsWithInput);
        }
    } else {
        collectInputTypeNodeRefs(source.node, out, modelsWithInput);
    }
}
 
/** Collect Input variant refs for request-side ContractTypeNode types. */
function collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {
    if (!modelsWithInput) return;
    switch (type.kind) {
        case 'ref':
            if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);
            break;
        case 'array':
            collectInputTypeNodeRefs(type.item, out, modelsWithInput);
            break;
        case 'intersection':
        case 'union':
        case 'discriminatedUnion':
            type.members.forEach(m => collectInputTypeNodeRefs(m, out, modelsWithInput));
            break;
        case 'inlineObject':
            type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));
            break;
        case 'lazy':
            collectInputTypeNodeRefs(type.inner, out, modelsWithInput);
            break;
    }
}
 
function collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {
    if (!source) return;
    if (source.kind === 'ref') {
        if (/^[A-Z]/.test(source.name)) out.add(source.name);
    } else if (source.kind === 'params') {
        for (const param of source.nodes) {
            collectTypeNodeRefs(param.type, out);
        }
    } else {
        collectTypeNodeRefs(source.node, out);
    }
}
 
function collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {
    switch (type.kind) {
        case 'ref':
            if (/^[A-Z]/.test(type.name)) out.add(type.name);
            break;
        case 'array':
            collectTypeNodeRefs(type.item, out);
            break;
        case 'tuple':
            type.items.forEach(t => collectTypeNodeRefs(t, out));
            break;
        case 'record':
            collectTypeNodeRefs(type.key, out);
            collectTypeNodeRefs(type.value, out);
            break;
        case 'union':
            type.members.forEach(t => collectTypeNodeRefs(t, out));
            break;
        case 'discriminatedUnion':
            type.members.forEach(t => collectTypeNodeRefs(t, out));
            break;
        case 'intersection':
            type.members.forEach(t => collectTypeNodeRefs(t, out));
            break;
        case 'lazy':
            collectTypeNodeRefs(type.inner, out);
            break;
        case 'inlineObject':
            type.fields.forEach(f => collectTypeNodeRefs(f.type, out));
            break;
    }
}
 
/**
 * Walk the model graph from a set of seed types and return every transitively
 * referenced model name. Bases are followed; aliased model `type` and field types
 * are queued. Useful for cache fingerprinting — gives the slice of the model
 * universe a particular op or contract root depends on.
 *
 * Models referenced by name but not present in `modelMap` are still included in
 * the result (so a fingerprint that mentions them will detect when they appear
 * later), but no further traversal happens through them.
 */
export function collectTransitiveModelRefs(seedTypes: ContractTypeNode[], modelMap: Map<string, ModelNode>): Set<string> {
    const found = new Set<string>();
    const queue: ContractTypeNode[] = [...seedTypes];
    while (queue.length > 0) {
        const t = queue.pop()!;
        const refs = new Set<string>();
        collectTypeRefs(t, refs);
        for (const ref of refs) {
            if (found.has(ref)) continue;
            found.add(ref);
            const m = modelMap.get(ref);
            if (!m) continue;
            if (m.type) queue.push(m.type);
            for (const f of m.fields) queue.push(f.type);
            if (m.bases) {
                for (const base of m.bases) {
                    if (found.has(base)) continue;
                    found.add(base);
                    const bm = modelMap.get(base);
                    if (!bm) continue;
                    if (bm.type) queue.push(bm.type);
                    for (const f of bm.fields) queue.push(f.type);
                }
            }
        }
    }
    return found;
}
 
export function collectTypeRefs(type: ContractTypeNode, out: Set<string>): void {
    switch (type.kind) {
        case 'ref':
            out.add(type.name);
            break;
        case 'array':
            collectTypeRefs(type.item, out);
            break;
        case 'tuple':
            type.items.forEach(t => collectTypeRefs(t, out));
            break;
        case 'record':
            collectTypeRefs(type.key, out);
            collectTypeRefs(type.value, out);
            break;
        case 'union':
            type.members.forEach(t => collectTypeRefs(t, out));
            break;
        case 'discriminatedUnion':
            type.members.forEach(t => collectTypeRefs(t, out));
            break;
        case 'intersection':
            type.members.forEach(t => collectTypeRefs(t, out));
            break;
        case 'lazy':
            collectTypeRefs(type.inner, out);
            break;
        case 'inlineObject':
            type.fields.forEach(f => collectTypeRefs(f.type, out));
            break;
    }
}
 
// ─── Contract model utilities ─────────────────────────────────────────────
 
/**
 * Compute which models need Input variants, including transitive dependencies.
 * A model needs an Input variant if it has visibility-modified fields, OR if
 * any of its field types (recursively) reference a model that has an Input variant.
 */
export function computeModelsWithInput(models: ModelNode[], externalModelsWithInput: Set<string> = new Set()): Set<string> {
    const result = new Set<string>();
 
    // Initial pass: direct visibility modifiers
    for (const model of models) {
        if (model.fields.some(f => f.visibility !== 'normal')) {
            result.add(model.name);
        }
    }
 
    // Transitive closure
    let changed = true;
    while (changed) {
        changed = false;
        for (const model of models) {
            if (result.has(model.name)) continue;
            const refs = new Set<string>();
            for (const field of model.fields) {
                collectTypeRefs(field.type, refs);
            }
            if (model.bases) for (const b of model.bases) refs.add(b);
            if (model.type) collectTypeRefs(model.type, refs);
            for (const ref of refs) {
                if (result.has(ref) || externalModelsWithInput.has(ref)) {
                    result.add(model.name);
                    changed = true;
                    break;
                }
            }
        }
    }
 
    return result;
}
 
/**
 * Compute which models need Output variants (post-transform wire shape),
 * including transitive dependencies. A model needs an Output variant if it
 * has `format(output=...)` set to a non-camel case, OR if any of its field
 * types (recursively) reference a model that has an Output variant.
 */
export function computeModelsWithOutput(models: ModelNode[], externalModelsWithOutput: Set<string> = new Set()): Set<string> {
    const result = new Set<string>();
 
    // Initial pass: direct outputCase transforms
    for (const model of models) {
        if (model.outputCase && model.outputCase !== 'camel') {
            result.add(model.name);
        }
    }
 
    // Transitive closure
    let changed = true;
    while (changed) {
        changed = false;
        for (const model of models) {
            if (result.has(model.name)) continue;
            const refs = new Set<string>();
            for (const field of model.fields) {
                collectTypeRefs(field.type, refs);
            }
            if (model.bases) for (const b of model.bases) refs.add(b);
            if (model.type) collectTypeRefs(model.type, refs);
            for (const ref of refs) {
                if (result.has(ref) || externalModelsWithOutput.has(ref)) {
                    result.add(model.name);
                    changed = true;
                    break;
                }
            }
        }
    }
 
    return result;
}
 
export function collectExternalRefs(root: ContractRootNode): string[] {
    const localNames = new Set(root.models.map(m => m.name));
    const refs = new Set<string>();
 
    for (const model of root.models) {
        if (model.bases) for (const b of model.bases) if (!localNames.has(b)) refs.add(b);
        if (model.type) collectTypeRefs(model.type, refs);
        for (const field of model.fields) {
            collectTypeRefs(field.type, refs);
        }
    }
 
    for (const name of localNames) refs.delete(name);
    return [...refs].sort();
}
 
/** Collect external Output variant refs needed for Output schema fields. */
export function collectExternalOutputRefs(root: ContractRootNode, modelsWithOutput: Set<string>): string[] {
    const localNames = new Set(root.models.map(m => m.name));
    const refs = new Set<string>();
 
    for (const model of root.models) {
        if (!modelsWithOutput.has(model.name)) continue;
        if (model.type) {
            collectOutputTypeRefsForExport(model.type, refs, modelsWithOutput);
            continue;
        }
        if (model.bases) {
            for (const base of model.bases) {
                if (modelsWithOutput.has(base) && !localNames.has(base)) refs.add(`${base}Output`);
            }
        }
        for (const field of model.fields) {
            collectOutputTypeRefsForExport(field.type, refs, modelsWithOutput);
        }
    }
 
    for (const name of localNames) {
        refs.delete(`${name}Output`);
    }
 
    return [...refs].sort();
}
 
function collectOutputTypeRefsForExport(type: ContractTypeNode, out: Set<string>, modelsWithOutput: Set<string>): void {
    switch (type.kind) {
        case 'ref':
            if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);
            break;
        case 'array':
            collectOutputTypeRefsForExport(type.item, out, modelsWithOutput);
            break;
        case 'tuple':
            type.items.forEach(i => collectOutputTypeRefsForExport(i, out, modelsWithOutput));
            break;
        case 'record':
            collectOutputTypeRefsForExport(type.key, out, modelsWithOutput);
            collectOutputTypeRefsForExport(type.value, out, modelsWithOutput);
            break;
        case 'union':
            type.members.forEach(m => collectOutputTypeRefsForExport(m, out, modelsWithOutput));
            break;
        case 'discriminatedUnion':
            type.members.forEach(m => collectOutputTypeRefsForExport(m, out, modelsWithOutput));
            break;
        case 'intersection':
            type.members.forEach(m => collectOutputTypeRefsForExport(m, out, modelsWithOutput));
            break;
        case 'lazy':
            collectOutputTypeRefsForExport(type.inner, out, modelsWithOutput);
            break;
        case 'inlineObject':
            type.fields.forEach(f => collectOutputTypeRefsForExport(f.type, out, modelsWithOutput));
            break;
    }
}
 
/** Collect external Input variant refs needed for Input schema fields. */
export function collectExternalInputRefs(root: ContractRootNode, modelsWithInput: Set<string>): string[] {
    const localNames = new Set(root.models.map(m => m.name));
    const refs = new Set<string>();
 
    for (const model of root.models) {
        if (!modelsWithInput.has(model.name)) continue;
        if (model.type) {
            collectInputTypeRefsForExport(model.type, refs, modelsWithInput);
            continue;
        }
        if (model.bases) {
            for (const base of model.bases) {
                if (modelsWithInput.has(base) && !localNames.has(base)) refs.add(`${base}Input`);
            }
        }
        const writeFields = model.fields.filter(f => f.visibility !== 'readonly');
        for (const field of writeFields) {
            collectInputTypeRefsForExport(field.type, refs, modelsWithInput);
        }
    }
 
    for (const name of localNames) {
        refs.delete(`${name}Input`);
    }
 
    return [...refs].sort();
}
 
function collectInputTypeRefsForExport(type: ContractTypeNode, out: Set<string>, modelsWithInput: Set<string>): void {
    switch (type.kind) {
        case 'ref':
            if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);
            break;
        case 'array':
            collectInputTypeRefsForExport(type.item, out, modelsWithInput);
            break;
        case 'tuple':
            type.items.forEach(i => collectInputTypeRefsForExport(i, out, modelsWithInput));
            break;
        case 'record':
            collectInputTypeRefsForExport(type.key, out, modelsWithInput);
            collectInputTypeRefsForExport(type.value, out, modelsWithInput);
            break;
        case 'union':
            type.members.forEach(m => collectInputTypeRefsForExport(m, out, modelsWithInput));
            break;
        case 'discriminatedUnion':
            type.members.forEach(m => collectInputTypeRefsForExport(m, out, modelsWithInput));
            break;
        case 'intersection':
            type.members.forEach(m => collectInputTypeRefsForExport(m, out, modelsWithInput));
            break;
        case 'lazy':
            collectInputTypeRefsForExport(type.inner, out, modelsWithInput);
            break;
        case 'inlineObject':
            type.fields.forEach(f => collectInputTypeRefsForExport(f.type, out, modelsWithInput));
            break;
    }
}
 
/**
 * Topologically sort models so dependencies are emitted before dependents.
 * Falls back to source order for cycles.
 */
export function topoSortModels(models: ModelNode[]): ModelNode[] {
    const localNames = new Set(models.map(m => m.name));
    const modelMap = new Map(models.map(m => [m.name, m]));
 
    const deps = new Map<string, Set<string>>();
    for (const model of models) {
        const refs = new Set<string>();
        if (model.bases) for (const b of model.bases) if (localNames.has(b)) refs.add(b);
        if (model.type) collectTypeRefs(model.type, refs);
        for (const field of model.fields) {
            collectTypeRefs(field.type, refs);
        }
        const localDeps = new Set<string>();
        for (const r of refs) {
            if (localNames.has(r) && r !== model.name) localDeps.add(r);
        }
        deps.set(model.name, localDeps);
    }
 
    const remaining = new Map<string, Set<string>>();
    for (const [name, d] of deps) {
        remaining.set(name, new Set(d));
    }
 
    const queue: string[] = [];
    for (const name of localNames) {
        if (remaining.get(name)!.size === 0) queue.push(name);
    }
 
    const sorted: ModelNode[] = [];
    while (queue.length > 0) {
        const name = queue.shift()!;
        sorted.push(modelMap.get(name)!);
        for (const [other, rem] of remaining) {
            if (rem.delete(name) && rem.size === 0) {
                queue.push(other);
            }
        }
    }
 
    for (const model of models) {
        if (!sorted.includes(model)) sorted.push(model);
    }
 
    return sorted;
}
 
/** Convert PascalCase to dot-separated lowercase: CounterpartyAccount → counterparty.account */
export function pascalToDotCase(name: string): string {
    return name.replace(/([a-z0-9])([A-Z])/g, '$1.$2').toLowerCase();
}