All files / src index.ts

58.17% Statements 185/318
47.22% Branches 68/144
63.04% Functions 29/46
62.78% Lines 167/266

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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786                                                                                                                                                                                                      1x   1x       1x     1x 1x               17x     17x                                     18x 18x   18x 18x   18x 18x 18x 18x   18x                   18x   18x 49x               18x 18x 3x   18x         3x 3x 3x 3x 3x       3x         16x 16x 16x 16x 16x 16x 16x 1x   16x 4x 4x           16x       1x 1x 1x           1x         19x 19x 2x 2x 2x       2x         19x         38x 38x     38x                     14x 14x 14x 14x 14x 14x 14x         14x 14x 14x 3x 3x 3x 3x 3x 3x 3x           14x 3x 3x 3x                   3x       3x           3x 3x           14x 13x 13x 13x                         13x     13x                                                   4x 4x 4x 4x     4x 4x   4x 4x 4x 5x 4x   4x 4x 4x     4x 4x                                 4x                                                                                             4x 4x   4x 4x 5x 5x 5x 5x 2x 2x 2x 3x 2x 2x 2x   1x         4x 3x 2x 2x 2x 2x                         2x     2x                                       4x 1x 1x 1x 1x                       1x     1x                                           4x   4x 4x 4x 4x 4x 4x             4x 2x 2x 2x     4x       1x 1x       4x   3x   2x                           2x                   4x           4x 4x 4x   4x 4x 4x 3x 3x 3x   4x         4x                                                                                                                                                                                                                                         18x                 18x                                                       18x    
import { resolve, join, relative, dirname, basename } from 'node:path';
import { existsSync, readFileSync, rmSync, readdirSync, rmdirSync } from 'node:fs';
import { generateContract } from './codegen-contract.js';
import { generateOp } from './codegen-operation.js';
import type {
    ContractKitPlugin,
    PluginContext,
    ContractRootNode,
    OpRootNode,
    ModelNode,
    IncrementalManifest,
    IncrementalUnit,
    IncrementalOutputFile,
} from '@contractkit/core';
import {
    runIncrementalCodegen,
    parseIncrementalManifest,
    emptyIncrementalManifest,
    hashFingerprint,
    collectTransitiveModelRefs,
    collectTypeRefs,
} from '@contractkit/core';
import {
    generateSdk,
    generateSdkOptions,
    generateSdkAggregator,
    deriveClientClassName,
    deriveClientPropertyName,
    deriveSubareaClientClassName,
    deriveSubareaPropertyName,
    getAreaSubarea,
    hasPublicOperations,
    type SdkClientInfo,
    type SdkAreaInfo,
} from './codegen-sdk.js';
import { generatePlainTypes } from './codegen-plain-types.js';
import {
    TEMPLATE_VAR_RE,
    resolveTemplate,
    commonDir,
    computeOpOutPath,
    computeContractOutPath,
    computeSdkOutPath,
    computeSdkTypeOutPath,
    generateBarrelFiles,
    computePubliclyReachableTypes,
} from './path-utils.js';
 
// ─── Sub-config interfaces ─────────────────────────────────────────────────
 
export interface ServerConfig {
    /** Directory (relative to rootDir) where server files are written. Default: rootDir. */
    baseDir?: string;
    /** When true, `output.types` emits Zod schema files (via `generateContract`). When false/omitted, emits plain TypeScript. */
    zod?: boolean;
    output?: {
        /** Path template for Koa router files. Supports {filename}, {dir}, {area}. */
        routes?: string;
        /** Path template for type/schema files. Supports {filename}, {dir}, {area}. */
        types?: string;
    };
    /** Import path template for service implementations. */
    servicePathTemplate?: string;
    /** Whether to emit handlers for `internal` operations. Default true. */
    includeInternal?: boolean;
}
 
export interface SdkConfig {
    baseDir?: string;
    name?: string;
    zod?: boolean;
    output?: {
        sdk?: string;
        types?: string;
        clients?: string;
    };
    includeInternal?: boolean;
}
 
export interface ZodConfig {
    baseDir?: string;
    output?: string;
}
 
export interface TypesConfig {
    baseDir?: string;
    output?: string;
}
 
export interface TypescriptPluginConfig {
    server?: ServerConfig;
    sdk?: SdkConfig;
    zod?: ZodConfig;
    types?: TypesConfig;
}
 
// ─── Caching constants ─────────────────────────────────────────────────────
 
/** Bumped when the codegen output shape changes in a way that should bust every per-file fingerprint. */
export const TYPESCRIPT_CODEGEN_VERSION = '1';
 
const MANIFEST_FILENAME = '.contractkit-typescript-manifest.json';
 
// ─── Plugin entry points ──────────────────────────────────────────────────
 
const plugin: ContractKitPlugin = {
    name: 'typescript',
    async generateTargets(inputs, ctx) {
        const config = ctx.options as TypescriptPluginConfig;
        await runTypescriptCodegen(inputs, ctx, config, ctx.rootDir);
    },
};
 
export default plugin;
 
/** Build a `@contractkit/plugin-typescript` instance with explicit configuration, for programmatic use. */
export function createTypescriptPlugin(config: TypescriptPluginConfig, rootDir: string): ContractKitPlugin {
    return {
        name: 'typescript',
        async generateTargets(inputs, ctx) {
            await runTypescriptCodegen(inputs, ctx, config, rootDir);
        },
    };
}
 
/**
 * Shared orchestration. Each sub-generator (server / sdk / zod / types) contributes a
 * set of cacheable units (per-file fingerprints) plus a set of always-regenerated global
 * files (aggregators, barrels, sdk-options). Units share a single manifest so the cache
 * survives cross-cutting reads — the manifest lives at `<rootDir>/.contractkit-typescript-manifest.json`.
 *
 * Honors `ctx.cacheEnabled` — `--force` bypasses the manifest entirely.
 */
async function runTypescriptCodegen(
    inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
    ctx: PluginContext,
    config: TypescriptPluginConfig,
    rootDir: string,
): Promise<void> {
    const manifestPath = resolve(rootDir, MANIFEST_FILENAME);
    const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);
 
    const units: IncrementalUnit[] = [];
    const globalFiles: IncrementalOutputFile[] = [];
 
    if (config.server) collectServerOutput(config.server, rootDir, inputs, units);
    if (config.sdk) collectSdkOutput(config.sdk, rootDir, inputs, units, globalFiles);
    Iif (config.zod) collectZodOutput(config.zod, rootDir, inputs, units);
    Iif (config.types) collectTypesOutput(config.types, rootDir, inputs, units);
 
    const result = runIncrementalCodegen({
        codegenVersion: TYPESCRIPT_CODEGEN_VERSION,
        manifestFilename: manifestPath,
        prevManifest,
        globalFiles,
        units,
        // Paths are absolute, so existsSync works directly.
        fileExists: existsSync,
    });
 
    deleteStalePaths(result.deletedPaths);
 
    for (const { relativePath, content } of result.filesToWrite) {
        ctx.emitFile(relativePath, content);
    }
}
 
// ─── Cross-file dependency analysis ────────────────────────────────────────
 
/** Build a quick lookup from model name → its definition. */
function buildModelMap(contractRoots: readonly ContractRootNode[]): Map<string, ModelNode> {
    const map = new Map<string, ModelNode>();
    for (const root of contractRoots) {
        for (const model of root.models) map.set(model.name, model);
    }
    return map;
}
 
/** Collect every model referenced by this contract root (own models' fields + bases). Used to slice cross-file fingerprint inputs to just what this file actually depends on. */
function collectContractRootRefs(root: ContractRootNode, modelMap: Map<string, ModelNode>): Set<string> {
    const seeds: Parameters<typeof collectTypeRefs>[0][] = [];
    for (const m of root.models) {
        Iif (m.type) seeds.push(m.type);
        for (const f of m.fields) seeds.push(f.type);
        Iif (m.bases) {
            for (const b of m.bases) seeds.push({ kind: 'ref', name: b } as Parameters<typeof collectTypeRefs>[0]);
        }
    }
    return collectTransitiveModelRefs(seeds, modelMap);
}
 
/** Collect every model referenced by an op root's routes/operations (transitive). */
function collectOpRootRefs(root: OpRootNode, modelMap: Map<string, ModelNode>): Set<string> {
    const seeds: Parameters<typeof collectTypeRefs>[0][] = [];
    for (const route of root.routes) {
        if (route.params) seeds.push(...paramSourceTypes(route.params));
        for (const op of route.operations) {
            Iif (op.query) seeds.push(...paramSourceTypes(op.query));
            Iif (op.headers) seeds.push(...paramSourceTypes(op.headers));
            if (op.request) {
                for (const body of op.request.bodies) seeds.push(body.bodyType);
            }
            for (const resp of op.responses) {
                if (resp.bodyType) seeds.push(resp.bodyType);
                Iif (resp.headers) {
                    for (const h of resp.headers) seeds.push(h.type);
                }
            }
        }
    }
    return collectTransitiveModelRefs(seeds, modelMap);
}
 
function paramSourceTypes(src: NonNullable<OpRootNode['routes'][number]['params']>): Parameters<typeof collectTypeRefs>[0][] {
    const out: Parameters<typeof collectTypeRefs>[0][] = [];
    if (src.kind === 'params') {
        for (const n of src.nodes) out.push(n.type);
    } else Eif (src.kind === 'ref') {
        out.push({ kind: 'ref', name: src.name } as Parameters<typeof collectTypeRefs>[0]);
    } else if (src.kind === 'type') {
        out.push(src.node);
    }
    return out;
}
 
/** Build a sorted, JSON-stable record of (modelName -> outPath) for refs this unit depends on. */
function sliceOutPathMap(refs: Set<string>, modelOutPaths: Map<string, string>, modelsWithInput: Set<string>, modelsWithOutput: Set<string>): Record<string, string> {
    const slice: Record<string, string> = {};
    for (const ref of [...refs].sort()) {
        const p = modelOutPaths.get(ref);
        Iif (p) slice[ref] = p;
        Iif (modelsWithInput.has(ref)) {
            const ip = modelOutPaths.get(`${ref}Input`);
            if (ip) slice[`${ref}Input`] = ip;
        }
        Iif (modelsWithOutput.has(ref)) {
            const op = modelOutPaths.get(`${ref}Output`);
            if (op) slice[`${ref}Output`] = op;
        }
    }
    return slice;
}
 
/** Slice modelsWithInput/Output to only the names relevant to this unit. */
function sliceModelSet(refs: Set<string>, ownNames: Set<string>, set: Set<string>): string[] {
    const result: string[] = [];
    for (const name of set) {
        if (refs.has(name) || ownNames.has(name)) result.push(name);
    }
    return result.sort();
}
 
// ─── Server sub-generator ──────────────────────────────────────────────────
 
function collectServerOutput(
    config: ServerConfig,
    rootDir: string,
    inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
    units: IncrementalUnit[],
): void {
    const serverBase = resolve(rootDir, config.baseDir ?? '.');
    const modelsWithInput = inputs.modelsWithInput as Set<string>;
    const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
    const modelMap = buildModelMap(inputs.contractRoots);
    const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
    const commonRoot = commonDir(allFiles, rootDir);
    const subConfigKey = stableSubConfig(config);
 
    // Pre-pass: register all model → outPath. Cross-file refs need to resolve correctly,
    // which means we need the COMPLETE map (not a slice) — even though each unit's fingerprint
    // only includes its own slice.
    const serverModelOutPaths = new Map<string, string>();
    const typeEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];
    if (config.output?.types) {
        for (const ast of inputs.contractRoots) {
            const typeOutPath = computeContractOutPath(ast.file, serverBase, config.output.types, '.ts', commonRoot, ast.meta);
            typeEntries.push({ ast, typeOutPath });
            for (const model of ast.models) {
                serverModelOutPaths.set(model.name, typeOutPath);
                Iif (modelsWithInput.has(model.name)) serverModelOutPaths.set(`${model.name}Input`, typeOutPath);
                Iif (modelsWithOutput.has(model.name)) serverModelOutPaths.set(`${model.name}Output`, typeOutPath);
            }
        }
    }
 
    // ── Per-contract-root types unit ──
    for (const { ast, typeOutPath } of typeEntries) {
        const refs = collectContractRootRefs(ast, modelMap);
        const ownNames = new Set(ast.models.map(m => m.name));
        const fingerprint = hashFingerprint({
            kind: 'server-types',
            v: TYPESCRIPT_CODEGEN_VERSION,
            outPath: typeOutPath,
            root: ast,
            outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),
            modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),
            modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),
            sub: subConfigKey,
        });
        units.push({
            key: `server-types::${typeOutPath}`,
            fingerprint,
            render: () => {
                const renderCtx = {
                    modelOutPaths: serverModelOutPaths,
                    currentOutPath: typeOutPath,
                    modelsWithInput,
                    modelsWithOutput,
                };
                const content = config.zod ? generateContract(ast, renderCtx) : generatePlainTypes(ast, renderCtx);
                return [{ relativePath: typeOutPath, content }];
            },
        });
    }
 
    // ── Per-op-root router unit ──
    for (const ast of inputs.opRoots) {
        const outPath = computeOpOutPath(ast.file, serverBase, config.output?.routes, '.router.ts', commonRoot, ast.meta);
        const refs = collectOpRootRefs(ast, modelMap);
        const fingerprint = hashFingerprint({
            kind: 'server-router',
            v: TYPESCRIPT_CODEGEN_VERSION,
            outPath,
            root: ast,
            // The router imports types from each contract root's type file; the slice covers exactly that.
            outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),
            modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),
            modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),
            servicePathTemplate: config.servicePathTemplate ?? null,
            includeInternal: config.includeInternal ?? true,
            sub: subConfigKey,
        });
        units.push({
            key: `server-router::${outPath}`,
            fingerprint,
            render: () => [
                {
                    relativePath: outPath,
                    content: generateOp(ast, {
                        servicePathTemplate: config.servicePathTemplate,
                        outPath,
                        modelOutPaths: serverModelOutPaths,
                        modelsWithInput,
                        modelsWithOutput,
                        includeInternal: config.includeInternal,
                    }),
                },
            ],
        });
    }
}
 
// ─── SDK sub-generator ─────────────────────────────────────────────────────
 
function collectSdkOutput(
    config: SdkConfig,
    rootDir: string,
    inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
    units: IncrementalUnit[],
    globalFiles: IncrementalOutputFile[],
): void {
    const sdkBase = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;
    const sdkName = config.name;
    const sdkOutput = config.output?.sdk;
    const sdkEntryPath = sdkOutput
        ? join(sdkBase, TEMPLATE_VAR_RE.test(sdkOutput) ? resolveTemplate(sdkOutput, { name: sdkName ?? 'sdk' }) : sdkOutput)
        : join(sdkBase, 'sdk.ts');
    const sdkOptionsPath = join(dirname(sdkEntryPath), 'sdk-options.ts');
    const subConfigKey = stableSubConfig(config);
 
    const modelsWithInput = inputs.modelsWithInput as Set<string>;
    const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
    const modelMap = buildModelMap(inputs.contractRoots);
    const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
    const ckCommonRoot = commonDir(allFiles, rootDir);
 
    const sdkModelOutPaths = new Map<string, string>();
    const sdkTypePaths: string[] = [];
    const sdkClientInfos: { outPath: string; className: string; propertyName: string }[] = [];
 
    // ── Pre-pass: SDK type files ──
    const sdkContractEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];
    Iif (config.output?.types) {
        const publicTypes = computePubliclyReachableTypes(inputs.opRoots, inputs.contractRoots, modelsWithInput, modelsWithOutput);
        for (const ast of inputs.contractRoots) {
            const typeOutPath = computeSdkTypeOutPath(ast.file, sdkBase, config.output.types, ckCommonRoot, ast.meta);
            if (!typeOutPath) continue;
            if (publicTypes !== null && !ast.models.some(m => publicTypes.has(m.name))) continue;
            sdkTypePaths.push(typeOutPath);
            sdkContractEntries.push({ ast, typeOutPath });
            for (const model of ast.models) {
                sdkModelOutPaths.set(model.name, typeOutPath);
                if (modelsWithInput.has(model.name)) sdkModelOutPaths.set(`${model.name}Input`, typeOutPath);
                if (modelsWithOutput.has(model.name)) sdkModelOutPaths.set(`${model.name}Output`, typeOutPath);
            }
        }
    }
 
    // ── SDK type units ──
    for (const { ast, typeOutPath } of sdkContractEntries) {
        const refs = collectContractRootRefs(ast, modelMap);
        const ownNames = new Set(ast.models.map(m => m.name));
        const fingerprint = hashFingerprint({
            kind: 'sdk-types',
            v: TYPESCRIPT_CODEGEN_VERSION,
            outPath: typeOutPath,
            root: ast,
            outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),
            modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),
            modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),
            sdkOptionsPath,
            sub: subConfigKey,
        });
        units.push({
            key: `sdk-types::${typeOutPath}`,
            fingerprint,
            render: () => {
                let content: string;
                if (config.zod) {
                    content = generateContract(ast, {
                        modelOutPaths: sdkModelOutPaths,
                        currentOutPath: typeOutPath,
                        modelsWithInput,
                        modelsWithOutput,
                    });
                } else {
                    let rel = relative(dirname(typeOutPath), sdkOptionsPath).replace(/\.ts$/, '.js');
                    if (!rel.startsWith('.')) rel = './' + rel;
                    content = generatePlainTypes(ast, {
                        modelOutPaths: sdkModelOutPaths,
                        currentOutPath: typeOutPath,
                        modelsWithInput,
                        modelsWithOutput,
                        jsonValueImportPath: rel,
                    });
                }
                return [{ relativePath: typeOutPath, content }];
            },
        });
    }
 
    // ── Bucket op roots by area/subarea ──
    interface AreaBucket {
        leaves: { ast: OpRootNode; outPath: string; subarea: string }[];
        inlineRoots: OpRootNode[];
    }
    const areaBuckets = new Map<string, AreaBucket>();
    const topLevelEntries: { ast: OpRootNode; outPath: string }[] = [];
 
    Eif (config.output?.clients) {
        for (const ast of inputs.opRoots) {
            const sdkOutPath = computeSdkOutPath(ast.file, sdkBase, config.output.clients, ckCommonRoot, ast.meta);
            Iif (!sdkOutPath || !hasPublicOperations(ast, config.includeInternal)) continue;
            const { area, subarea } = getAreaSubarea(ast);
            if (area && subarea) {
                const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };
                bucket.leaves.push({ ast, outPath: sdkOutPath, subarea });
                areaBuckets.set(area, bucket);
            } else if (area) {
                const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };
                bucket.inlineRoots.push(ast);
                areaBuckets.set(area, bucket);
            } else {
                topLevelEntries.push({ ast, outPath: sdkOutPath });
            }
        }
 
        // ── Per-leaf-client (area+subarea) units ──
        for (const [area, bucket] of areaBuckets.entries()) {
            for (const leaf of bucket.leaves) {
                const className = deriveSubareaClientClassName(area, leaf.subarea);
                sdkClientInfos.push({ outPath: leaf.outPath, className, propertyName: deriveSubareaPropertyName(leaf.subarea) });
                const refs = collectOpRootRefs(leaf.ast, modelMap);
                const fingerprint = hashFingerprint({
                    kind: 'sdk-leaf-client',
                    v: TYPESCRIPT_CODEGEN_VERSION,
                    outPath: leaf.outPath,
                    root: leaf.ast,
                    outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),
                    modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),
                    modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),
                    sdkOptionsPath,
                    className,
                    includeInternal: config.includeInternal ?? false,
                    sub: subConfigKey,
                });
                units.push({
                    key: `sdk-leaf-client::${leaf.outPath}`,
                    fingerprint,
                    render: () => [
                        {
                            relativePath: leaf.outPath,
                            content: generateSdk(leaf.ast, {
                                typeImportPathTemplate: undefined,
                                outPath: leaf.outPath,
                                modelOutPaths: sdkModelOutPaths,
                                sdkOptionsPath,
                                modelsWithInput,
                                modelsWithOutput,
                                includeInternal: config.includeInternal,
                                clientClassName: className,
                            }),
                        },
                    ],
                });
            }
        }
 
        // ── Top-level (no area) client units ──
        for (const { ast, outPath } of topLevelEntries) {
            const className = deriveClientClassName(ast.file);
            sdkClientInfos.push({ outPath, className, propertyName: deriveClientPropertyName(ast.file) });
            const refs = collectOpRootRefs(ast, modelMap);
            const fingerprint = hashFingerprint({
                kind: 'sdk-top-client',
                v: TYPESCRIPT_CODEGEN_VERSION,
                outPath,
                root: ast,
                outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),
                modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),
                modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),
                sdkOptionsPath,
                includeInternal: config.includeInternal ?? false,
                sub: subConfigKey,
            });
            units.push({
                key: `sdk-top-client::${outPath}`,
                fingerprint,
                render: () => [
                    {
                        relativePath: outPath,
                        content: generateSdk(ast, {
                            typeImportPathTemplate: undefined,
                            outPath,
                            modelOutPaths: sdkModelOutPaths,
                            sdkOptionsPath,
                            modelsWithInput,
                            modelsWithOutput,
                            includeInternal: config.includeInternal,
                        }),
                    },
                ],
            });
        }
    }
 
    // ── Global files: sdk-options, aggregator, barrels, root index ──
    // The aggregator inlines area-only op roots, so its content depends on each inline root's
    // full AST. Caching it gains little — the codegen is fast and any inline-root change rebuilds
    // the file anyway. Same for barrels (one line per imported file). Always regenerate.
    globalFiles.push({ relativePath: sdkOptionsPath, content: generateSdkOptions() });
 
    const hasAnything = sdkClientInfos.length > 0 || areaBuckets.size > 0;
    Eif (hasAnything) {
        const sdkEntryDir = dirname(sdkEntryPath);
        const sdkOptionsRel = relative(sdkEntryDir, sdkOptionsPath).replace(/\.ts$/, '.js');
        const sdkOptionsImportPath = sdkOptionsRel.startsWith('.') ? sdkOptionsRel : './' + sdkOptionsRel;
        const sdkClassName = sdkName
            ? sdkName
                  .split(/[-._\s]+/)
                  .map(s => s.charAt(0).toUpperCase() + s.slice(1))
                  .join('') + 'Sdk'
            : 'Sdk';
 
        const toClientImport = (info: { outPath: string; className: string; propertyName: string }): SdkClientInfo => {
            let rel = relative(sdkEntryDir, info.outPath).replace(/\.ts$/, '.js');
            Eif (!rel.startsWith('.')) rel = './' + rel;
            return { className: info.className, propertyName: info.propertyName, importPath: rel };
        };
 
        const topLevelClients: SdkClientInfo[] = topLevelEntries.map(e => ({
            className: deriveClientClassName(e.ast.file),
            propertyName: deriveClientPropertyName(e.ast.file),
            importPath: (() => {
                const rel = relative(sdkEntryDir, e.outPath).replace(/\.ts$/, '.js');
                return rel.startsWith('.') ? rel : './' + rel;
            })(),
        }));
 
        const areas: SdkAreaInfo[] = [...areaBuckets.entries()]
            .sort(([a], [b]) => a.localeCompare(b))
            .map(([area, bucket]) => ({
                area,
                inlineFiles: bucket.inlineRoots.map(root => ({
                    root,
                    codegenOptions: {
                        typeImportPathTemplate: undefined,
                        outPath: sdkEntryPath,
                        modelOutPaths: sdkModelOutPaths,
                        sdkOptionsPath,
                        modelsWithInput,
                        modelsWithOutput,
                        includeInternal: config.includeInternal,
                    },
                })),
                subareaClients: bucket.leaves
                    .sort((a, b) => a.subarea.localeCompare(b.subarea))
                    .map(l => ({
                        propertyName: deriveSubareaPropertyName(l.subarea),
                        client: toClientImport({
                            outPath: l.outPath,
                            className: deriveSubareaClientClassName(area, l.subarea),
                            propertyName: deriveSubareaPropertyName(l.subarea),
                        }),
                    })),
            }));
 
        globalFiles.push({
            relativePath: sdkEntryPath,
            content: generateSdkAggregator({ topLevelClients, areas, sdkOptionsImportPath, sdkClassName }),
        });
    }
 
    const sdkSrcDir = dirname(sdkEntryPath);
    const sdkTypeBarrels = generateBarrelFiles(sdkTypePaths);
    for (const barrel of sdkTypeBarrels) globalFiles.push({ relativePath: barrel.outPath, content: barrel.content });
 
    const rootExports: string[] = [`export * from './${basename(sdkOptionsPath).replace(/\.ts$/, '.js')}';`];
    Eif (hasAnything) rootExports.push(`export * from './${basename(sdkEntryPath).replace(/\.ts$/, '.js')}';`);
    for (const c of sdkClientInfos) {
        let rel = relative(sdkSrcDir, c.outPath).replace(/\.ts$/, '.js');
        Eif (!rel.startsWith('.')) rel = './' + rel;
        rootExports.push(`export * from '${rel}';`);
    }
    for (const barrel of sdkTypeBarrels) {
        let rel = relative(sdkSrcDir, barrel.outPath).replace(/\.ts$/, '.js');
        if (!rel.startsWith('.')) rel = './' + rel;
        rootExports.push(`export * from '${rel}';`);
    }
    globalFiles.push({
        relativePath: join(sdkSrcDir, 'index.ts'),
        content: `// Auto-generated barrel file\n${rootExports.sort().join('\n')}\n`,
    });
}
 
// ─── Zod sub-generator ─────────────────────────────────────────────────────
 
function collectZodOutput(
    config: ZodConfig,
    rootDir: string,
    inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
    units: IncrementalUnit[],
): void {
    const zodBase = resolve(rootDir, config.baseDir ?? '.');
    const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
    const commonRoot = commonDir(allFiles, rootDir);
    const modelsWithInput = inputs.modelsWithInput as Set<string>;
    const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
    const modelMap = buildModelMap(inputs.contractRoots);
    const subConfigKey = stableSubConfig(config);
 
    const modelOutPaths = new Map<string, string>();
    const entries: { ast: ContractRootNode; outPath: string }[] = [];
    for (const ast of inputs.contractRoots) {
        const outPath = computeContractOutPath(ast.file, zodBase, config.output, '.schema.ts', commonRoot, ast.meta);
        entries.push({ ast, outPath });
        for (const model of ast.models) {
            modelOutPaths.set(model.name, outPath);
            if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);
            if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);
        }
    }
 
    for (const { ast, outPath } of entries) {
        const refs = collectContractRootRefs(ast, modelMap);
        const ownNames = new Set(ast.models.map(m => m.name));
        const fingerprint = hashFingerprint({
            kind: 'zod',
            v: TYPESCRIPT_CODEGEN_VERSION,
            outPath,
            root: ast,
            outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),
            modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),
            modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),
            sub: subConfigKey,
        });
        units.push({
            key: `zod::${outPath}`,
            fingerprint,
            render: () => [
                {
                    relativePath: outPath,
                    content: generateContract(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput }),
                },
            ],
        });
    }
}
 
// ─── Plain types sub-generator ─────────────────────────────────────────────
 
function collectTypesOutput(
    config: TypesConfig,
    rootDir: string,
    inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],
    units: IncrementalUnit[],
): void {
    const typesBase = resolve(rootDir, config.baseDir ?? '.');
    const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];
    const commonRoot = commonDir(allFiles, rootDir);
    const modelsWithInput = inputs.modelsWithInput as Set<string>;
    const modelsWithOutput = inputs.modelsWithOutput as Set<string>;
    const modelMap = buildModelMap(inputs.contractRoots);
    const subConfigKey = stableSubConfig(config);
 
    const modelOutPaths = new Map<string, string>();
    const entries: { ast: ContractRootNode; outPath: string }[] = [];
    for (const ast of inputs.contractRoots) {
        const outPath = computeContractOutPath(ast.file, typesBase, config.output, '.types.ts', commonRoot, ast.meta);
        entries.push({ ast, outPath });
        for (const model of ast.models) {
            modelOutPaths.set(model.name, outPath);
            if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);
            if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);
        }
    }
 
    for (const { ast, outPath } of entries) {
        const refs = collectContractRootRefs(ast, modelMap);
        const ownNames = new Set(ast.models.map(m => m.name));
        const fingerprint = hashFingerprint({
            kind: 'plain-types',
            v: TYPESCRIPT_CODEGEN_VERSION,
            outPath,
            root: ast,
            outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),
            modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),
            modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),
            sub: subConfigKey,
        });
        units.push({
            key: `plain-types::${outPath}`,
            fingerprint,
            render: () => [
                {
                    relativePath: outPath,
                    content: generatePlainTypes(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput }),
                },
            ],
        });
    }
}
 
// ─── Manifest IO + cleanup ─────────────────────────────────────────────────
 
function readManifest(manifestPath: string): IncrementalManifest {
    Eif (!existsSync(manifestPath)) return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);
    try {
        return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));
    } catch {
        return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);
    }
}
 
function deleteStalePaths(absPaths: string[]): void {
    Eif (absPaths.length === 0) return;
    const removedDirs = new Set<string>();
    for (const abs of absPaths) {
        if (existsSync(abs)) {
            rmSync(abs, { force: true });
            removedDirs.add(dirname(abs));
        }
    }
    // Walk up affected dirs and remove if empty. Bounded — stops at filesystem root or first non-empty dir.
    for (const dir of removedDirs) {
        let current = dir;
        while (current.length > 1) {
            try {
                if (readdirSync(current).length === 0) {
                    rmdirSync(current);
                    current = dirname(current);
                } else {
                    break;
                }
            } catch {
                break;
            }
        }
    }
}
 
/** Stringify a sub-config so it can participate in fingerprints. JSON.stringify gives stable output for typical config shapes. */
function stableSubConfig(config: unknown): string {
    return JSON.stringify(config ?? null);
}