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 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 | 5x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 190x 190x 34x 12x 2x 8x 2x 2x 12x 11x 12x 4x 83x 83x 83x 83x 83x 75x 83x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 83x 5x 83x 83x 83x 83x 83x 83x 83x 83x 88x 95x 95x 89x 89x 89x 83x 83x 83x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 5x 95x 95x 95x 5x 5x 5x 5x 4x 1x 2x 1x 95x 95x 95x 95x 95x 8x 8x 95x 95x 95x 95x 1x 1x 1x 94x 1x 1x 1x 1x 93x 1x 1x 95x 95x 8x 87x 95x 95x 14x 14x 14x 1x 13x 13x 2x 2x 11x 11x 81x 3x 3x 95x 17x 8x 1x 1x 1x 7x 95x 95x 64x 31x 31x 71x 31x 95x 95x 4x 5x 4x 1x 3x 3x 91x 78x 95x 95x 95x 13x 95x 95x 13x 10x 10x 3x 2x 2x 1x 95x 95x 14x 14x 14x 1x 13x 1x 12x 1x 11x 81x 1x 1x 1x 2x 1x 80x 1x 2x 1x 79x 1x 2x 1x 2x 1x 95x 8x 8x 6x 2x 1x 1x 1x 95x 8x 8x 6x 2x 1x 1x 1x 95x 101x 34x 31x 3x 9x 66x 31x 31x 35x 2x 2x 33x 33x 33x 31x 89x 89x 92x 85x 4x 4x 7x 47x 51x 23x 23x 12x 15x 6x 8x 88x 88x 100x 93x 90x 90x 90x 94x 17x 20x 20x 94x 94x 80x 80x 94x 4x 5x 5x 94x 94x 94x 94x 88x 86x 3x 2x 2x 1x 1x 278x 1x 1x 20x 278x 28x 4x 24x 21x 25x 3x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4x 4x 5x 92x 97x 104x 98x 285x 26x 3x 98x 5x 87x 147x 98x 98x 8x 8x 6x 4x 75x 75x 75x 3x 3x 3x 5x 5x 4x 4x 4x 1x 3x 3x 4x 4x 4x 4x 3x 1x 1x 72x 72x 75x 72x 72x 72x 1x 71x 5x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 6x 6x 6x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 6x 6x 6x 6x 7x 7x 7x 6x 6x 6x 2x 6x 6x 6x 6x 5x 5x 5x 5x 6x 6x 6x 5x 6x 6x 6x 6x 6x 5x 6x 18x 6x 6x 6x 10x 10x 10x 10x 10x 10x 10x 11x 11x 11x 11x 10x 10x 10x 10x 10x 5x 10x 6x 10x 10x 10x 10x 5x 10x 6x 10x 10x 10x 10x | import type { OpRootNode, OpRouteNode, OpOperationNode, OpRequestBodyNode, ContractTypeNode, ParamSource } from '@contractkit/core';
import { resolveModifiers, isJsonMime, classifyContentType } from '@contractkit/core';
import { renderInputTsType, renderOutputTsType, quoteKey, headerNameToProperty, JSON_VALUE_TYPE_DECL } from './ts-render.js';
import { pascalToDotCase, typeNeedsScalar } from './codegen-contract.js';
import { bodyTypesStructurallyEqual } from './codegen-operation.js';
import { basename, dirname, relative } from 'path';
// ─── Body strategy ────────────────────────────────────────────────────────
type BodyStrategy =
| { kind: 'none' }
| { kind: 'single'; body: OpRequestBodyNode }
| { kind: 'multi-equal'; bodies: OpRequestBodyNode[] }
| { kind: 'multi-formdata-detect'; bodies: OpRequestBodyNode[] }
| { kind: 'multi-required-arg'; bodies: OpRequestBodyNode[] };
/** Serialize expression for a single MIME, given the source body var (e.g. 'body'). */
function jsonOrFormSerialize(varName: string, contentType: string): string {
if (contentType === 'application/x-www-form-urlencoded') {
return `new URLSearchParams(${varName} as unknown as Record<string, string>).toString()`;
}
Iif (contentType === 'multipart/form-data') {
return `(${varName} as FormData)`;
}
// application/json + any `+json` structured suffix — JSON.stringify with bigint support.
return `JSON.stringify(${varName}, bigIntReplacer)`;
}
/**
* Build a runtime expression that picks the right serialization based on a contentType variable.
* Used by the SDK when the caller passes (or defaults to) a content-type at call time.
*/
function renderSerializeExpr(varName: string, bodies: OpRequestBodyNode[], ctVar: string): string {
// Build a chained ternary, last MIME is the fallback
const arms = bodies.slice(0, -1);
const last = bodies[bodies.length - 1]!;
let expr = jsonOrFormSerialize(varName, last.contentType);
for (let i = arms.length - 1; i >= 0; i--) {
const arm = arms[i]!;
expr = `${ctVar} === '${arm.contentType}' ? ${jsonOrFormSerialize(varName, arm.contentType)} : ${expr}`;
}
return expr;
}
function classifyBodyStrategy(op: OpOperationNode): BodyStrategy {
const bodies = op.request?.bodies ?? [];
if (bodies.length === 0) return { kind: 'none' };
if (bodies.length === 1) return { kind: 'single', body: bodies[0]! };
if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {
return { kind: 'multi-equal', bodies };
}
if (bodies.some(b => b.contentType === 'multipart/form-data')) {
return { kind: 'multi-formdata-detect', bodies };
}
return { kind: 'multi-required-arg', bodies };
}
// ─── Public entry point ────────────────────────────────────────────────────
/** Options shared by every SDK code-generation entry point. */
export interface SdkCodegenOptions {
/** Template for type import paths when `modelOutPaths` is not provided. Supports `{module}` and `{base}`. */
typeImportPathTemplate?: string;
/** Absolute path of the file currently being generated. Used to compute relative imports. */
outPath?: string;
/** Map from model name → absolute output file path (for cross-module type imports) */
modelOutPaths?: Map<string, string>;
/** Absolute path to the shared sdk-options.ts file (if set, imports SdkOptions instead of defining inline) */
sdkOptionsPath?: 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>;
/**
* Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —
* internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`
* to include them (e.g. for an internal-use SDK).
*/
includeInternal?: boolean;
/**
* Override the generated client class name. When omitted, falls back to
* `deriveClientClassName(root.file)` (the legacy per-file name). The aggregator
* uses this to emit `<Area><Subarea>Client` for area+subarea leaf files.
*/
clientClassName?: string;
}
/**
* Returns true if the root contains at least one operation eligible for SDK emission.
* With `includeInternal: false` (default) that means at least one non-internal op; with
* `includeInternal: true` any op qualifies.
*/
export function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {
for (const route of root.routes) {
for (const op of route.operations) {
if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;
}
}
return false;
}
/**
* Generate a complete `*.client.ts` file for one operation root: imports, the client class
* declaration, and one method per public operation. Used for top-level (no-area) files and
* for subarea-leaf files. Area-level files are NOT routed through this — their methods get
* inlined into the SDK aggregator via {@link generateClientMethods} + {@link generateSdkAggregator}.
*/
export function generateSdk(root: OpRootNode, options: SdkCodegenOptions = {}): string {
const lines: string[] = [];
const includeInternal = options.includeInternal ?? false;
const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput, includeInternal);
const clientClassName = options.clientClassName ?? deriveClientClassName(root.file);
// Type-only imports
if (types.length > 0) {
lines.push(...generateTypeImports(types, root.file, options));
}
// SdkOptions import (from shared file) or inline fallback
if (options.sdkOptionsPath && options.outPath) {
let rel = relative(dirname(options.outPath), options.sdkOptionsPath);
rel = rel.replace(/\.ts$/, '.js');
if (!rel.startsWith('.')) rel = './' + rel;
const jsonImport = sdkNeedsJson(root, includeInternal) ? ', JsonValue' : '';
lines.push(`import type { SdkFetch${jsonImport} } from '${rel}';`);
const valueImports: string[] = [];
Iif (sdkNeedsBigIntReplacer(root, includeInternal)) valueImports.push('bigIntReplacer');
if (sdkNeedsBigIntReviver(root, includeInternal)) valueImports.push('parseJson');
Iif (sdkNeedsQueryString(root, includeInternal)) valueImports.push('buildQueryString');
if (valueImports.length > 0) {
lines.push(`import { ${valueImports.join(', ')} } from '${rel}';`);
}
} else {
lines.push('');
lines.push('export class SdkError extends Error {');
lines.push(' constructor(');
lines.push(' public readonly status: number,');
lines.push(' public readonly statusText: string,');
lines.push(' public readonly body: unknown,');
lines.push(' public readonly headers: Headers,');
lines.push(' ) {');
lines.push(' super(`${status} ${statusText}`);');
lines.push(" this.name = 'SdkError';");
lines.push(' }');
lines.push('}');
lines.push('');
lines.push('export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;');
lines.push('');
lines.push('export interface SdkOptions {');
lines.push(' baseUrl: string;');
lines.push(' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);');
lines.push(' fetch?: SdkFetch;');
lines.push(' /** Called once per request to produce a unique X-Request-ID header value */');
lines.push(' requestIdFactory?: () => string;');
lines.push('}');
lines.push('');
lines.push('export function createSdkFetch(options: SdkOptions): SdkFetch {');
lines.push(' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());');
lines.push(' return async (url: string, init: RequestInit): Promise<Response> => {');
lines.push(" const baseHeaders = typeof options.headers === 'function'");
lines.push(' ? await options.headers()');
lines.push(' : options.headers ?? {};');
lines.push(' const res = await fetch(`${options.baseUrl}${url}`, {');
lines.push(' ...init,');
lines.push(" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },");
lines.push(' });');
lines.push(' if (!res.ok) {');
lines.push(' const text = await res.text();');
lines.push(' let body: unknown;');
lines.push(' try { body = JSON.parse(text); } catch { body = text; }');
lines.push(' throw new SdkError(res.status, res.statusText, body, res.headers);');
lines.push(' }');
lines.push(' return res;');
lines.push(' };');
lines.push('}');
lines.push('');
lines.push('export function buildQueryString(query: object | undefined): string {');
lines.push(' const searchParams = new URLSearchParams();');
lines.push(' if (query) {');
lines.push(' for (const [k, v] of Object.entries(query)) {');
lines.push(' if (v === undefined || v === null) continue;');
lines.push(' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }');
lines.push(' else searchParams.set(k, String(v));');
lines.push(' }');
lines.push(' }');
lines.push(' const qs = searchParams.toString();');
lines.push(" return qs ? `?${qs}` : '';");
lines.push('}');
lines.push('');
lines.push('export async function parseJson<T>(res: Response): Promise<T> {');
lines.push(' return JSON.parse(await res.text(), bigIntReviver) as T;');
lines.push('}');
}
if (sdkNeedsJson(root, includeInternal) && !(options.sdkOptionsPath && options.outPath)) {
lines.push(JSON_VALUE_TYPE_DECL);
}
lines.push('');
// Client class
lines.push('/**');
const relFile = options.outPath ? relative(dirname(options.outPath), root.file) : root.file;
lines.push(` * generated from [${basename(root.file)}](file://./${relFile})`);
lines.push(' */');
lines.push(`export class ${clientClassName} {`);
lines.push(' constructor(private fetch: SdkFetch) {}');
for (const route of root.routes) {
for (const op of route.operations) {
const mods = resolveModifiers(route, op);
if (!includeInternal && mods.includes('internal')) continue;
lines.push('');
if (mods.includes('deprecated')) lines.push(' /** @deprecated */');
lines.push(...generateMethod(route, op, root.file, options));
}
}
lines.push('}');
lines.push('');
return lines.join('\n');
}
/**
* Render the method-block lines for an operation file as if they were declared inside a
* client class. Returns one consolidated array of strings (each pre-indented for class body
* level, with leading blank lines between methods) plus the set of method names emitted —
* the caller uses the names to detect cross-file collisions when multiple files contribute
* to the same area-level client.
*
* Skips operations marked `internal` unless `options.includeInternal` is set.
*/
export function generateClientMethods(
root: OpRootNode,
options: SdkCodegenOptions,
): { lines: string[]; methodNames: string[] } {
const lines: string[] = [];
const methodNames: string[] = [];
const includeInternal = options.includeInternal ?? false;
for (const route of root.routes) {
for (const op of route.operations) {
const mods = resolveModifiers(route, op);
Iif (!includeInternal && mods.includes('internal')) continue;
lines.push('');
Iif (mods.includes('deprecated')) lines.push(' /** @deprecated */');
lines.push(...generateMethod(route, op, root.file, options));
methodNames.push(deriveMethodName(op, route));
}
}
return { lines, methodNames };
}
// ─── Method generation ────────────────────────────────────────────────────
function generateMethod(route: OpRouteNode, op: OpOperationNode, file: string, options: SdkCodegenOptions): string[] {
const lines: string[] = [];
const methodName = deriveMethodName(op, route);
const httpMethod = op.method.toUpperCase();
const { modelsWithInput, modelsWithOutput } = options;
// Build method parameters (request-side — use Input variants)
const params = buildMethodParams(route, op, modelsWithInput);
const paramStr = params.map(p => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ');
// Determine return type — response side uses Output variants (post-transform wire shape).
// For non-JSON responses the schema is ignored: text/* is read as string, binary as Blob.
const primaryResponse = op.responses.find(r => r.bodyType) ?? op.responses[0];
const isVoid = !primaryResponse?.bodyType;
const respCategory = primaryResponse?.contentType ? classifyContentType(primaryResponse.contentType) : 'json';
const dataType = isVoid
? 'void'
: respCategory === 'text'
? 'string'
: respCategory === 'binary'
? 'Blob'
: renderOutputTsType(primaryResponse!.bodyType!, modelsWithOutput);
const respHeaders = primaryResponse?.headers ?? [];
const hasRespHeaders = respHeaders.length > 0;
const headersShape = hasRespHeaders
? `{ ${respHeaders.map(h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput)}`).join('; ')} }`
: '';
const returnType = hasRespHeaders ? (isVoid ? `{ headers: ${headersShape} }` : `{ data: ${dataType}; headers: ${headersShape} }`) : dataType;
// JSDoc
const desc = op.description ?? route.description;
if (op.name || desc) {
const tags: string[] = [];
if (op.name) tags.push(`@name ${op.name}`);
if (desc) tags.push(`@description ${desc}`);
if (tags.length === 1) {
lines.push(` /** ${tags[0]} */`);
} else {
lines.push(` /**`);
for (const tag of tags) lines.push(` * ${tag}`);
lines.push(` */`);
}
}
lines.push(` async ${methodName}(${paramStr}): Promise<${returnType}> {`);
// Build URL with path params
const urlExpr = buildUrlExpression(route.path, route.params);
// Query string
const hasQuery = !!op.query;
let fetchUrl = urlExpr;
if (hasQuery) {
lines.push(` const qs = buildQueryString(query);`);
fetchUrl = urlExpr;
}
// Build fetch options
const strategy = classifyBodyStrategy(op);
const hasBody = strategy.kind !== 'none';
const hasOpHeaders = !!op.headers;
// Pre-emit serialization preludes for multi-MIME strategies
if (strategy.kind === 'multi-equal') {
const defaultCt = strategy.bodies[0]!.contentType;
lines.push(` const __contentType = options?.contentType ?? '${defaultCt}';`);
lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);
} else if (strategy.kind === 'multi-formdata-detect') {
lines.push(` const __isFormData = body instanceof FormData;`);
const nonMultipart = strategy.bodies.find(b => b.contentType !== 'multipart/form-data')!;
lines.push(` const __contentType: string = __isFormData ? 'multipart/form-data' : '${nonMultipart.contentType}';`);
lines.push(
` const __serialized: BodyInit = __isFormData ? (body as FormData) : ${jsonOrFormSerialize('body', nonMultipart.contentType)};`,
);
} else if (strategy.kind === 'multi-required-arg') {
lines.push(` const __contentType = options.contentType;`);
lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);
}
const fetchArgs: string[] = [];
if (hasQuery) {
fetchArgs.push(`url: \`${fetchUrl}\${qs}\``);
} else {
fetchArgs.push(`url: \`${fetchUrl}\``);
}
fetchArgs.push(`method: '${httpMethod}'`);
if (strategy.kind === 'single') {
const body = strategy.body;
const cat = classifyContentType(body.contentType);
if (cat === 'multipart') {
// FormData supplies its own Content-Type with boundary; don't override it.
fetchArgs.push('body: body');
} else Iif (cat === 'urlencoded') {
fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);
fetchArgs.push('body: new URLSearchParams(body as unknown as Record<string, string>).toString()');
} else if (cat === 'text' || cat === 'binary') {
// text/* and binary mimes pass the body through to fetch as-is — no schema serialization.
fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);
fetchArgs.push('body: body');
} else {
fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);
fetchArgs.push('body: JSON.stringify(body, bigIntReplacer)');
}
} else if (hasBody) {
// multi-equal | multi-formdata-detect | multi-required-arg — share a __contentType / __serialized prelude
fetchArgs.push(`headers: { 'Content-Type': __contentType }`);
fetchArgs.push('body: __serialized');
}
if (hasOpHeaders) {
const lastHeaderIdx = fetchArgs.findIndex(a => a.startsWith('headers:'));
if (lastHeaderIdx !== -1) {
const existing = fetchArgs[lastHeaderIdx]!;
const inner = existing.slice('headers: '.length).replace(/^\{\s*|\s*\}$/g, '');
fetchArgs[lastHeaderIdx] = `headers: { ${inner}, ...customHeaders }`;
} else {
fetchArgs.push('headers: customHeaders');
}
}
const resultPrefix = isVoid && !hasRespHeaders ? '' : 'const result = ';
if (fetchArgs.length === 2 && !hasBody && !hasOpHeaders && !hasQuery) {
// Simple case — inline
lines.push(` ${resultPrefix}await this.fetch(\`${fetchUrl}\`, { method: '${httpMethod}' });`);
} else {
lines.push(` ${resultPrefix}await this.fetch(${fetchArgs[0]!.split(': ').slice(1).join(': ')}, {`);
for (let i = 1; i < fetchArgs.length; i++) {
lines.push(` ${fetchArgs[i]},`);
}
lines.push(` });`);
}
const readBodyExpr =
respCategory === 'text' ? `await result.text()` : respCategory === 'binary' ? `await result.blob()` : `await parseJson<${dataType}>(result)`;
if (hasRespHeaders) {
const headerEntries = respHeaders
.map(h => `${quoteKey(headerNameToProperty(h.name))}: result.headers.get('${h.name}') ?? undefined`)
.join(', ');
if (isVoid) {
lines.push(` return { headers: { ${headerEntries} } };`);
} else {
lines.push(` const data = ${readBodyExpr};`);
lines.push(` return { data, headers: { ${headerEntries} } };`);
}
} else if (!isVoid) {
lines.push(` return ${readBodyExpr};`);
}
lines.push(' }');
return lines;
}
// ─── URL building ─────────────────────────────────────────────────────────
function buildUrlExpression(path: string, _?: ParamSource): string {
// Replace {paramName} with ${encodeURIComponent(paramName)}
return path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_match, name) => {
return `\${encodeURIComponent(${name})}`;
});
}
// ─── Method parameters ────────────────────────────────────────────────────
interface MethodParam {
name: string;
type: string;
optional: boolean;
}
function buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {
const params: MethodParam[] = [];
// Path params — always first, always required (request-side — use Input variants)
if (route.params) {
if (route.params.kind === 'params') {
for (const p of route.params.nodes) {
params.push({ name: p.name, type: renderInputTsType(p.type, modelsWithInput), optional: false });
}
} else if (route.params.kind === 'ref') {
const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;
params.push({ name: 'params', type: typeName, optional: false });
} else {
params.push({ name: 'params', type: renderInputTsType(route.params.node, modelsWithInput), optional: false });
}
}
// Body (request-side — use Input variants)
const strategy = classifyBodyStrategy(op);
if (strategy.kind === 'single') {
const body = strategy.body;
const cat = classifyContentType(body.contentType);
if (cat === 'multipart') {
params.push({ name: 'body', type: 'FormData', optional: false });
} else if (cat === 'text') {
params.push({ name: 'body', type: 'string', optional: false });
} else if (cat === 'binary') {
params.push({ name: 'body', type: 'Blob | ArrayBuffer | Uint8Array | string', optional: false });
} else {
params.push({ name: 'body', type: renderInputTsType(body.bodyType, modelsWithInput), optional: false });
}
} else if (strategy.kind === 'multi-equal') {
const bodies = strategy.bodies;
const bodyType = renderInputTsType(bodies[0]!.bodyType, modelsWithInput);
params.push({ name: 'body', type: bodyType, optional: false });
const ctUnion = bodies.map(b => `'${b.contentType}'`).join(' | ');
params.push({ name: 'options', type: `{ contentType?: ${ctUnion} }`, optional: true });
} else if (strategy.kind === 'multi-formdata-detect') {
const types = strategy.bodies
.map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))
.join(' | ');
params.push({ name: 'body', type: types, optional: false });
} else if (strategy.kind === 'multi-required-arg') {
const types = strategy.bodies
.map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))
.join(' | ');
params.push({ name: 'body', type: types, optional: false });
const ctUnion = strategy.bodies.map(b => `'${b.contentType}'`).join(' | ');
params.push({ name: 'options', type: `{ contentType: ${ctUnion} }`, optional: false });
}
// Query (request-side — use Input variants)
if (op.query) {
if (op.query.kind === 'params') {
const fields = op.query.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');
params.push({ name: 'query', type: `{ ${fields} }`, optional: true });
} else if (op.query.kind === 'ref') {
const typeName = modelsWithInput?.has(op.query.name) ? `${op.query.name}Input` : op.query.name;
params.push({ name: 'query', type: typeName, optional: true });
} else {
params.push({ name: 'query', type: renderInputTsType(op.query.node, modelsWithInput), optional: true });
}
}
// Headers (request-side — use Input variants)
if (op.headers) {
if (op.headers.kind === 'params') {
const fields = op.headers.nodes.map(p => `${quoteKey(p.name)}?: ${renderInputTsType(p.type, modelsWithInput)}`).join('; ');
params.push({ name: 'customHeaders', type: `{ ${fields} }`, optional: true });
} else if (op.headers.kind === 'ref') {
const typeName = modelsWithInput?.has(op.headers.name) ? `${op.headers.name}Input` : op.headers.name;
params.push({ name: 'customHeaders', type: typeName, optional: true });
} else {
params.push({ name: 'customHeaders', type: renderInputTsType(op.headers.node, modelsWithInput), optional: true });
}
}
return params;
}
// ─── Method name inference ────────────────────────────────────────────────
function deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {
if (op.sdk) return op.sdk;
if (op.name) return nameToMethodName(op.name);
return inferMethodName(op.method, route.path);
}
function nameToMethodName(name: string): string {
const parts = name.split(/[\s\-_]+/).filter(Boolean);
return parts.map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join('');
}
function inferMethodName(method: string, path: string): string {
// Build a name from the path segments + method
// e.g. GET /users/:id → getUsersById
// e.g. POST /users → postUsers
// e.g. DELETE /users/:id → deleteUsersById
const segments = path.split('/').filter(s => s.length > 0);
const parts: string[] = [method.toLowerCase()];
for (const seg of segments) {
if (seg.startsWith('{')) {
// {id} → ById, {accountId} → ByAccountId
const paramName = seg.slice(1, -1);
parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));
} else {
// Regular segment — camelCase it
const segParts = seg.split(/[.-]/).filter(Boolean);
for (const sp of segParts) {
parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));
}
}
}
return parts[0]! + parts.slice(1).join('');
}
// ─── Naming conventions ────────────────────────────────────────────────────
function deriveBaseName(file: string): string {
const base =
file
.split('/')
.pop()
?.replace(/\.(op|ck)$/, '') ?? 'Resource';
return base
.split('.')
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join('');
}
/** Derive a client class name from a `.ck` file path, e.g. `users.ck` → `UsersClient`. Used for legacy flat (no-area) files. */
export function deriveClientClassName(file: string): string {
return `${deriveBaseName(file)}Client`;
}
/** Camel-cased property name for a flat client on the SDK aggregator, e.g. `users.ck` → `users`. */
export function deriveClientPropertyName(file: string): string {
const base = deriveBaseName(file);
return base.charAt(0).toLowerCase() + base.slice(1);
}
/**
* Pull `area` / `subarea` from a file's `root.meta` (set via `options { keys: { ... } }`).
* Both are optional. `area` drives top-level SDK grouping; `subarea` drives nesting under
* an area's client class.
*/
export function getAreaSubarea(root: OpRootNode): { area?: string; subarea?: string } {
return { area: root.meta?.area, subarea: root.meta?.subarea };
}
function pascal(value: string): string {
return value
.split(/[-_\s]+/)
.filter(Boolean)
.map(s => s.charAt(0).toUpperCase() + s.slice(1))
.join('');
}
function camel(value: string): string {
const p = pascal(value);
return p.charAt(0).toLowerCase() + p.slice(1);
}
/** Class name for the area-level client, e.g. `area=identity` → `IdentityClient`. */
export function deriveAreaClientClassName(area: string): string {
return `${pascal(area)}Client`;
}
/** Property name on the SDK aggregator for an area, e.g. `area=identity` → `identity`. */
export function deriveAreaPropertyName(area: string): string {
return camel(area);
}
/** Class name for a leaf subarea client, e.g. `(identity, invitations)` → `IdentityInvitationsClient`. */
export function deriveSubareaClientClassName(area: string, subarea: string): string {
return `${pascal(area)}${pascal(subarea)}Client`;
}
/** Property name on the area client for a subarea, e.g. `subarea=invitations` → `invitations`. */
export function deriveSubareaPropertyName(subarea: string): string {
return camel(subarea);
}
// ─── Type collection ──────────────────────────────────────────────────────
function collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>, includeInternal = false): string[] {
const types = new Set<string>();
for (const route of root.routes) {
const publicOps = route.operations.filter(op => includeInternal || !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);
}
if (resp.headers) {
for (const h of resp.headers) {
collectTypeNodeRefs(h.type, types);
collectOutputTypeNodeRefs(h.type, 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':
Eif (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') {
Eif (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);
} else Eif (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 {
Eif (!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') {
Eif (/^[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);
}
}
/** True if any emitted operation has query params (drives the `buildQueryString` import). */
function sdkNeedsQueryString(root: OpRootNode, includeInternal = false): boolean {
for (const route of root.routes) {
for (const op of route.operations) {
Iif (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
Iif (op.query) return true;
}
}
return false;
}
/** True if any emitted operation serializes a JSON request body (uses bigIntReplacer). */
function sdkNeedsBigIntReplacer(root: OpRootNode, includeInternal = false): boolean {
for (const route of root.routes) {
for (const op of route.operations) {
Iif (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
Iif (op.request && op.request.bodies.some(b => isJsonMime(b.contentType))) return true;
}
}
return false;
}
/** True if any public operation parses a JSON response body (uses bigIntReviver). */
function sdkNeedsBigIntReviver(root: OpRootNode, includeInternal = false): boolean {
for (const route of root.routes) {
for (const op of route.operations) {
Iif (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
if (
op.responses.some(r => {
if (!r.bodyType) return false;
// Only JSON-shaped responses use parseJson — text/binary read raw.
return !r.contentType || classifyContentType(r.contentType) === 'json';
})
) {
return true;
}
}
}
return false;
}
function sdkNeedsJson(root: OpRootNode, includeInternal = false): boolean {
for (const route of root.routes) {
for (const op of route.operations) {
if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
const check = (src: ParamSource | undefined) => {
if (!src || src.kind === 'ref') return false;
if (src.kind === 'params') return src.nodes.some(p => typeNeedsScalar(p.type, 'json'));
return typeNeedsScalar(src.node, 'json');
};
if (
!!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, 'json')) ||
op.responses.some(r => r.bodyType && typeNeedsScalar(r.bodyType, 'json')) ||
check(op.query) ||
check(op.headers) ||
check(route.params)
)
return true;
}
}
return false;
}
function collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {
switch (type.kind) {
case 'ref':
Eif (/^[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;
}
}
// ─── Type import resolution ───────────────────────────────────────────────
function generateTypeImports(types: string[], opFile: string, options: SdkCodegenOptions): string[] {
const lines: string[] = [];
const { modelOutPaths, outPath } = options;
if (modelOutPaths && outPath) {
const byFile = new Map<string, string[]>();
const unresolved: string[] = [];
for (const type of types) {
const typeOutPath = modelOutPaths.get(type);
if (typeOutPath) {
const group = byFile.get(typeOutPath) ?? [];
group.push(type);
byFile.set(typeOutPath, group);
} else {
unresolved.push(type);
}
}
const fromDir = dirname(outPath);
for (const [typeOutPath, names] of byFile) {
let rel = relative(fromDir, typeOutPath);
rel = rel.replace(/\.ts$/, '.js');
if (!rel.startsWith('.')) rel = './' + rel;
lines.push(`import type { ${names.sort().join(', ')} } from '${rel}';`);
}
for (const type of unresolved) {
const moduleName = pascalToDotCase(type);
lines.push(`import type { ${type} } from './${moduleName}.js';`);
}
} else {
const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);
lines.push(`import type { ${types.join(', ')} } from '${typeImport}';`);
}
return lines;
}
function deriveTypeImportPath(file: string, template?: string): string {
const base =
file
.split('/')
.pop()
?.replace(/\.(op|ck)$/, '') ?? 'resource';
const module = base.split('.')[0] ?? base;
if (template) {
return template.replace(/\{module\}/g, module).replace(/\{base\}/g, base);
}
return `#modules/${module}/types/index.js`;
}
// ─── Shared SDK files ──────────────────────────────────────────────────────
/** Generate the shared SdkOptions interface file. */
export function generateSdkOptions(): string {
return [
'export class SdkError extends Error {',
' constructor(',
' public readonly status: number,',
' public readonly statusText: string,',
' public readonly body: unknown,',
' public readonly headers: Headers,',
' ) {',
' super(`${status} ${statusText}`);',
" this.name = 'SdkError';",
' }',
'}',
'',
'export type SdkFetch = (url: string, init: RequestInit) => Promise<Response>;',
'',
'export interface SdkOptions {',
' baseUrl: string;',
' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);',
' fetch?: SdkFetch;',
' /** Called once per request to produce a unique X-Request-ID header value */',
' requestIdFactory?: () => string;',
'}',
'',
'export const bigIntReplacer = (_: string, value: any): any => {',
" if (typeof value === 'bigint') {",
" return value.toString() + 'n';",
' }',
' return value;',
'};',
'',
'export const bigIntReviver = (_: string, value: any): any => {',
" if (typeof value === 'string' && /^-?\\d+n$/.test(value)) {",
' return BigInt(value.slice(0, -1));',
' }',
' return value;',
'};',
'',
JSON_VALUE_TYPE_DECL,
'',
'export function createSdkFetch(options: SdkOptions): SdkFetch {',
' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());',
' return async (url: string, init: RequestInit): Promise<Response> => {',
" const baseHeaders = typeof options.headers === 'function'",
' ? await options.headers()',
' : options.headers ?? {};',
' const res = await fetch(`${options.baseUrl}${url}`, {',
' ...init,',
" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },",
' });',
' if (!res.ok) {',
' const text = await res.text();',
' let body: unknown;',
' try { body = JSON.parse(text); } catch { body = text; }',
' throw new SdkError(res.status, res.statusText, body, res.headers);',
' }',
' return res;',
' };',
'}',
'',
'export function buildQueryString(query: object | undefined): string {',
' const searchParams = new URLSearchParams();',
' if (query) {',
' for (const [k, v] of Object.entries(query)) {',
' if (v === undefined || v === null) continue;',
' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }',
' else searchParams.set(k, String(v));',
' }',
' }',
' const qs = searchParams.toString();',
" return qs ? `?${qs}` : '';",
'}',
'',
'export async function parseJson<T>(res: Response): Promise<T> {',
' return JSON.parse(await res.text(), bigIntReviver) as T;',
'}',
'',
].join('\n');
}
/**
* Reference to a per-file leaf client emitted to its own `*.client.ts`. Used by the
* aggregator to import the class and wire it as either a top-level `sdk.<prop>` or a
* nested `sdk.<area>.<subarea>` property.
*/
export interface SdkClientInfo {
/** Client class name (e.g. `UsersClient`, `IdentityInvitationsClient`). */
className: string;
/** Property name to expose this client under (e.g. `users`, `invitations`). */
propertyName: string;
/** Module specifier for the leaf file, relative to `sdk.ts` and `.js`-suffixed. */
importPath: string;
}
/**
* One area-level (no-subarea) `.ck` file whose methods are merged into the area's
* `<Area>Client` (emitted to its own `<area>.client.ts`).
*/
export interface SdkAreaInlineFile {
/** Parsed AST. */
root: OpRootNode;
/** Codegen options for this file (must have `outPath` pointing at the area client file so type-import paths resolve correctly). */
codegenOptions: SdkCodegenOptions;
}
/** A grouping of files that share the same `keys.area`. */
export interface SdkAreaInfo {
area: string;
/**
* Reference to the `<Area>Client` class — the file that holds it lives at
* `client.importPath` (relative to `sdk.ts`) and is generated separately by
* {@link generateAreaClient}. The aggregator just imports it.
*/
client: SdkClientInfo;
}
export interface SdkAggregatorInput {
/** Files with no `keys.area` — kept as flat `Sdk.<filename>` properties (legacy behavior). */
topLevelClients: SdkClientInfo[];
/** One entry per `keys.area`. */
areas: SdkAreaInfo[];
/** Path to `sdk-options.ts` to import `SdkOptions`/`createSdkFetch`/etc. from. */
sdkOptionsImportPath?: string;
/** Name of the top-level aggregator class. Defaults to `Sdk`. */
sdkClassName?: string;
}
/** Inputs to {@link generateAreaClient}. */
export interface AreaClientInput {
/** Area name (e.g. `payments`). Drives the generated class name (`PaymentsClient`). */
area: string;
/** Output path of the generated `<area>.client.ts` file. Used to resolve relative type / leaf-client / sdk-options imports. */
outPath: string;
/** Files contributing inlined methods to the area client (typically area-level files with no subarea). */
inlineFiles: SdkAreaInlineFile[];
/** Subarea leaf clients exposed as named properties on the area client. */
subareaClients: { propertyName: string; client: SdkClientInfo }[];
/** Path to `sdk-options.ts`, used for `SdkFetch` and runtime helpers. */
sdkOptionsPath: string;
}
/**
* Generate a complete `<area>.client.ts` file: the `<Area>Client` class with
* subarea property fields, a constructor that wires them, and inlined methods
* merged from every area-level file in `inlineFiles`.
*
* Emitted by the plugin alongside the per-leaf `*.client.ts` files. The SDK
* aggregator just imports the resulting class — see {@link generateSdkAggregator}.
*
* @throws if two area-level files contribute the same method name to the area —
* disambiguate via `sdk:` on the operation, or move one into a subarea.
*/
export function generateAreaClient(input: AreaClientInput): string {
const { area, outPath, inlineFiles, subareaClients, sdkOptionsPath } = input;
const className = deriveAreaClientClassName(area);
// ── Merge inputs across all inline files ────────────────────────────────
const collectedMethodLines: string[] = [];
const seenMethods = new Set<string>();
const typesByImportPath = new Map<string, Set<string>>();
const unresolvedTypes = new Set<string>();
let needsJson = false;
let needsBigIntReplacer = false;
let needsBigIntReviver = false;
let needsQueryString = false;
for (const inline of inlineFiles) {
const includeInternal = inline.codegenOptions.includeInternal ?? false;
const { lines: methodLines, methodNames } = generateClientMethods(inline.root, inline.codegenOptions);
for (const name of methodNames) {
if (seenMethods.has(name)) {
throw new Error(
`[sdk] duplicate method '${name}' in area '${area}': two area-level files contribute the same method. Disambiguate via 'sdk:' or move one into a subarea.`,
);
}
seenMethods.add(name);
}
collectedMethodLines.push(...methodLines);
Iif (sdkNeedsJson(inline.root, includeInternal)) needsJson = true;
Iif (sdkNeedsBigIntReplacer(inline.root, includeInternal)) needsBigIntReplacer = true;
if (sdkNeedsBigIntReviver(inline.root, includeInternal)) needsBigIntReviver = true;
Iif (sdkNeedsQueryString(inline.root, includeInternal)) needsQueryString = true;
// Resolve each file's type refs against THIS file's modelOutPaths, but
// produce import paths relative to the area client's outPath (not the
// contributing file's outPath, which pointed at the now-defunct sdk.ts).
const typesForFile = collectTypes(
inline.root,
inline.codegenOptions.modelsWithInput,
inline.codegenOptions.modelsWithOutput,
includeInternal,
);
const { modelOutPaths } = inline.codegenOptions;
if (modelOutPaths) {
const fromDir = dirname(outPath);
for (const t of typesForFile) {
const typeOutPath = modelOutPaths.get(t);
if (typeOutPath) {
let rel = relative(fromDir, typeOutPath).replace(/\.ts$/, '.js');
if (!rel.startsWith('.')) rel = './' + rel;
const set = typesByImportPath.get(rel) ?? new Set();
set.add(t);
typesByImportPath.set(rel, set);
} else {
unresolvedTypes.add(t);
}
}
}
}
// ── Imports ─────────────────────────────────────────────────────────────
let sdkOptionsRel = relative(dirname(outPath), sdkOptionsPath).replace(/\.ts$/, '.js');
Iif (!sdkOptionsRel.startsWith('.')) sdkOptionsRel = './' + sdkOptionsRel;
const lines: string[] = [];
const jsonImport = needsJson ? ', JsonValue' : '';
lines.push(`import type { SdkFetch${jsonImport} } from '${sdkOptionsRel}';`);
const valueImports: string[] = [];
Iif (needsBigIntReplacer) valueImports.push('bigIntReplacer');
if (needsBigIntReviver) valueImports.push('parseJson');
Iif (needsQueryString) valueImports.push('buildQueryString');
if (valueImports.length > 0) {
lines.push(`import { ${valueImports.join(', ')} } from '${sdkOptionsRel}';`);
}
for (const path of [...typesByImportPath.keys()].sort()) {
const names = [...typesByImportPath.get(path)!].sort();
lines.push(`import type { ${names.join(', ')} } from '${path}';`);
}
for (const t of [...unresolvedTypes].sort()) {
lines.push(`import type { ${t} } from './${pascalToDotCase(t)}.js';`);
}
// Leaf client imports (subareas only — top-level clients live next to sdk.ts).
const importedClients = new Set<string>();
for (const sc of subareaClients) {
const key = `${sc.client.className}|${sc.client.importPath}`;
Iif (importedClients.has(key)) continue;
importedClients.add(key);
lines.push(`import { ${sc.client.className} } from '${sc.client.importPath}';`);
}
lines.push('');
// ── <Area>Client class ──────────────────────────────────────────────────
lines.push(`export class ${className} {`);
for (const sc of subareaClients) {
lines.push(` readonly ${sc.propertyName}: ${sc.client.className};`);
}
if (subareaClients.length > 0) lines.push('');
Eif (collectedMethodLines.length > 0 || subareaClients.length > 0) {
const fetchModifier = collectedMethodLines.length > 0 ? 'private ' : '';
lines.push(` constructor(${fetchModifier}fetch: SdkFetch) {`);
for (const sc of subareaClients) {
lines.push(` this.${sc.propertyName} = new ${sc.client.className}(fetch);`);
}
lines.push(' }');
}
for (const ln of collectedMethodLines) lines.push(ln);
lines.push('}');
lines.push('');
return lines.join('\n');
}
/**
* Generate the SDK aggregator (`sdk.ts`) — the entry-point file consumers import.
*
* Imports every `<Area>Client` (one per area, generated by {@link generateAreaClient}
* to its own `<area>.client.ts`) and every leaf top-level client, then emits a
* `class Sdk` that exposes them as properties.
*/
export function generateSdkAggregator(input: SdkAggregatorInput): string {
const sdkOptionsImportPath = input.sdkOptionsImportPath ?? './sdk-options.js';
const sdkClassName = input.sdkClassName ?? 'Sdk';
const lines: string[] = [];
lines.push(`import type { SdkOptions } from '${sdkOptionsImportPath}';`);
lines.push(`import { createSdkFetch } from '${sdkOptionsImportPath}';`);
const importedClients = new Set<string>();
const pushClientImport = (c: SdkClientInfo): void => {
const key = `${c.className}|${c.importPath}`;
Iif (importedClients.has(key)) return;
importedClients.add(key);
lines.push(`import { ${c.className} } from '${c.importPath}';`);
};
// Areas first, then top-level — keeps the aggregator's import order stable.
for (const area of input.areas) pushClientImport(area.client);
for (const c of input.topLevelClients) pushClientImport(c);
lines.push('');
lines.push(`export class ${sdkClassName} {`);
for (const area of input.areas) {
lines.push(` readonly ${deriveAreaPropertyName(area.area)}: ${area.client.className};`);
}
for (const c of input.topLevelClients) {
lines.push(` readonly ${c.propertyName}: ${c.className};`);
}
lines.push('');
lines.push(' constructor(options: SdkOptions) {');
lines.push(' const sdkFetch = options.fetch ?? createSdkFetch(options);');
for (const area of input.areas) {
lines.push(` this.${deriveAreaPropertyName(area.area)} = new ${area.client.className}(sdkFetch);`);
}
for (const c of input.topLevelClients) {
lines.push(` this.${c.propertyName} = new ${c.className}(sdkFetch);`);
}
lines.push(' }');
lines.push('}');
lines.push('');
return lines.join('\n');
}
|