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 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 | 126x 119x 5x 2x 143x 143x 224x 30x 143x 143x 162x 162x 221x 155x 155x 192x 155x 155x 155x 71x 21x 21x 21x 143x 105x 105x 105x 105x 1x 105x 105x 105x 105x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 19x 19x 80x 80x 1x 80x 5x 80x 3x 80x 1x 1x 80x 143x 105x 80x 105x 105x 80x 111x 15x 15x 15x 11x 11x 111x 1x 2x 3x 1x 105x 5x 100x 127x 105x 105x 3x 100x 5x 5x 5x 5x 5x 3x 3x 5x 5x 72x 72x 72x 72x 72x 72x 72x 8x 8x 17x 8x 8x 17x 17x 17x 8x 8x 8x 8x 64x 64x 72x 6x 6x 3x 6x 6x 6x 58x 74x 58x 64x 64x 14x 14x 2x 14x 5x 5x 4x 4x 1x 4x 4x 4x 4x 28x 28x 28x 28x 28x 47x 28x 28x 4x 4x 4x 10x 4x 4x 48x 28x 28x 8x 7x 21x 44x 28x 28x 28x 48x 28x 28x 28x 7x 9x 4x 4x 2x 2x 28x 2x 28x 8x 7x 21x 31x 28x 28x 28x 20x 16x 34x 19x 6x 137x 4x 8x 8x 8x 8x 8x 8x 8x 3x 7x 7x 7x 7x 1x 6x 7x 7x 143x 143x 143x 143x 143x 6x 6x 137x 6x 143x 143x 143x 274x 210x 12x 2x 2x 3x 6x 3x 1x 4x 26x 2x 3x 6x 6x 3x 6x 4x 2x 2x 2x 1x 1x 2x 239x 118x 118x 117x 116x 118x 118x 118x 16x 16x 16x 16x 16x 16x 16x 16x 6x 6x 6x 6x 6x 5x 5x 2x 2x 7x 4x 7x 7x 7x 7x 7x 7x 6x 5x 7x 3x 1x 38x 2x 3x 1x 2x 2x 12x 12x 12x 12x 4x 2x 7x 3x 6x 2x 6x 3x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 4x 3x 3x 3x 1x 2x 1x 2x 2x 2x 1x 2x 4x 4x 2x 29x 61x 29x 25x 3x 3x 3x 3x 2x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 3x 33x 33x 33x 33x 33x 1x 1x 32x 3x 33x 33x 33x 31x 5x 1x 1x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 4x 2x 2x 2x 2x 2x 2x 2x 214x 214x 25x 140x 1456x 852x 76x 12x 6x 24x 2x 68x 6x 46x 430x 825x 263x 149x 14x 2x 8x 8x 84x 183x 143x 143x 183x 183x 183x 253x 183x 143x 57x 34x 34x 57x 51x 5x 5x 46x 2x 80x 46x 52x 34x 57x 34x 79x 17x 17x 6x 6x 2x 1x 10x 5x 4x 4x 183x 183x 143x 143x 183x 183x 183x 183x 253x 183x 183x 60x 183x 143x 183x 143x 183x 37x 143x 143x 183x 143x 143x 183x 143x 143x 183x 183x 183x 291x 35x 143x 183x 143x 38x 21x 21x 15x 15x 15x 15x 15x 23x 23x 26x | import { relative, dirname } from 'node:path';
import type {
ContractRootNode,
ModelNode,
FieldNode,
ContractTypeNode,
ScalarTypeNode,
ArrayTypeNode,
TupleTypeNode,
RecordTypeNode,
EnumTypeNode,
LiteralTypeNode,
UnionTypeNode,
DiscriminatedUnionTypeNode,
InlineObjectTypeNode,
IntersectionTypeNode,
ObjectMode,
} from '@contractkit/core';
import {
collectTypeRefs,
computeModelsWithOutput as ckComputeModelsWithOutput,
collectExternalOutputRefs as ckCollectExternalOutputRefs,
} from '@contractkit/core';
/**
* Maps a ContractKit object mode to its Zod constructor name.
*
* @returns `"z.strictObject"` | `"z.object"` | `"z.looseObject"`
*/
export function modeToWrapper(mode: ObjectMode): string {
switch (mode) {
case 'strict':
return 'z.strictObject';
case 'strip':
return 'z.object';
case 'loose':
return 'z.looseObject';
}
}
// ─── Cross-file import resolution ─────────────────────────────────────────
/** Cross-file context passed to `generateContract` to wire up imports and Input/Output variant tracking. */
export interface ContractCodegenContext {
/** Map from model name → absolute output file path */
modelOutPaths: Map<string, string>;
/** Absolute output file path for the current contract file */
currentOutPath: string;
/** Set of model names that have Input variants (models with visibility modifiers) */
modelsWithInput?: Set<string>;
/** Set of model names that have Output variants (models with format(output=...)) */
modelsWithOutput?: Set<string>;
/** If set, import JsonValue from this path instead of re-declaring it (avoids barrel re-export conflicts) */
jsonValueImportPath?: string;
}
// ─── Public entry point ────────────────────────────────────────────────────
/**
* 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: add models that reference models with Input variants,
// including through base model inheritance.
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);
}
// A model that extends a parent with Input variants also needs an Input variant,
// so that the write schema can extend ParentInput instead of Parent.
if (model.bases) for (const b of model.bases) refs.add(b);
// A type alias (model.type set) that references a model with Input variants
// also needs an Input variant.
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;
}
function generateComments(model: ModelNode, outPath?: string): string[] {
const lines: string[] = [];
lines.push('/**');
Iif (model.deprecated) {
lines.push(` * @deprecated`);
}
if (model.description) {
lines.push(` * ${model.description}`);
}
const relPath = outPath ? relative(dirname(outPath), model.loc.file) : model.loc.file;
lines.push(` * generated from [${model.name}](file://./${relPath}#L${model.loc.line})`);
lines.push('*/');
return lines;
}
/**
* Generate a TypeScript module containing Zod schemas for every model in `root`.
*
* Emits up to three schemas per model when visibility modifiers are present:
* `ModelBase` (all fields), `Model` (read — no writeonly), `ModelInput` (write — no readonly).
*
* @param root - The parsed contract root node.
* @param context - Optional cross-file context for import resolution and Input/Output variant tracking.
* @returns The full TypeScript source as a string.
*/
export function generateContract(root: ContractRootNode, context?: ContractCodegenContext): string {
const needsDateTime = rootNeedsDateTime(root);
const needsDuration = rootNeedsScalar(root, 'duration');
const needsInterval = rootNeedsScalar(root, 'interval');
const needsBinary = rootNeedsScalar(root, 'binary');
const needsDatetime = rootNeedsScalar(root, 'datetime');
const needsJson = rootNeedsScalar(root, 'json');
const externalRefs = collectExternalRefs(root);
const lines: string[] = [];
// Compute which models have Input variants (local, incl. transitive deps + external)
const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();
const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);
const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);
// Compute which models have Output variants (post-transform wire shape)
const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();
const localModelsWithOutput = ckComputeModelsWithOutput(root.models, externalModelsWithOutput);
const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);
// Collect additional external Input refs needed for Input schema fields
const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];
const externalOutputRefs = allModelsWithOutput.size > 0 ? ckCollectExternalOutputRefs(root, allModelsWithOutput) : [];
const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();
lines.push(`import { z } from 'zod';`);
const luxonImports: string[] = [];
if (needsDateTime) luxonImports.push('DateTime');
if (needsDuration) luxonImports.push('Duration');
if (needsInterval) luxonImports.push('Interval');
if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);
for (const ref of allExternalRefs) {
const importPath = resolveImportPath(ref, context);
lines.push(`import { ${ref} } from '${importPath}';`);
}
lines.push('');
if (needsBinary) {
lines.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);
}
if (needsDatetime) {
lines.push(
`const _ZodDatetime = z.preprocess((val) => typeof val === 'string' ? DateTime.fromISO(val) : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be in ISO 8601 format' }));`,
);
}
if (needsInterval) {
lines.push(
`const _ZodInterval = z.preprocess((val) => typeof val === 'string' ? Interval.fromISO(val) : val, z.custom<Interval>((val) => val instanceof Interval && val.isValid, { message: 'Must be an ISO 8601 interval' })).transform(val => val.toISO()!);`,
);
}
if (needsJson) {
lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);
lines.push(
`const _ZodJson: z.ZodType<_JsonValue> = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(_ZodJson), z.record(z.string(), _ZodJson)]));`,
);
}
if (needsBinary || needsDatetime || needsInterval || needsJson) lines.push('');
const modelsWithWriteonly = new Set(root.models.filter(m => m.fields.some(f => f.visibility === 'writeonly')).map(m => m.name));
const modelMap = new Map(root.models.map(m => [m.name, m]));
for (const model of topoSortModels(root.models)) {
lines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, modelsWithWriteonly, modelMap, allModelsWithOutput));
lines.push('');
}
return lines.join('\n');
}
// ─── Model ─────────────────────────────────────────────────────────────────
/**
* If any ancestor in the base chain has a format(input=)/format(output=) transform,
* the parent schema compiles to a `ZodPipe` (object().transform()) which has no `.extend()`.
* To keep extension working, inline the parent's fields into the child and inherit format/mode
* so the child re-applies the transform on the merged shape. Returns the model unchanged when
* no ancestor has format, preserving the existing `.extend()`-based output.
*/
function flattenFormatChain(model: ModelNode, modelMap: Map<string, ModelNode>): ModelNode {
if (!model.bases || model.bases.length === 0) return model;
// TODO(multi-base): currently only the first base is followed for format inheritance.
// Multi-base format flattening will need a topological merge across all bases.
const firstBase = model.bases[0]!;
const parent = modelMap.get(firstBase);
if (!parent) return model;
const flatParent = flattenFormatChain(parent, modelMap);
const parentHasFormat =
(flatParent.inputCase !== undefined && flatParent.inputCase !== 'camel') ||
(flatParent.outputCase !== undefined && flatParent.outputCase !== 'camel');
if (!parentHasFormat) return model;
const merged = new Map<string, FieldNode>();
for (const f of flatParent.fields) merged.set(f.name, f);
for (const f of model.fields) merged.set(f.name, f);
return {
...model,
bases: undefined,
fields: [...merged.values()],
inputCase: model.inputCase ?? flatParent.inputCase,
outputCase: model.outputCase ?? flatParent.outputCase,
mode: model.mode ?? flatParent.mode,
};
}
function generateModel(
model: ModelNode,
outPath?: string,
modelsWithInput?: Set<string>,
modelsWithWriteonly?: Set<string>,
modelMap?: Map<string, ModelNode>,
modelsWithOutput?: Set<string>,
): string[] {
// Type alias: Name : typeExpression
if (model.type) {
return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);
}
const effective = modelMap ? flattenFormatChain(model, modelMap) : model;
// A model needs Input/read split if it has visibility-modified fields OR if it
// transitively references models that have Input variants (captured in modelsWithInput).
const needsInputSplit = effective.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(effective.name) ?? false);
const lines = needsInputSplit
? generateThreeSchemaModel(effective, outPath, modelsWithInput, modelsWithWriteonly, modelMap)
: generateSimpleModel(effective, outPath);
// Emit Output type alias when this model (transitively) has format(output=...)
if (modelsWithOutput?.has(effective.name)) {
lines.push(`export type ${effective.name}Output = z.output<typeof ${effective.name}>;`);
}
return lines;
}
function generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {
const lines: string[] = [];
lines.push(...generateComments(model, outPath));
lines.push(`export const ${model.name} = ${renderType(model.type!)};`);
lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);
if (modelsWithInput?.has(model.name)) {
lines.push(`export const ${model.name}Input = ${renderInputType(model.type!, modelsWithInput)};`);
lines.push(`export type ${model.name}Input = z.infer<typeof ${model.name}Input>;`);
}
Iif (modelsWithOutput?.has(model.name)) {
lines.push(`export type ${model.name}Output = z.output<typeof ${model.name}>;`);
}
return lines;
}
function generateSimpleModel(model: ModelNode, outPath?: string): string[] {
const lines: string[] = [];
lines.push(...generateComments(model, outPath));
const wrapper = modeToWrapper(model.mode ?? 'strict');
const { inputCase, outputCase } = model;
const hasInputTransform = !!inputCase && inputCase !== 'camel';
const hasOutputTransform = !!outputCase && outputCase !== 'camel';
if (hasInputTransform || hasOutputTransform) {
const inputBody =
inputCase === 'snake'
? renderFieldsAsSnakeCase(model.fields, model.mode)
: inputCase === 'pascal'
? renderFieldsAsPascalCase(model.fields, model.mode)
: renderFields(model.fields, model.mode);
lines.push(`export const ${model.name} = ${wrapper}({`);
lines.push(...inputBody.map(l => ` ${l}`));
lines.push(`}).transform(data => ({`);
for (const field of model.fields) {
const inputKey = applyCase(field.name, inputCase);
const outputKey = applyCase(field.name, outputCase);
lines.push(` ${quoteKey(outputKey)}: data.${inputKey},`);
}
lines.push(`}));`);
// When only outputCase is set, the developer-facing type is the schema's
// pre-transform shape (camelCase). With inputCase, the post-transform
// shape is what consumers work with.
const typeSource = hasOutputTransform && !hasInputTransform ? 'input' : 'output';
lines.push(`export type ${model.name} = z.${typeSource}<typeof ${model.name}>;`);
return lines;
}
const body = renderFields(model.fields, model.mode);
const bases = model.bases ?? [];
if (bases.length > 0) {
const head = bases[0]!;
const tail = bases
.slice(1)
.map(b => `.extend(${b}.shape)`)
.join('');
lines.push(`export const ${model.name} = ${head}${tail}.extend({`);
lines.push(...body.map(l => ` ${l}`));
lines.push(`});`);
} else {
lines.push(`export const ${model.name} = ${wrapper}({`);
lines.push(...body.map(l => ` ${l}`));
lines.push(`});`);
}
lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);
return lines;
}
/** Builds a Zod extension chain "Head.extend(B.shape).extend(C.shape)..." for a list of base names,
* applying a per-base name resolver (e.g. choosing "BaseInput" for bases that have an Input variant). */
function buildExtendChain(bases: string[], resolveName: (b: string) => string): { head: string; tail: string } {
const head = resolveName(bases[0]!);
const tail = bases
.slice(1)
.map(b => `.extend(${resolveName(b)}.shape)`)
.join('');
return { head, tail };
}
function collectEffectiveWritableFieldNames(modelName: string, modelMap: Map<string, ModelNode>): Set<string> {
const model = modelMap.get(modelName);
if (!model || model.type) return new Set();
const result = new Set<string>();
for (const base of model.bases ?? []) {
for (const f of collectEffectiveWritableFieldNames(base, modelMap)) result.add(f);
}
for (const field of model.fields) {
Iif (field.visibility === 'readonly') result.delete(field.name);
else result.add(field.name);
}
return result;
}
function generateThreeSchemaModel(
model: ModelNode,
outPath?: string,
modelsWithInput?: Set<string>,
modelsWithWriteonly?: Set<string>,
modelMap?: Map<string, ModelNode>,
): string[] {
const lines: string[] = [];
const name = model.name;
lines.push(...generateComments(model, outPath));
const wrapper = modeToWrapper(model.mode ?? 'strict');
const allFields = model.fields;
const hasWriteonly = allFields.some(f => f.visibility === 'writeonly');
const bases = model.bases ?? [];
// Base schema — all fields (used internally when a submodel extends this one).
// Only needed when this model has writeonly fields; otherwise Base === Read.
if (hasWriteonly) {
const baseBody = renderFields(allFields, model.mode);
Iif (bases.length > 0) {
const { head, tail } = buildExtendChain(bases, b => (modelsWithWriteonly?.has(b) ? `${b}Base` : b));
lines.push(`const ${name}Base = ${head}${tail}.extend({`);
} else {
lines.push(`const ${name}Base = ${wrapper}({`);
}
lines.push(...baseBody.map(l => ` ${l}`));
lines.push(`});`);
lines.push('');
}
// Read schema — omit writeonly fields; extends parent read schema
const readFields = allFields.filter(f => f.visibility !== 'writeonly');
const readBody = renderFields(readFields, model.mode);
if (bases.length > 0) {
const { head, tail } = buildExtendChain(bases, b => b);
lines.push(`export const ${name} = ${head}${tail}.extend({`);
} else {
lines.push(`export const ${name} = ${wrapper}({`);
}
lines.push(...readBody.map(l => ` ${l}`));
lines.push(`});`);
lines.push(`export type ${name} = z.infer<typeof ${name}>;`);
lines.push('');
// Write schema — omit readonly fields (use Input variants for sub-type refs);
// extends ParentInput if parent has an Input variant, else extends parent read schema
const writeFields = allFields.filter(f => f.visibility !== 'readonly');
const writeBody = modelsWithInput ? renderInputFields(writeFields, modelsWithInput, model.mode) : renderFields(writeFields, model.mode);
// Fields that become readonly in this model but were writable in a base must be omitted from
// the base Input schema — Zod's .extend() cannot remove inherited fields.
const fieldsToOmit = new Set<string>();
if (bases.length > 0 && modelMap) {
for (const field of allFields) {
if (field.visibility === 'readonly') {
for (const base of bases) {
if (collectEffectiveWritableFieldNames(base, modelMap).has(field.name)) {
fieldsToOmit.add(field.name);
break;
}
}
}
}
}
const omitClause =
fieldsToOmit.size > 0
? `.omit({ ${[...fieldsToOmit].map(f => `${quoteKey(f)}: true`).join(', ')} })`
: '';
if (bases.length > 0) {
const { head, tail } = buildExtendChain(bases, b => (modelsWithInput?.has(b) ? `${b}Input` : b));
lines.push(`export const ${name}Input = ${head}${tail}${omitClause}.extend({`);
} else {
lines.push(`export const ${name}Input = ${wrapper}({`);
}
lines.push(...writeBody.map(l => ` ${l}`));
lines.push(`});`);
lines.push(`export type ${name}Input = z.infer<typeof ${name}Input>;`);
return lines;
}
// ─── Fields ────────────────────────────────────────────────────────────────
function camelToSnake(s: string): string {
return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);
}
function camelToPascal(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
function applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {
if (!caseTransform || caseTransform === 'camel') return name;
if (caseTransform === 'snake') return camelToSnake(name);
return camelToPascal(name);
}
function renderFields(fields: FieldNode[], defaultMode?: ObjectMode): string[] {
return fields.flatMap(f => renderField(f, defaultMode));
}
function renderFieldsAsPascalCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {
return fields.map(f => {
const pascalKey = camelToPascal(f.name);
let expr = renderType(f.type, 'pascal', defaultMode);
Iif (f.default !== undefined) {
if (f.nullable) expr += '.nullable()';
const dv = typeof f.default === 'string' ? `"${escapeString(f.default)}"` : String(f.default);
expr += `.default(${dv})`;
} else Iif (f.optional) {
expr += '.nullish()';
} else Iif (f.nullable) {
expr += '.nullable()';
}
Iif (f.description) expr += `.describe("${escapeString(f.description)}")`;
return `${quoteKey(pascalKey)}: ${expr},`;
});
}
function renderFieldsAsSnakeCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {
return fields.map(f => {
const snakeKey = camelToSnake(f.name);
let expr = renderType(f.type, 'snake', defaultMode);
Iif (f.default !== undefined) {
if (f.nullable) expr += '.nullable()';
const dv = typeof f.default === 'string' ? `"${escapeString(f.default)}"` : String(f.default);
expr += `.default(${dv})`;
} else if (f.optional) {
// .nullish() accepts null or undefined from the API; the transform coerces null → undefined
expr += '.nullish()';
} else Iif (f.nullable) {
expr += '.nullable()';
}
Iif (f.description) expr += `.describe("${escapeString(f.description)}")`;
return `${quoteKey(snakeKey)}: ${expr},`;
});
}
function renderField(field: FieldNode, defaultMode?: ObjectMode): string[] {
const lines: string[] = [];
Iif (field.deprecated) lines.push('/** @deprecated */');
let expr = renderType(field.type, undefined, defaultMode);
if (field.nullable) expr += '.nullable()';
if (field.default !== undefined) {
const dv = typeof field.default === 'string' ? `"${escapeString(field.default)}"` : String(field.default);
expr += `.default(${dv})`;
} else if (field.optional) {
expr += '.optional()';
}
if (field.description) expr += `.describe("${escapeString(field.description)}")`;
lines.push(`${quoteKey(field.name)}: ${expr},`);
return lines;
}
// ─── Type rendering ────────────────────────────────────────────────────────
/**
* Render a ContractKit AST type node as a Zod schema expression string.
*
* @param parseCaseTransform - When set, generates a `.transform()` that remaps incoming keys from
* the given casing (`'snake'` | `'pascal'`) to camelCase for `inlineObject` types.
* @param defaultMode - Fallback object mode (`'strict'` | `'strip'` | `'loose'`) when the node
* doesn't specify its own mode.
*/
export function renderType(type: ContractTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {
switch (type.kind) {
case 'scalar':
return renderScalar(type);
case 'array':
return renderArray(type, parseCaseTransform, defaultMode);
case 'tuple':
return renderTuple(type);
case 'record':
return renderRecord(type);
case 'enum':
return renderEnum(type);
case 'literal':
return renderLiteral(type);
case 'union':
return renderUnion(type, parseCaseTransform, defaultMode);
case 'discriminatedUnion':
return renderDiscriminatedUnion(type, parseCaseTransform, defaultMode);
case 'intersection':
return renderIntersection(type, parseCaseTransform, defaultMode);
case 'ref':
return type.name;
case 'lazy':
return `z.lazy(() => ${renderType(type.inner, parseCaseTransform, defaultMode)})`;
case 'inlineObject':
return renderInlineObject(type, parseCaseTransform, defaultMode);
default:
return 'z.unknown()';
}
}
/**
* Render a regex source as a JS regex literal for `.regex(...)`. If the source already has
* anchors (`^` at the start and/or an unescaped `$` at the end) we trust the user's intent
* and emit it as-is; otherwise we wrap with `^...$` so contracts default to full-match
* semantics. Forward slashes are always escaped since `/` is the literal delimiter.
*/
function renderRegexLiteral(source: string): string {
const body = source.replace(/\//g, '\\/');
if (regexHasAnchor(source)) return `/${body}/`;
return `/^${body}$/`;
}
function regexHasAnchor(source: string): boolean {
if (source.startsWith('^')) return true;
if (!source.endsWith('$')) return false;
// The trailing `$` is an anchor only if it isn't escaped — count immediately preceding
// backslashes; an even count (including zero) means `$` is unescaped.
let i = source.length - 2;
let backslashes = 0;
while (i >= 0 && source[i] === '\\') {
backslashes++;
i--;
}
return backslashes % 2 === 0;
}
function renderScalar(s: ScalarTypeNode): string {
switch (s.name) {
case 'string': {
let e = 'z.string()';
if (s.min !== undefined && s.max !== undefined) e += `.min(${s.min}).max(${s.max})`;
else if (s.min !== undefined) e += `.min(${s.min})`;
else if (s.max !== undefined) e += `.max(${s.max})`;
if (s.len !== undefined) e += `.length(${s.len})`;
if (s.regex) e += `.regex(${renderRegexLiteral(s.regex)})`;
return e;
}
case 'number': {
let e = 'z.coerce.number()';
if (s.min !== undefined) e += `.min(${s.min})`;
if (s.max !== undefined) e += `.max(${s.max})`;
return e;
}
case 'int': {
let e = 'z.coerce.number().int()';
if (s.min !== undefined) e += `.min(${s.min})`;
if (s.max !== undefined) e += `.max(${s.max})`;
return e;
}
case 'bigint': {
let inner = 'z.bigint()';
if (s.min !== undefined) inner += `.min(${s.min}n)`;
if (s.max !== undefined) inner += `.max(${s.max}n)`;
return `z.preprocess((val) => typeof val === 'string' ? BigInt(val.replace(/n$/, '')) : val, ${inner})`;
}
case 'boolean':
return `z.preprocess((v) => v === 'true' ? true : v === 'false' ? false : v, z.boolean())`;
case 'date': {
const fmt = s.format ?? 'yyyy-MM-dd';
return `z.preprocess((val) => typeof val === 'string' ? DateTime.fromFormat(val, '${escapeString(fmt)}') : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be a date in format ${escapeString(fmt)}' }))`;
}
case 'time': {
const fmt = s.format ?? 'HH:mm:ss';
return `z.preprocess((val) => typeof val === 'string' ? DateTime.fromFormat(val, '${escapeString(fmt)}') : val, z.custom<DateTime>((val) => val instanceof DateTime && val.isValid, { message: 'Must be a time in format ${escapeString(fmt)}' }))`;
}
case 'datetime':
return '_ZodDatetime';
case 'interval':
return '_ZodInterval';
case 'duration': {
const validParts = [`val instanceof Duration && val.isValid`];
if (s.min !== undefined) validParts.push(`val.toMillis() >= Duration.fromISO('${s.min}').toMillis()`);
if (s.max !== undefined) validParts.push(`val.toMillis() <= Duration.fromISO('${s.max}').toMillis()`);
const validation = validParts.join(' && ');
let message = 'Must be an ISO 8601 duration';
if (s.min !== undefined && s.max !== undefined) message += ` between ${s.min} and ${s.max}`;
else if (s.min !== undefined) message += ` of at least ${s.min}`;
else if (s.max !== undefined) message += ` of at most ${s.max}`;
return `z.preprocess((val) => typeof val === 'string' ? Duration.fromISO(val) : val, z.custom<Duration>((val) => ${validation}, { message: '${message}' }))`;
}
case 'email':
return 'z.email()';
case 'url':
return 'z.url()';
case 'uuid':
return 'z.uuid()';
case 'unknown':
return 'z.unknown()';
case 'null':
return 'z.null()';
case 'object':
return 'z.record(z.string(), z.unknown())';
case 'binary':
return '_ZodBinary';
case 'json':
return '_ZodJson';
default:
return 'z.unknown()';
}
}
function renderArray(a: ArrayTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {
let e = `z.array(${renderType(a.item, parseCaseTransform, defaultMode)})`;
if (a.min !== undefined) e += `.min(${a.min})`;
if (a.max !== undefined) e += `.max(${a.max})`;
return e;
}
function renderTuple(t: TupleTypeNode): string {
return `z.tuple([${t.items.map(i => renderType(i)).join(', ')}])`;
}
function renderRecord(r: RecordTypeNode): string {
return `z.record(${renderType(r.key)}, ${renderType(r.value)})`;
}
function renderEnum(e: EnumTypeNode): string {
const vals = e.values.map(v => `"${v}"`).join(', ');
return `z.enum([${vals}])`;
}
function renderLiteral(l: LiteralTypeNode): string {
if (typeof l.value === 'string') return `z.literal("${escapeString(l.value)}")`;
return `z.literal(${l.value})`;
}
function renderUnion(u: UnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {
return `z.union([${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;
}
function renderDiscriminatedUnion(u: DiscriminatedUnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {
return `z.discriminatedUnion("${escapeString(u.discriminator)}", [${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;
}
function renderIntersection(i: IntersectionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {
const [first, ...rest] = i.members;
// When the pattern is ref & (ref | inlineObject)*, use .extend() chains to
// produce a single ZodObject. .and() breaks strict objects — each strict side
// rejects the other side's keys during intersection parsing, and ZodIntersection
// has no .strict() method.
Eif (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {
let expr = first.name;
for (const member of rest) {
if (member.kind === 'ref') {
expr += `.extend(${member.name}.shape)`;
} else {
const m = member as InlineObjectTypeNode;
const fieldLines =
parseCaseTransform === 'snake'
? renderFieldsAsSnakeCase(m.fields, defaultMode)
.map(l => ` ${l}`)
.join('\n')
: parseCaseTransform === 'pascal'
? renderFieldsAsPascalCase(m.fields, defaultMode)
.map(l => ` ${l}`)
.join('\n')
: m.fields
.flatMap(f => renderField(f, defaultMode))
.map(l => ` ${l}`)
.join('\n');
expr += `.extend({\n${fieldLines}\n})`;
}
}
return expr;
}
let expr = renderType(first!, parseCaseTransform, defaultMode);
for (const member of rest) {
expr += `.and(${renderType(member, parseCaseTransform, defaultMode)})`;
}
return expr;
}
function renderInlineObject(o: InlineObjectTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {
const wrapper = modeToWrapper(o.mode ?? defaultMode ?? 'strict');
Iif (parseCaseTransform === 'snake') {
const snakeLines = renderFieldsAsSnakeCase(o.fields, defaultMode);
const joined = snakeLines.map(l => ` ${l}`).join('\n');
const transformEntries = o.fields
.map(f => {
const snakeKey = camelToSnake(f.name);
// Optional fields use .nullish() on input; coerce null → undefined in output
const val = f.optional ? `data.${snakeKey} ?? undefined` : `data.${snakeKey}`;
return ` ${quoteKey(f.name)}: ${val},`;
})
.join('\n');
return `${wrapper}({\n${joined}\n}).transform(data => ({\n${transformEntries}\n}))`;
}
if (parseCaseTransform === 'pascal') {
const pascalLines = renderFieldsAsPascalCase(o.fields, defaultMode);
const joined = pascalLines.map(l => ` ${l}`).join('\n');
const transformEntries = o.fields
.map(f => {
const pascalKey = camelToPascal(f.name);
const val = f.optional ? `data.${pascalKey} ?? undefined` : `data.${pascalKey}`;
return ` ${quoteKey(f.name)}: ${val},`;
})
.join('\n');
return `${wrapper}({\n${joined}\n}).transform(data => ({\n${transformEntries}\n}))`;
}
const fields = o.fields
.flatMap(f => renderField(f, defaultMode))
.map(l => ` ${l}`)
.join('\n');
return `${wrapper}({\n${fields}\n})`;
}
// ─── Input type rendering ─────────────────────────────────────────────────
/**
* Like renderScalar, but coerces from string input (JSON wire format).
* Used for Input (write) schemas where data arrives as JSON strings.
*/
function renderInputScalar(s: ScalarTypeNode): string {
return renderScalar(s);
}
/**
* Like renderType, but substitutes model refs with their Input variant
* when the model has visibility modifiers, and coerces scalars from strings.
* Used for Input (write) schema fields so that sub-type references also
* point to their Input variants.
*/
export function renderInputType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {
switch (type.kind) {
case 'scalar':
return renderInputScalar(type);
case 'ref':
return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;
case 'array': {
let e = `z.array(${renderInputType(type.item, modelsWithInput, defaultMode)})`;
Iif (type.min !== undefined) e += `.min(${type.min})`;
Iif (type.max !== undefined) e += `.max(${type.max})`;
return e;
}
case 'tuple':
return `z.tuple([${type.items.map(i => renderInputType(i, modelsWithInput, defaultMode)).join(', ')}])`;
case 'record':
return `z.record(${renderInputType(type.key, modelsWithInput, defaultMode)}, ${renderInputType(type.value, modelsWithInput, defaultMode)})`;
case 'union':
return `z.union([${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;
case 'discriminatedUnion':
return `z.discriminatedUnion("${escapeString(type.discriminator)}", [${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;
case 'intersection': {
const [first, ...rest] = type.members;
Eif (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {
let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;
for (const member of rest) {
if (member.kind === 'ref') {
const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;
expr += `.extend(${name}.shape)`;
} else {
const fieldLines = (member as InlineObjectTypeNode).fields
.map(f => ` ${renderInputField(f, modelsWithInput ?? new Set(), defaultMode)}`)
.join('\n');
expr += `.extend({\n${fieldLines}\n})`;
}
}
return expr;
}
let expr = renderInputType(first!, modelsWithInput, defaultMode);
for (const member of rest) {
expr += `.and(${renderInputType(member, modelsWithInput, defaultMode)})`;
}
return expr;
}
case 'lazy':
return `z.lazy(() => ${renderInputType(type.inner, modelsWithInput, defaultMode)})`;
case 'inlineObject': {
const fields = type.fields
.flatMap(f => renderInputField(f, modelsWithInput ?? new Set(), defaultMode))
.map(l => ` ${l}`)
.join('\n');
return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\n${fields}\n})`;
}
default:
return renderType(type, undefined, defaultMode);
}
}
function renderInputField(field: FieldNode, modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {
const lines: string[] = [];
Iif (field.deprecated) lines.push('/** @deprecated */');
let expr = renderInputType(field.type, modelsWithInput, defaultMode);
Iif (field.nullable) expr += '.nullable()';
if (field.default !== undefined) {
const dv = typeof field.default === 'string' ? `"${escapeString(field.default)}"` : String(field.default);
expr += `.default(${dv})`;
} else if (field.optional) {
expr += '.optional()';
}
Iif (field.description) expr += `.describe("${escapeString(field.description)}")`;
lines.push(`${quoteKey(field.name)}: ${expr},`);
return lines;
}
function renderInputFields(fields: FieldNode[], modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {
return fields.flatMap(f => renderInputField(f, modelsWithInput, defaultMode));
}
// ─── Query type rendering ─────────────────────────────────────────────────
/**
* Like renderType, but wraps array types with z.preprocess to handle
* query strings where a single value arrives as a string instead of a string[].
* Also uses Input variants for model refs when modelsWithInput is provided.
*/
export function renderQueryType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {
switch (type.kind) {
case 'array': {
const inner = modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);
return `z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner})`;
}
case 'inlineObject': {
const fields = type.fields.map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`).join('\n');
return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\n${fields}\n})`;
}
case 'intersection': {
const [first, ...rest] = type.members;
Eif (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {
let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;
for (const member of rest) {
if (member.kind === 'ref') {
const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;
expr += `.extend(${name}.shape)`;
} else {
const fieldLines = (member as InlineObjectTypeNode).fields
.map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`)
.join('\n');
expr += `.extend({\n${fieldLines}\n})`;
}
}
return expr;
}
let expr = renderQueryType(first!, modelsWithInput, defaultMode);
for (const member of rest) {
expr += `.and(${renderQueryType(member, modelsWithInput, defaultMode)})`;
}
return expr;
}
case 'ref':
return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;
default:
return modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);
}
}
function renderQueryField(field: FieldNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {
let expr =
field.type.kind === 'array'
? renderQueryType(field.type, modelsWithInput, defaultMode)
: modelsWithInput
? renderInputType(field.type, modelsWithInput, defaultMode)
: renderType(field.type, undefined, defaultMode);
Iif (field.nullable) expr += '.nullable()';
Iif (field.default !== undefined) {
const dv = typeof field.default === 'string' ? `"${escapeString(field.default)}"` : String(field.default);
expr += `.default(${dv})`;
} else Eif (field.optional) {
expr += '.optional()';
}
Iif (field.description) expr += `.describe("${escapeString(field.description)}")`;
return `${quoteKey(field.name)}: ${expr},`;
}
function isValidIdentifier(name: string): boolean {
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
}
function quoteKey(name: string): string {
return isValidIdentifier(name) ? name : `'${name}'`;
}
// ─── String escaping ──────────────────────────────────────────────────────
function escapeString(s: string): string {
return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
}
// ─── Helpers ───────────────────────────────────────────────────────────────
function rootNeedsDateTime(root: ContractRootNode): boolean {
return root.models.some(m => (m.type && typeNeedsDateTime(m.type)) || m.fields.some(f => typeNeedsDateTime(f.type)));
}
/** Returns true if `type` (recursively) contains a scalar with the given `name`. */
export function typeNeedsScalar(type: ContractTypeNode, name: string): boolean {
switch (type.kind) {
case 'scalar':
return type.name === name;
case 'array':
return typeNeedsScalar(type.item, name);
case 'tuple':
return type.items.some(i => typeNeedsScalar(i, name));
case 'record':
return typeNeedsScalar(type.key, name) || typeNeedsScalar(type.value, name);
case 'union':
return type.members.some(m => typeNeedsScalar(m, name));
case 'discriminatedUnion':
return type.members.some(m => typeNeedsScalar(m, name));
case 'intersection':
return type.members.some(m => typeNeedsScalar(m, name));
case 'lazy':
return typeNeedsScalar(type.inner, name);
case 'inlineObject':
return type.fields.some(f => typeNeedsScalar(f.type, name));
default:
return false;
}
}
/** Returns true if any model in `root` uses a scalar with the given `name`. */
export function rootNeedsScalar(root: ContractRootNode, name: string): boolean {
return root.models.some(m => (m.type && typeNeedsScalar(m.type, name)) || m.fields.some(f => typeNeedsScalar(f.type, name)));
}
/** Returns true if `type` (recursively) contains a `date`, `time`, or `datetime` scalar. */
export function typeNeedsDateTime(type: ContractTypeNode): boolean {
switch (type.kind) {
case 'scalar':
return type.name === 'date' || type.name === 'time' || type.name === 'datetime';
case 'array':
return typeNeedsDateTime(type.item);
case 'union':
return type.members.some(typeNeedsDateTime);
case 'discriminatedUnion':
return type.members.some(typeNeedsDateTime);
case 'intersection':
return type.members.some(typeNeedsDateTime);
case 'inlineObject':
return type.fields.some(f => typeNeedsDateTime(f.type));
default:
return false;
}
}
/** Collect model names referenced in `root` that are not defined locally (need to be imported). */
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?.[0] && !localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);
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 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;
// Type alias: collect Input refs from the aliased type expression.
if (model.type) {
collectInputTypeRefs(model.type, refs, modelsWithInput);
continue;
}
// When a model extends an external parent that has an Input variant,
// the write schema extends ParentInput — so we need to import it.
if (model.bases?.[0] && modelsWithInput.has(model.bases?.[0]) && !localNames.has(model.bases?.[0])) {
refs.add(`${model.bases?.[0]}Input`);
}
const writeFields = model.fields.filter(f => f.visibility !== 'readonly');
for (const field of writeFields) {
collectInputTypeRefs(field.type, refs, modelsWithInput);
}
}
// Remove locally defined Input variants (generated in this file)
for (const name of localNames) {
refs.delete(`${name}Input`);
}
return [...refs].sort();
}
function collectInputTypeRefs(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':
collectInputTypeRefs(type.item, out, modelsWithInput);
break;
case 'tuple':
type.items.forEach(i => collectInputTypeRefs(i, out, modelsWithInput));
break;
case 'record':
collectInputTypeRefs(type.key, out, modelsWithInput);
collectInputTypeRefs(type.value, out, modelsWithInput);
break;
case 'union':
type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));
break;
case 'discriminatedUnion':
type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));
break;
case 'intersection':
type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));
break;
case 'lazy':
collectInputTypeRefs(type.inner, out, modelsWithInput);
break;
case 'inlineObject':
type.fields.forEach(f => collectInputTypeRefs(f.type, out, modelsWithInput));
break;
}
}
/**
* Topologically sort models so dependencies are emitted before dependents.
* Falls back to source order for cycles (which would need z.lazy at runtime).
*/
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]));
// Build adjacency: model name → set of local model names it depends on
const deps = new Map<string, Set<string>>();
for (const model of models) {
const refs = new Set<string>();
if (model.bases?.[0] && localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);
if (model.type) collectTypeRefs(model.type, refs);
for (const field of model.fields) {
collectTypeRefs(field.type, refs);
}
// Keep only local dependencies
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);
}
// Kahn's algorithm
const inDegree = new Map<string, number>();
for (const name of localNames) inDegree.set(name, 0);
for (const [, d] of deps) {
for (const dep of d) {
inDegree.set(dep, (inDegree.get(dep) ?? 0) + 1);
}
}
// Note: inDegree counts how many models *depend on* this model,
// but for Kahn's we need how many dependencies each model has.
// Re-do: inDegree = number of unresolved deps for each model.
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)!);
// Remove this model from all dependents' remaining sets
for (const [other, rem] of remaining) {
if (rem.delete(name) && rem.size === 0) {
queue.push(other);
}
}
}
// Append any models not yet emitted (cycles)
for (const model of models) {
Iif (!sorted.includes(model)) sorted.push(model);
}
return sorted;
}
/**
* Resolve the import path for an external model reference.
* When a codegen context is available, computes the correct relative path
* from the current file to the referenced model's output file.
* Falls back to same-directory PascalCase → dot.case convention.
*/
export function resolveImportPath(refName: string, context?: ContractCodegenContext): string {
if (context) {
const refOutPath = context.modelOutPaths.get(refName);
if (refOutPath) {
const fromDir = dirname(context.currentOutPath);
let rel = relative(fromDir, refOutPath);
// Replace .ts extension with .js for ESM imports
rel = rel.replace(/\.ts$/, '.js');
// Ensure relative path starts with ./ or ../
if (!rel.startsWith('.')) rel = './' + rel;
return rel;
}
}
// Fallback: assume same directory, use PascalCase → dot.case convention
const moduleName = pascalToDotCase(refName);
return `./${moduleName}.js`;
}
/** 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();
}
|