@contractkit/plugin-typescript 0.34.1 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build$colon$ci.log +5 -5
- package/.turbo/turbo-test$colon$ci.log +25 -18
- package/CHANGELOG.md +56 -0
- package/README.md +4 -3
- package/dist/codegen-mcp.d.ts +8 -1
- package/dist/codegen-mcp.d.ts.map +1 -1
- package/dist/codegen-operation.d.ts +13 -5
- package/dist/codegen-operation.d.ts.map +1 -1
- package/dist/index.d.ts +12 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +370 -91
- package/dist/index.js.map +1 -1
- package/dist/server-framework-fastify.d.ts +8 -0
- package/dist/server-framework-fastify.d.ts.map +1 -0
- package/dist/server-framework-koa.d.ts +7 -0
- package/dist/server-framework-koa.d.ts.map +1 -0
- package/dist/server-framework.d.ts +101 -0
- package/dist/server-framework.d.ts.map +1 -0
- package/llms.txt +1 -1
- package/package.json +2 -2
- package/src/codegen-mcp.ts +11 -25
- package/src/codegen-operation.ts +146 -77
- package/src/index.ts +37 -5
- package/src/server-framework-fastify.ts +128 -0
- package/src/server-framework-koa.ts +114 -0
- package/src/server-framework.ts +129 -0
- package/tests/codegen-mcp.test.ts +12 -0
- package/tests/codegen-operation-framework.test.ts +184 -0
- package/tests/codegen-operation.test.ts +74 -0
- package/tests/codegen-server.test.ts +56 -0
- package/tests/server-framework-fastify.test.ts +148 -0
- package/tests/server-framework-koa.test.ts +115 -0
- package/tests/server-framework.test.ts +25 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/codegen-contract.ts","../src/ts-render.ts","../src/decimal-runtime.ts","../src/codegen-revive.ts","../src/codegen-operation.ts","../src/codegen-sdk.ts","../src/codegen-plain-types.ts","../src/codegen-mcp.ts","../src/path-utils.ts"],"sourcesContent":["import { resolve, join, relative, dirname, basename } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, rmdirSync } from 'node:fs';\nimport { generateContract, rootNeedsScalar } from './codegen-contract.js';\nimport { generateOp } from './codegen-operation.js';\nimport type {\n ContractKitPlugin,\n PluginContext,\n ContractRootNode,\n OpRootNode,\n ModelNode,\n ScalarTypeNode,\n IncrementalManifest,\n IncrementalUnit,\n IncrementalOutputFile,\n} from '@contractkit/core';\nimport {\n runIncrementalCodegen,\n parseIncrementalManifest,\n emptyIncrementalManifest,\n serializeIncrementalManifest,\n hashFingerprint,\n collectTransitiveModelRefs,\n collectTypeRefs,\n computeModelsWithCaseTransform,\n computeModelsWithScalar,\n} from '@contractkit/core';\nimport {\n generateSdk,\n generateSdkOptions,\n generateSdkAggregator,\n generateAreaClient,\n deriveClientClassName,\n deriveClientPropertyName,\n deriveAreaClientClassName,\n deriveAreaPropertyName,\n deriveSubareaClientClassName,\n deriveSubareaPropertyName,\n getAreaSubarea,\n hasPublicOperations,\n generateSdkPackageJson,\n generateSdkTsconfig,\n type SdkClientInfo,\n type SdkAreaInfo,\n type SdkScaffoldDeps,\n} from './codegen-sdk.js';\nimport { generatePlainTypes } from './codegen-plain-types.js';\nimport { DEFAULT_REVIVABLE_SCALARS } from './codegen-revive.js';\n\n/** Taint set for the SDK's bigint response reviver. */\nconst BIGINT_SCALARS: ReadonlySet<ScalarTypeNode['name']> = new Set(['bigint']);\nimport { generateMcpFile, generateMcpAggregator, generateMcpRouter, hasMcpOperations, deriveMcpRegisterFnName } from './codegen-mcp.js';\nimport {\n TEMPLATE_VAR_RE,\n TEMPLATE_VAR_RE_G,\n resolveTemplate,\n commonDir,\n computeOpOutPath,\n computeContractOutPath,\n computeSdkOutPath,\n computeSdkAreaClientOutPath,\n computeSdkTypeOutPath,\n generateBarrelFiles,\n computePubliclyReachableTypes,\n} from './path-utils.js';\n\n// ─── Sub-config interfaces ─────────────────────────────────────────────────\n\n/** Koa server output: routers, and the type or Zod schema files they import. */\nexport interface ServerConfig {\n /** Directory (relative to rootDir) where server files are written. Default: rootDir. */\n baseDir?: string;\n /** When true, `output.types` emits Zod schema files (via `generateContract`). When false/omitted, emits plain TypeScript. */\n zod?: boolean;\n output?: {\n /** Path template for Koa router files. Supports {filename}, {dir}, {area}. */\n routes?: string;\n /** Path template for type/schema files. Supports {filename}, {dir}, {area}. */\n types?: string;\n };\n /** Import path template for service implementations. */\n servicePathTemplate?: string;\n /** Whether to emit handlers for `internal` operations. Default true. */\n includeInternal?: boolean;\n /**\n * When true, each handler re-parses the service result through its declared response schema\n * before writing `ctx.body`, and writes the parsed value. Requires `zod: true` — without it\n * `output.types` emits plain interfaces, which are types with no runtime schema value.\n *\n * A body that transitively references a model with `format(input=...)`/`format(output=...)`, and\n * a status whose several mimes carry different body types, are left unvalidated. Default false.\n */\n validateResponses?: boolean;\n}\n\n/** TypeScript SDK client output: the client class, per-area operation clients, and their types. */\nexport interface SdkConfig {\n baseDir?: string;\n name?: string;\n zod?: boolean;\n output?: {\n sdk?: string;\n types?: string;\n clients?: string;\n };\n includeInternal?: boolean;\n /**\n * Emit a starter `package.json` and `tsconfig.json` at the SDK `baseDir` so the\n * generated output is a buildable, publishable package on its own. Opt-in and\n * write-once: the files are created only when absent and are never overwritten or\n * cleaned up on later builds, so any edits you make to them are preserved.\n * Dependency ranges are derived from the contracts (always `zod` when `zod: true`;\n * `luxon` when any covered model uses a date/time/datetime/duration/interval scalar;\n * `decimal.js` when any uses a decimal).\n */\n scaffold?: boolean;\n}\n\n/** Standalone Zod schema output, independent of the server and SDK sub-generators. */\nexport interface ZodConfig {\n baseDir?: string;\n output?: string;\n}\n\n/** Standalone plain TypeScript type output, independent of the server and SDK sub-generators. */\nexport interface TypesConfig {\n baseDir?: string;\n output?: string;\n /**\n * Runtime the emitted types describe. Affects scalars whose TypeScript type is runtime-specific:\n * `binary` renders as `Buffer` for `'server'` and `Blob` for `'client'`. Default `'client'`.\n * The `server` and `sdk` sub-generators set this themselves.\n */\n target?: 'client' | 'server';\n}\n\n/** MCP tool output: per-op-file handlers, the aggregator, and the optional POST route. */\nexport interface McpConfig {\n /** Directory (relative to rootDir) where MCP files are written. Default: rootDir. */\n baseDir?: string;\n output?: {\n /** Path template for per-op-file tool handlers. Supports {filename}, {dir}, {area}. Default `{filename}.mcp.ts`. */\n tools?: string;\n /** Path (or template) for the aggregator that assembles the McpToolHandlerMap. Default `mcp.tools.ts`. */\n index?: string;\n /** Path (or template) for the optional POST /mcp route file. Default `mcp.router.ts`. */\n router?: string;\n /**\n * Path template for the model **Zod schema** files the tools import (for arg validation and\n * `z.toJSONSchema`). When omitted, falls back to the `server` sub-config's `output.types`\n * (if `server.zod`) or the `zod` sub-config's output. Tools require Zod schemas, not plain types.\n */\n types?: string;\n };\n /** Emit the `mcp.router.ts` route boilerplate. Default true. */\n emitRouter?: boolean;\n /** Mount path used in the emitted router. Default `/mcp`. */\n path?: string;\n /** Import path template for service implementations (same semantics as ServerConfig). */\n servicePathTemplate?: string;\n /** Whether to expose operations marked `internal` as MCP tools. Default false. */\n includeInternal?: boolean;\n}\n\n/** Top-level plugin config. Each sub-config that is present enables its sub-generator. */\nexport interface TypescriptPluginConfig {\n server?: ServerConfig;\n sdk?: SdkConfig;\n zod?: ZodConfig;\n types?: TypesConfig;\n mcp?: McpConfig;\n}\n\n// ─── Caching constants ─────────────────────────────────────────────────────\n\n/** Bumped when the codegen output shape changes in a way that should bust every per-file fingerprint. */\nexport const TYPESCRIPT_CODEGEN_VERSION = '2';\n\n// The taint set is `DEFAULT_REVIVABLE_SCALARS` rather than decimal alone, which is what makes a\n// temporal field a real Luxon object in an SDK client rather than a string wearing a `DateTime`\n// type. It also feeds every `hashFingerprint` that already slices this set, so a model gaining a\n// `datetime` in another `.ck` file invalidates this file's cached output with no extra plumbing.\n\n/** Filename for the persisted TypeScript manifest under the CLI cache directory. */\nconst CACHE_MANIFEST_FILENAME = 'typescript-manifest.json';\n\n// ─── Plugin entry points ──────────────────────────────────────────────────\n\nconst plugin: ContractKitPlugin = {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n const config = ctx.options as TypescriptPluginConfig;\n await runTypescriptCodegen(inputs, ctx, config, ctx.rootDir);\n },\n};\n\nexport default plugin;\n\n/** Build a `@contractkit/plugin-typescript` instance with explicit configuration, for programmatic use. */\nexport function createTypescriptPlugin(config: TypescriptPluginConfig, rootDir: string): ContractKitPlugin {\n return {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n await runTypescriptCodegen(inputs, ctx, config, rootDir);\n },\n };\n}\n\n/** Reject config combinations that would generate code that cannot compile or cannot run. */\nfunction assertValidConfig(config: TypescriptPluginConfig): void {\n if (config.server?.validateResponses && !config.server.zod) {\n throw new Error(\n 'plugin-typescript: server.validateResponses requires server.zod: true — without it output.types emits plain TypeScript interfaces, which are types with no runtime schema value for the router to validate against.',\n );\n }\n}\n\n/**\n * Shared orchestration. Each sub-generator (server / sdk / zod / types) contributes a\n * set of cacheable units (per-file fingerprints) plus a set of always-regenerated global\n * files (aggregators, barrels, sdk-options). Units share a single manifest so the cache\n * survives cross-cutting reads — the manifest lives at `<rootDir>/.contractkit-typescript-manifest.json`.\n *\n * Honors `ctx.cacheEnabled` — `--force` bypasses the manifest entirely.\n */\nasync function runTypescriptCodegen(\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n ctx: PluginContext,\n config: TypescriptPluginConfig,\n rootDir: string,\n): Promise<void> {\n assertValidConfig(config);\n const manifestPath = resolve(ctx.cacheDir, CACHE_MANIFEST_FILENAME);\n const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n\n const units: IncrementalUnit[] = [];\n const globalFiles: IncrementalOutputFile[] = [];\n\n if (config.server) collectServerOutput(config.server, rootDir, inputs, units);\n if (config.sdk) collectSdkOutput(config.sdk, rootDir, inputs, units, globalFiles);\n if (config.zod) collectZodOutput(config.zod, rootDir, inputs, units);\n if (config.types) collectTypesOutput(config.types, rootDir, inputs, units);\n if (config.mcp) collectMcpOutput(config.mcp, config, rootDir, inputs, units, globalFiles);\n\n const result = runIncrementalCodegen({\n codegenVersion: TYPESCRIPT_CODEGEN_VERSION,\n prevManifest,\n globalFiles,\n units,\n // Paths are absolute, so existsSync works directly.\n fileExists: existsSync,\n });\n\n deleteStalePaths(result.deletedPaths);\n\n const unresolved = new Set<string>();\n for (const { relativePath, content, ifAbsent } of result.filesToWrite) {\n for (const [, key] of relativePath.matchAll(TEMPLATE_VAR_RE_G)) unresolved.add(`${key}::${relativePath}`);\n ctx.emitFile(relativePath, content, ifAbsent ? { ifAbsent: true } : undefined);\n }\n // `resolveTemplate` leaves an unknown `{key}` in place, which then joins straight into the\n // output path — producing a literal `{area}` directory rather than an error. `assertWithinBase`\n // does not catch it, since the path is inside the base, just wrong. Checked here rather than\n // threaded down through five path helpers: every output path passes through this one funnel,\n // whichever helper built it.\n for (const entry of [...unresolved].sort()) {\n const [key, outPath] = entry.split('::');\n ctx.warn?.(\n `Output path template variable {${key}} has no value, so '${outPath}' contains it literally. ` +\n `Declare it in the source file's 'options { keys { ${key}: ... } }' block, or remove it from the path template.`,\n );\n }\n\n writeManifest(manifestPath, result.manifest);\n}\n\n// ─── Cross-file dependency analysis ────────────────────────────────────────\n\n/** Build a quick lookup from model name → its definition. */\nfunction buildModelMap(contractRoots: readonly ContractRootNode[]): Map<string, ModelNode> {\n const map = new Map<string, ModelNode>();\n for (const root of contractRoots) {\n for (const model of root.models) map.set(model.name, model);\n }\n return map;\n}\n\n/** Collect every model referenced by this contract root (own models' fields + bases). Used to slice cross-file fingerprint inputs to just what this file actually depends on. */\nfunction collectContractRootRefs(root: ContractRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const m of root.models) {\n if (m.type) seeds.push(m.type);\n for (const f of m.fields) seeds.push(f.type);\n if (m.bases) {\n for (const b of m.bases) seeds.push({ kind: 'ref', name: b } as Parameters<typeof collectTypeRefs>[0]);\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\n/** Collect every model referenced by an op root's routes/operations (transitive). */\nfunction collectOpRootRefs(root: OpRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const route of root.routes) {\n if (route.params) seeds.push(...paramSourceTypes(route.params));\n for (const op of route.operations) {\n if (op.query) seeds.push(...paramSourceTypes(op.query));\n if (op.headers) seeds.push(...paramSourceTypes(op.headers));\n if (op.request) {\n for (const body of op.request.bodies) seeds.push(body.bodyType);\n }\n for (const resp of op.responses) {\n for (const body of resp.bodies) seeds.push(body.bodyType);\n if (resp.headers) {\n for (const h of resp.headers) seeds.push(h.type);\n }\n }\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\nfunction paramSourceTypes(src: NonNullable<OpRootNode['routes'][number]['params']>): Parameters<typeof collectTypeRefs>[0][] {\n const out: Parameters<typeof collectTypeRefs>[0][] = [];\n if (src.kind === 'params') {\n for (const n of src.nodes) out.push(n.type);\n } else if (src.kind === 'ref') {\n out.push({ kind: 'ref', name: src.name } as Parameters<typeof collectTypeRefs>[0]);\n } else if (src.kind === 'type') {\n out.push(src.node);\n }\n return out;\n}\n\n/** Build a sorted, JSON-stable record of (modelName -> outPath) for refs this unit depends on. */\nfunction sliceOutPathMap(refs: Set<string>, modelOutPaths: Map<string, string>, modelsWithInput: Set<string>, modelsWithOutput: Set<string>): Record<string, string> {\n const slice: Record<string, string> = {};\n for (const ref of [...refs].sort()) {\n const p = modelOutPaths.get(ref);\n if (p) slice[ref] = p;\n if (modelsWithInput.has(ref)) {\n const ip = modelOutPaths.get(`${ref}Input`);\n if (ip) slice[`${ref}Input`] = ip;\n }\n if (modelsWithOutput.has(ref)) {\n const op = modelOutPaths.get(`${ref}Output`);\n if (op) slice[`${ref}Output`] = op;\n }\n }\n return slice;\n}\n\n/** Slice modelsWithInput/Output to only the names relevant to this unit. */\nfunction sliceModelSet(refs: Set<string>, ownNames: Set<string>, set: Set<string>): string[] {\n const result: string[] = [];\n for (const name of set) {\n if (refs.has(name) || ownNames.has(name)) result.push(name);\n }\n return result.sort();\n}\n\n// ─── Server sub-generator ──────────────────────────────────────────────────\n\nfunction collectServerOutput(\n config: ServerConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const serverBase = resolve(rootDir, config.baseDir ?? '.');\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n // Not `modelsWithOutput`: that set seeds only from `format(output=...)`, because only that case\n // needs an `Output` type alias. A `format(input=...)`-only model is just as untouchable for\n // response validation — its schema's input casing is not what the service hands back.\n const modelsWithTransform = computeModelsWithCaseTransform(inputs.contractRoots.flatMap(r => r.models));\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const subConfigKey = stableSubConfig(config);\n\n // Pre-pass: register all model → outPath. Cross-file refs need to resolve correctly,\n // which means we need the COMPLETE map (not a slice) — even though each unit's fingerprint\n // only includes its own slice.\n const serverModelOutPaths = new Map<string, string>();\n const typeEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeContractOutPath(ast.file, serverBase, config.output.types, '.ts', commonRoot, ast.meta);\n typeEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n serverModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) serverModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) serverModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── Per-contract-root types unit ──\n for (const { ast, typeOutPath } of typeEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'server-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `server-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n const renderCtx = {\n modelOutPaths: serverModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n // These types are consumed by Koa handlers, so `binary` is a Buffer, not a Blob.\n target: 'server' as const,\n };\n const content = config.zod ? generateContract(ast, renderCtx) : generatePlainTypes(ast, renderCtx);\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Per-op-root router unit ──\n for (const ast of inputs.opRoots) {\n const outPath = computeOpOutPath(ast.file, serverBase, config.output?.routes, '.router.ts', commonRoot, ast.meta);\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'server-router',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n // The router imports types from each contract root's type file; the slice covers exactly that.\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n servicePathTemplate: config.servicePathTemplate ?? null,\n includeInternal: config.includeInternal ?? true,\n // Not covered by `sub`: adding `format(input=snake)` to a *different* .ck file changes\n // this router's output with no change to `root` or the config.\n modelsWithTransform: sliceModelSet(refs, new Set(), modelsWithTransform),\n validateResponses: config.validateResponses ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `server-router::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateOp(ast, {\n servicePathTemplate: config.servicePathTemplate,\n outPath,\n modelOutPaths: serverModelOutPaths,\n modelsWithInput,\n modelsWithOutput,\n modelsWithTransform,\n includeInternal: config.includeInternal,\n validateResponses: config.validateResponses,\n }),\n },\n ],\n });\n }\n}\n\n// ─── SDK sub-generator ─────────────────────────────────────────────────────\n\nfunction collectSdkOutput(\n config: SdkConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n globalFiles: IncrementalOutputFile[],\n): void {\n const sdkBase = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;\n const sdkName = config.name;\n const sdkOutput = config.output?.sdk;\n const sdkEntryPath = sdkOutput\n ? join(sdkBase, TEMPLATE_VAR_RE.test(sdkOutput) ? resolveTemplate(sdkOutput, { name: sdkName ?? 'sdk' }) : sdkOutput)\n : join(sdkBase, 'sdk.ts');\n const sdkOptionsPath = join(dirname(sdkEntryPath), 'sdk-options.ts');\n const subConfigKey = stableSubConfig(config);\n\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n // Computed across every contract root, not per file: one decimal below a model taints it, and\n // the reference that reaches it may live in another .ck file entirely.\n const modelsWithDecimal = computeModelsWithScalar(inputs.contractRoots.flatMap(r => r.models), DEFAULT_REVIVABLE_SCALARS);\n // Which response bodies need the `123n` reviver. Transitive, because a bigint reached through\n // a referenced model counts, and cross-file, because that model may live in another .ck file —\n // which is also why it is sliced into every fingerprint below, exactly as modelsWithDecimal is.\n const modelsWithBigInt = computeModelsWithScalar(inputs.contractRoots.flatMap(r => r.models), BIGINT_SCALARS);\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const ckCommonRoot = commonDir(allFiles, rootDir);\n\n const sdkModelOutPaths = new Map<string, string>();\n const sdkTypePaths: string[] = [];\n const sdkClientInfos: { outPath: string; className: string; propertyName: string }[] = [];\n\n // ── Pre-pass: SDK type files ──\n const sdkContractEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n const publicTypes = computePubliclyReachableTypes(inputs.opRoots, inputs.contractRoots, modelsWithInput, modelsWithOutput);\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeSdkTypeOutPath(ast.file, sdkBase, config.output.types, ckCommonRoot, ast.meta);\n if (!typeOutPath) continue;\n if (publicTypes !== null && !ast.models.some(m => publicTypes.has(m.name))) continue;\n sdkTypePaths.push(typeOutPath);\n sdkContractEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n sdkModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) sdkModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) sdkModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── SDK type units ──\n for (const { ast, typeOutPath } of sdkContractEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'sdk-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n // Not covered by `root`: adding a decimal to a model in a *different* .ck file changes\n // this file's revivers with no change to `root` or the config.\n modelsWithDecimal: sliceModelSet(refs, ownNames, modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(refs, ownNames, modelsWithBigInt),\n sdkOptionsPath,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n let content: string;\n // `emitRevivers` is set for SDK type files only: a server handler receives decimals\n // already parsed by `_ZodDecimal`, so it has nothing to rehydrate.\n if (config.zod) {\n content = generateContract(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n emitRevivers: true,\n // An SDK client runs in a browser as readily as in Node, and its scaffold\n // declares no `@types/node`.\n target: 'client',\n });\n } else {\n let rel = relative(dirname(typeOutPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n content = generatePlainTypes(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n emitRevivers: true,\n jsonValueImportPath: rel,\n });\n }\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Bucket op roots by area/subarea ──\n interface AreaBucket {\n leaves: { ast: OpRootNode; outPath: string; subarea: string }[];\n inlineRoots: OpRootNode[];\n }\n const areaBuckets = new Map<string, AreaBucket>();\n const topLevelEntries: { ast: OpRootNode; outPath: string }[] = [];\n\n if (config.output?.clients) {\n for (const ast of inputs.opRoots) {\n const sdkOutPath = computeSdkOutPath(ast.file, sdkBase, config.output.clients, ckCommonRoot, ast.meta);\n if (!sdkOutPath || !hasPublicOperations(ast, config.includeInternal)) continue;\n const { area, subarea } = getAreaSubarea(ast);\n if (area && subarea) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.leaves.push({ ast, outPath: sdkOutPath, subarea });\n areaBuckets.set(area, bucket);\n } else if (area) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.inlineRoots.push(ast);\n areaBuckets.set(area, bucket);\n } else {\n topLevelEntries.push({ ast, outPath: sdkOutPath });\n }\n }\n\n // ── Per-leaf-client (area+subarea) units ──\n for (const [area, bucket] of areaBuckets.entries()) {\n for (const leaf of bucket.leaves) {\n const className = deriveSubareaClientClassName(area, leaf.subarea);\n sdkClientInfos.push({ outPath: leaf.outPath, className, propertyName: deriveSubareaPropertyName(leaf.subarea) });\n const refs = collectOpRootRefs(leaf.ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-leaf-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: leaf.outPath,\n root: leaf.ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n modelsWithDecimal: sliceModelSet(refs, new Set(), modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(refs, new Set(), modelsWithBigInt),\n sdkOptionsPath,\n className,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-leaf-client::${leaf.outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: leaf.outPath,\n content: generateSdk(leaf.ast, {\n typeImportPathTemplate: undefined,\n outPath: leaf.outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n modelsWithBigInt,\n modelMap,\n includeInternal: config.includeInternal,\n clientClassName: className,\n }),\n },\n ],\n });\n }\n }\n\n // ── Top-level (no area) client units ──\n for (const { ast, outPath } of topLevelEntries) {\n const className = deriveClientClassName(ast.file);\n sdkClientInfos.push({ outPath, className, propertyName: deriveClientPropertyName(ast.file) });\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-top-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n modelsWithDecimal: sliceModelSet(refs, new Set(), modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(refs, new Set(), modelsWithBigInt),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-top-client::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateSdk(ast, {\n typeImportPathTemplate: undefined,\n outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n modelsWithBigInt,\n modelMap,\n includeInternal: config.includeInternal,\n }),\n },\n ],\n });\n }\n }\n\n // ── Global files: sdk-options, aggregator, barrels, root index ──\n // sdk-options.ts is a constant; the aggregator is small (just imports + a wrapper class)\n // and depends on the cross-cutting client list, so it's cheap to regenerate every run.\n // Per-area `<area>.client.ts` files are cached as their own units below.\n globalFiles.push({ relativePath: sdkOptionsPath, content: generateSdkOptions() });\n\n const hasAnything = sdkClientInfos.length > 0 || areaBuckets.size > 0;\n const areaClientOutPaths = new Map<string, string>(); // area → absolute outPath of <area>.client.ts\n if (hasAnything) {\n const sdkEntryDir = dirname(sdkEntryPath);\n const sdkOptionsRel = relative(sdkEntryDir, sdkOptionsPath).replace(/\\.ts$/, '.js');\n const sdkOptionsImportPath = sdkOptionsRel.startsWith('.') ? sdkOptionsRel : './' + sdkOptionsRel;\n const sdkClassName = sdkName\n ? sdkName\n .split(/[-._\\s]+/)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('') + 'Sdk'\n : 'Sdk';\n\n const toClientImport = (sourceDir: string, info: { outPath: string; className: string; propertyName: string }): SdkClientInfo => {\n let rel = relative(sourceDir, info.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n return { className: info.className, propertyName: info.propertyName, importPath: rel };\n };\n\n const topLevelClients: SdkClientInfo[] = topLevelEntries.map(e =>\n toClientImport(sdkEntryDir, {\n outPath: e.outPath,\n className: deriveClientClassName(e.ast.file),\n propertyName: deriveClientPropertyName(e.ast.file),\n }),\n );\n\n // ── Per-area `<area>.client.ts` units ──\n const areaInfos: SdkAreaInfo[] = [];\n const sortedAreas = [...areaBuckets.entries()].sort(([a], [b]) => a.localeCompare(b));\n for (const [area, bucket] of sortedAreas) {\n const areaClientOutPath = computeSdkAreaClientOutPath(area, sdkBase, config.output!.clients);\n areaClientOutPaths.set(area, areaClientOutPath);\n const areaClassName = deriveAreaClientClassName(area);\n const areaPropertyName = deriveAreaPropertyName(area);\n sdkClientInfos.push({ outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName });\n\n const subareaClients = bucket.leaves\n .sort((a, b) => a.subarea.localeCompare(b.subarea))\n .map(l => ({\n propertyName: deriveSubareaPropertyName(l.subarea),\n client: toClientImport(dirname(areaClientOutPath), {\n outPath: l.outPath,\n className: deriveSubareaClientClassName(area, l.subarea),\n propertyName: deriveSubareaPropertyName(l.subarea),\n }),\n }));\n\n // Fingerprint covers every input the area client depends on:\n // - all inline roots (full AST)\n // - subarea client metadata (className / propertyName / import path)\n // - the modelOutPaths slice for refs across all inline roots\n // - modelsWithInput/Output slices\n const allInlineRefs = new Set<string>();\n for (const r of bucket.inlineRoots) {\n for (const ref of collectOpRootRefs(r, modelMap)) allInlineRefs.add(ref);\n }\n const fingerprint = hashFingerprint({\n kind: 'sdk-area-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: areaClientOutPath,\n area,\n inlineRoots: bucket.inlineRoots,\n subareaClients,\n outPathSlice: sliceOutPathMap(allInlineRefs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(allInlineRefs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(allInlineRefs, new Set(), modelsWithOutput),\n modelsWithDecimal: sliceModelSet(allInlineRefs, new Set(), modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(allInlineRefs, new Set(), modelsWithBigInt),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n\n const inlineFilesForGen = bucket.inlineRoots.map(root => ({\n root,\n codegenOptions: {\n typeImportPathTemplate: undefined,\n outPath: areaClientOutPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n modelsWithBigInt,\n modelMap,\n includeInternal: config.includeInternal,\n },\n }));\n\n units.push({\n key: `sdk-area-client::${areaClientOutPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: areaClientOutPath,\n content: generateAreaClient({\n area,\n outPath: areaClientOutPath,\n inlineFiles: inlineFilesForGen,\n subareaClients,\n sdkOptionsPath,\n }),\n },\n ],\n });\n\n areaInfos.push({\n area,\n client: toClientImport(sdkEntryDir, { outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName }),\n });\n }\n\n globalFiles.push({\n relativePath: sdkEntryPath,\n content: generateSdkAggregator({ topLevelClients, areas: areaInfos, sdkOptionsImportPath, sdkClassName }),\n });\n }\n\n const sdkSrcDir = dirname(sdkEntryPath);\n const sdkTypeBarrels = generateBarrelFiles(sdkTypePaths);\n for (const barrel of sdkTypeBarrels) globalFiles.push({ relativePath: barrel.outPath, content: barrel.content });\n\n const rootExports: string[] = [`export * from './${basename(sdkOptionsPath).replace(/\\.ts$/, '.js')}';`];\n if (hasAnything) rootExports.push(`export * from './${basename(sdkEntryPath).replace(/\\.ts$/, '.js')}';`);\n for (const c of sdkClientInfos) {\n let rel = relative(sdkSrcDir, c.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n for (const barrel of sdkTypeBarrels) {\n let rel = relative(sdkSrcDir, barrel.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n globalFiles.push({\n relativePath: join(sdkSrcDir, 'index.ts'),\n content: `// Auto-generated barrel file\\n${rootExports.sort().join('\\n')}\\n`,\n });\n\n // ── Scaffold files (opt-in, write-once) ──\n // Emitted at the SDK package root with `ifAbsent` so they're created once and\n // then owned by the user. Deps are derived from the contracts actually surfaced\n // into the SDK: zod when schema output is on, luxon when any covered model uses a\n // date/time/datetime/interval scalar.\n if (config.scaffold) {\n const coveredRoots = sdkContractEntries.map(e => e.ast);\n const deps: SdkScaffoldDeps = {\n zod: !!config.zod,\n // `duration` belongs here too: `generateContract` imports `Duration` from luxon for it,\n // so a contract whose only temporal scalar is a duration used to scaffold a package.json\n // with no luxon dependency and fail to compile.\n luxon: coveredRoots.some(r =>\n (['datetime', 'date', 'time', 'duration', 'interval'] as const).some(name => rootNeedsScalar(r, name)),\n ),\n decimal: coveredRoots.some(r => rootNeedsScalar(r, 'decimal')),\n };\n globalFiles.push({\n relativePath: join(sdkBase, 'package.json'),\n content: generateSdkPackageJson({ name: sdkName ?? 'sdk', deps }),\n ifAbsent: true,\n });\n globalFiles.push({\n relativePath: join(sdkBase, 'tsconfig.json'),\n content: generateSdkTsconfig(),\n ifAbsent: true,\n });\n }\n}\n\n// ─── Zod sub-generator ─────────────────────────────────────────────────────\n\nfunction collectZodOutput(\n config: ZodConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const zodBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, zodBase, config.output, '.schema.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'zod',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `zod::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n // Server-shaped, which is what this sub-generator has always emitted. The\n // standalone `zod:` output has no target option of its own; only the SDK's\n // schemas are client-shaped, and they pass their own target.\n content: generateContract(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput, target: 'server' }),\n },\n ],\n });\n }\n}\n\n// ─── Plain types sub-generator ─────────────────────────────────────────────\n\nfunction collectTypesOutput(\n config: TypesConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const typesBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, typesBase, config.output, '.types.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'plain-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `plain-types::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generatePlainTypes(ast, {\n modelOutPaths,\n currentOutPath: outPath,\n modelsWithInput,\n modelsWithOutput,\n target: config.target,\n }),\n },\n ],\n });\n }\n}\n\n// ─── MCP sub-generator ─────────────────────────────────────────────────────\n\n/**\n * Resolve where the model **Zod schema** files live so the MCP tools can import them (for arg\n * validation + `z.toJSONSchema`). Precedence: explicit `mcp.output.types` → the `server` sub-config's\n * `output.types` (only when `server.zod`) → the `zod` sub-config's output. Returns an empty map when\n * none resolve (imports then fall back to a colocated `./<name>.js` guess).\n */\nfunction resolveMcpModelOutPaths(\n config: TypescriptPluginConfig,\n rootDir: string,\n contractRoots: readonly ContractRootNode[],\n commonRoot: string,\n modelsWithInput: Set<string>,\n modelsWithOutput: Set<string>,\n): Map<string, string> {\n const map = new Map<string, string>();\n let base: string;\n let template: string | undefined;\n let suffix: string;\n if (config.mcp?.output?.types) {\n base = resolve(rootDir, config.mcp.baseDir ?? '.');\n template = config.mcp.output.types;\n suffix = '.ts';\n } else if (config.server?.zod && config.server.output?.types) {\n base = resolve(rootDir, config.server.baseDir ?? '.');\n template = config.server.output.types;\n suffix = '.ts';\n } else if (config.zod) {\n base = resolve(rootDir, config.zod.baseDir ?? '.');\n template = config.zod.output;\n suffix = '.schema.ts';\n } else {\n return map;\n }\n\n for (const ast of contractRoots) {\n const outPath = computeContractOutPath(ast.file, base, template, suffix, commonRoot, ast.meta);\n for (const model of ast.models) {\n map.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) map.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) map.set(`${model.name}Output`, outPath);\n }\n }\n return map;\n}\n\nfunction collectMcpOutput(\n config: McpConfig,\n fullConfig: TypescriptPluginConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n globalFiles: IncrementalOutputFile[],\n): void {\n const mcpBase = resolve(rootDir, config.baseDir ?? '.');\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const subConfigKey = stableSubConfig(config);\n const includeInternal = config.includeInternal ?? false;\n\n const modelOutPaths = resolveMcpModelOutPaths(fullConfig, rootDir, inputs.contractRoots, commonRoot, modelsWithInput, modelsWithOutput);\n\n // ── Per-op-root tool-handler units (only files with MCP-exposed ops) ──\n const entries: { outPath: string; registerFn: string }[] = [];\n for (const ast of inputs.opRoots) {\n if (!hasMcpOperations(ast, includeInternal)) continue;\n const outPath = computeOpOutPath(ast.file, mcpBase, config.output?.tools, '.mcp.ts', commonRoot, ast.meta);\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'mcp-tools',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n servicePathTemplate: config.servicePathTemplate ?? null,\n includeInternal,\n sub: subConfigKey,\n });\n units.push({\n key: `mcp-tools::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateMcpFile(ast, {\n outPath,\n modelOutPaths,\n modelsWithInput,\n modelsWithOutput,\n servicePathTemplate: config.servicePathTemplate,\n includeInternal,\n }),\n },\n ],\n });\n entries.push({ outPath, registerFn: deriveMcpRegisterFnName(ast.file) });\n }\n\n if (entries.length === 0) return;\n\n // ── Aggregator (global) ──\n const indexPath = join(mcpBase, config.output?.index ?? 'mcp.tools.ts');\n const aggregatorEntries = entries\n .map(e => {\n let rel = relative(dirname(indexPath), e.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n return { registerFn: e.registerFn, importPath: rel };\n })\n .sort((a, b) => a.registerFn.localeCompare(b.registerFn));\n globalFiles.push({ relativePath: indexPath, content: generateMcpAggregator(aggregatorEntries) });\n\n // ── Router (global, optional) ──\n if (config.emitRouter !== false) {\n const routerPath = join(mcpBase, config.output?.router ?? 'mcp.router.ts');\n globalFiles.push({ relativePath: routerPath, content: generateMcpRouter({ path: config.path }) });\n }\n}\n\n// ─── Manifest IO + cleanup ─────────────────────────────────────────────────\n\nfunction readManifest(manifestPath: string): IncrementalManifest {\n if (!existsSync(manifestPath)) return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n try {\n return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n }\n}\n\n/** Write the manifest to `manifestPath`. Creates parent dirs as needed. Errors are swallowed so a broken cache never blocks the build. */\nfunction writeManifest(manifestPath: string, manifest: IncrementalManifest): void {\n try {\n mkdirSync(dirname(manifestPath), { recursive: true });\n writeFileSync(manifestPath, serializeIncrementalManifest(manifest), 'utf-8');\n } catch {\n // best-effort\n }\n}\n\nfunction deleteStalePaths(absPaths: string[]): void {\n if (absPaths.length === 0) return;\n const removedDirs = new Set<string>();\n for (const abs of absPaths) {\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(dirname(abs));\n }\n }\n // Walk up affected dirs and remove if empty. Bounded — stops at filesystem root or first non-empty dir.\n for (const dir of removedDirs) {\n let current = dir;\n while (current.length > 1) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = dirname(current);\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n\n/** Stringify a sub-config so it can participate in fingerprints. JSON.stringify gives stable output for typical config shapes. */\nfunction stableSubConfig(config: unknown): string {\n return JSON.stringify(config ?? null);\n}\n","import { relative, dirname } from 'node:path';\nimport type {\n ContractRootNode,\n ModelNode,\n FieldNode,\n ContractTypeNode,\n ScalarTypeNode,\n ArrayTypeNode,\n TupleTypeNode,\n RecordTypeNode,\n EnumTypeNode,\n LiteralTypeNode,\n UnionTypeNode,\n DiscriminatedUnionTypeNode,\n InlineObjectTypeNode,\n IntersectionTypeNode,\n ObjectMode,\n} from '@contractkit/core';\nimport {\n collectTypeRefs,\n computeModelsWithOutput as ckComputeModelsWithOutput,\n collectExternalOutputRefs as ckCollectExternalOutputRefs,\n} from '@contractkit/core';\nimport { escapeJsDocLines, sourceLink } from './ts-render.js';\nimport type { TsRenderTarget } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_PRELUDE_LINES } from './decimal-runtime.js';\nimport { renderReviveFunctions, reviveFnName, coerceDeclsFor } from './codegen-revive.js';\n\n/**\n * Maps a ContractKit object mode to its Zod constructor name.\n *\n * @returns `\"z.strictObject\"` | `\"z.object\"` | `\"z.looseObject\"`\n */\nexport function modeToWrapper(mode: ObjectMode): string {\n switch (mode) {\n case 'strict':\n return 'z.strictObject';\n case 'strip':\n return 'z.object';\n case 'loose':\n return 'z.looseObject';\n }\n}\n\n// ─── Cross-file import resolution ─────────────────────────────────────────\n\n/** Cross-file context passed to `generateContract` to wire up imports and Input/Output variant tracking. */\nexport interface ContractCodegenContext {\n /** Map from model name → absolute output file path */\n modelOutPaths: Map<string, string>;\n /** Absolute output file path for the current contract file */\n currentOutPath: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /** If set, import JsonValue from this path instead of re-declaring it (avoids barrel re-export conflicts) */\n jsonValueImportPath?: string;\n /**\n * Runtime the emitted types describe. Only affects scalars whose TypeScript type differs per\n * runtime: `binary` is a `Buffer` on a Node server and a `Blob` in a fetch client, and\n * `_ZodBinary` is generated to match. Default `'client'`.\n */\n target?: TsRenderTarget;\n /** Model names that carry a `decimal`, directly or transitively. */\n modelsWithDecimal?: Set<string>;\n /**\n * Emit `reviveX()` hydration functions alongside the schemas. Set only for SDK type files: a\n * server handler receives decimals already parsed by `_ZodDecimal`, so it has nothing to revive.\n */\n emitRevivers?: boolean;\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Compute which models need Input variants, including transitive dependencies.\n * A model needs an Input variant if it has visibility-modified fields, OR if\n * any of its field types (recursively) reference a model that has an Input variant.\n */\nexport function computeModelsWithInput(models: ModelNode[], externalModelsWithInput: Set<string> = new Set()): Set<string> {\n const result = new Set<string>();\n\n // Initial pass: direct visibility modifiers\n for (const model of models) {\n if (model.fields.some(f => f.visibility !== 'normal')) {\n result.add(model.name);\n }\n }\n\n // Transitive closure: add models that reference models with Input variants,\n // including through base model inheritance.\n let changed = true;\n while (changed) {\n changed = false;\n for (const model of models) {\n if (result.has(model.name)) continue;\n const refs = new Set<string>();\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // A model that extends a parent with Input variants also needs an Input variant,\n // so that the write schema can extend ParentInput instead of Parent.\n if (model.bases) for (const b of model.bases) refs.add(b);\n // A type alias (model.type set) that references a model with Input variants\n // also needs an Input variant.\n if (model.type) collectTypeRefs(model.type, refs);\n for (const ref of refs) {\n if (result.has(ref) || externalModelsWithInput.has(ref)) {\n result.add(model.name);\n changed = true;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n for (const l of escapeJsDocLines(model.description)) lines.push(` * ${l}`);\n }\n\n lines.push(` * generated from ${sourceLink(model.name, outPath, model.loc.file, model.loc.line)}`);\n lines.push('*/');\n return lines;\n}\n\n/**\n * Generate a TypeScript module containing Zod schemas for every model in `root`.\n *\n * Emits two schemas per model when visibility modifiers are present: `Model` (read — no\n * writeonly fields) and `ModelInput` (write — no readonly fields). Writeonly inheritance rides\n * on the Input chain, since a child's `Input` extends its parent's `Input`, which already carries\n * the parent's writeonly fields.\n *\n * @param root - The parsed contract root node.\n * @param context - Optional cross-file context for import resolution and Input/Output variant tracking.\n * @returns The full TypeScript source as a string.\n */\nexport function generateContract(root: ContractRootNode, context?: ContractCodegenContext): string {\n const needsDateTime = rootNeedsDateTime(root);\n const needsDuration = rootNeedsScalar(root, 'duration');\n const needsInterval = rootNeedsScalar(root, 'interval');\n const needsBinary = rootNeedsScalar(root, 'binary');\n const needsDatetime = rootNeedsScalar(root, 'datetime');\n const needsJson = rootNeedsScalar(root, 'json');\n const needsDecimal = rootNeedsScalar(root, 'decimal');\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = ckComputeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input refs needed for Input schema fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? ckCollectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n lines.push(`import { z } from 'zod';`);\n const luxonImports: string[] = [];\n if (needsDateTime) luxonImports.push('DateTime');\n if (needsDuration) luxonImports.push('Duration');\n if (needsInterval) luxonImports.push('Interval');\n if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n if (needsDecimal) lines.push(DECIMAL_IMPORT);\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n // A cross-file model that carries a decimal contributes its reviver too — the local\n // reviver calls it rather than re-deriving the other file's shape.\n const names =\n context?.emitRevivers && context.modelsWithDecimal?.has(ref) ? `${ref}, ${reviveFnName(ref)}` : ref;\n lines.push(`import { ${names} } from '${importPath}';`);\n }\n lines.push('');\n if (needsBinary) {\n // The one scalar with no single correct runtime type, so it follows `target` here exactly\n // as `renderTsScalar` does. An SDK type file reaching this through the shared\n // `generateContract` used to emit `Buffer.isBuffer` into a browser client, whose scaffold\n // declares no `@types/node` — the type did not resolve and the check could not run.\n lines.push(\n context?.target === 'server'\n ? `const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`\n : `const _ZodBinary = z.custom<Blob>((val) => val instanceof Blob, { error: 'Must be binary data' });`,\n );\n }\n if (needsDatetime) {\n lines.push(\n `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' }));`,\n );\n }\n if (needsInterval) {\n lines.push(\n `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()!);`,\n );\n }\n if (needsDecimal) {\n lines.push(...DECIMAL_PRELUDE_LINES);\n }\n if (needsJson) {\n lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n lines.push(\n `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)]));`,\n );\n }\n if (needsBinary || needsDatetime || needsInterval || needsDecimal || needsJson) lines.push('');\n\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n\n const reviveOpts =\n context?.emitRevivers && context.modelsWithDecimal\n ? { modelsWithDecimal: context.modelsWithDecimal, modelsWithOutput: allModelsWithOutput, modelMap }\n : undefined;\n\n const bodyLines: string[] = [];\n for (const model of topoSortModels(root.models)) {\n bodyLines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, modelMap, allModelsWithOutput));\n if (reviveOpts) {\n const revivers = renderReviveFunctions(model, reviveOpts);\n if (revivers.length > 0) {\n bodyLines.push('');\n bodyLines.push(...revivers);\n }\n }\n bodyLines.push('');\n }\n\n // Decided from the emitted revivers rather than from a predicate over the AST, so the\n // declarations and their uses cannot drift apart and leave an unused local behind.\n const coerceDecls = coerceDeclsFor(bodyLines);\n if (coerceDecls.length > 0) {\n lines.push(...coerceDecls);\n lines.push('');\n }\n lines.push(...bodyLines);\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\n/**\n * If any ancestor in the base chain has a format(input=)/format(output=) transform,\n * the parent schema compiles to a `ZodPipe` (object().transform()) which has no `.extend()`.\n * To keep extension working, inline the parent's fields into the child and inherit format/mode\n * so the child re-applies the transform on the merged shape. Returns the model unchanged when\n * no ancestor has format, preserving the existing `.extend()`-based output.\n */\nfunction flattenFormatChain(model: ModelNode, modelMap: Map<string, ModelNode>): ModelNode {\n if (!model.bases || model.bases.length === 0) return model;\n // TODO(multi-base): currently only the first base is followed for format inheritance.\n // Multi-base format flattening will need a topological merge across all bases.\n const firstBase = model.bases[0]!;\n const parent = modelMap.get(firstBase);\n if (!parent) return model;\n const flatParent = flattenFormatChain(parent, modelMap);\n const parentHasFormat =\n (flatParent.inputCase !== undefined && flatParent.inputCase !== 'camel') ||\n (flatParent.outputCase !== undefined && flatParent.outputCase !== 'camel');\n if (!parentHasFormat) return model;\n\n const merged = new Map<string, FieldNode>();\n for (const f of flatParent.fields) merged.set(f.name, f);\n for (const f of model.fields) merged.set(f.name, f);\n\n return {\n ...model,\n bases: undefined,\n fields: [...merged.values()],\n inputCase: model.inputCase ?? flatParent.inputCase,\n outputCase: model.outputCase ?? flatParent.outputCase,\n mode: model.mode ?? flatParent.mode,\n };\n}\n\nfunction generateModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n modelsWithOutput?: Set<string>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);\n }\n\n const effective = modelMap ? flattenFormatChain(model, modelMap) : model;\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = effective.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(effective.name) ?? false);\n\n const lines = needsInputSplit\n ? generateThreeSchemaModel(effective, outPath, modelsWithInput, modelMap)\n : generateSimpleModel(effective, outPath);\n\n // Emit Output type alias when this model (transitively) has format(output=...)\n if (modelsWithOutput?.has(effective.name)) {\n lines.push(`export type ${effective.name}Output = z.output<typeof ${effective.name}>;`);\n }\n\n return lines;\n}\n\nfunction generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export const ${model.name} = ${renderType(model.type!)};`);\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export const ${model.name}Input = ${renderInputType(model.type!, modelsWithInput)};`);\n lines.push(`export type ${model.name}Input = z.infer<typeof ${model.name}Input>;`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = z.output<typeof ${model.name}>;`);\n }\n return lines;\n}\n\nfunction generateSimpleModel(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const { inputCase, outputCase } = model;\n const hasInputTransform = !!inputCase && inputCase !== 'camel';\n const hasOutputTransform = !!outputCase && outputCase !== 'camel';\n\n if (hasInputTransform || hasOutputTransform) {\n const inputBody =\n inputCase === 'snake'\n ? renderFieldsAsSnakeCase(model.fields, model.mode)\n : inputCase === 'pascal'\n ? renderFieldsAsPascalCase(model.fields, model.mode)\n : renderFields(model.fields, model.mode);\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...inputBody.map(l => ` ${l}`));\n lines.push(`}).transform(data => ({`);\n for (const field of model.fields) {\n const inputKey = applyCase(field.name, inputCase);\n const outputKey = applyCase(field.name, outputCase);\n if (field.optional) {\n // Conditional spread keeps the field optional (`k?: T`) in the inferred\n // z.output / z.input type, instead of widening to required-nullable (`k: T | undefined`).\n // Consumer code built with `...(x ? { k: x } : {})` is only assignable to the optional form.\n // When inputCase is set, the input schema uses `.nullish()` so the guard must reject both\n // null and undefined; otherwise `.optional()` only allows undefined.\n const guard = hasInputTransform ? `data.${inputKey} != null` : `data.${inputKey} !== undefined`;\n lines.push(` ...(${guard} ? { ${quoteKey(outputKey)}: data.${inputKey} } : {}),`);\n } else {\n lines.push(` ${quoteKey(outputKey)}: data.${inputKey},`);\n }\n }\n lines.push(`}));`);\n // When only outputCase is set, the developer-facing type is the schema's\n // pre-transform shape (camelCase). With inputCase, the post-transform\n // shape is what consumers work with.\n const typeSource = hasOutputTransform && !hasInputTransform ? 'input' : 'output';\n lines.push(`export type ${model.name} = z.${typeSource}<typeof ${model.name}>;`);\n return lines;\n }\n\n const body = renderFields(model.fields, model.mode);\n const bases = model.bases ?? [];\n if (bases.length > 0) {\n const head = bases[0]!;\n const tail = bases\n .slice(1)\n .map(b => `.extend(${b}.shape)`)\n .join('');\n lines.push(`export const ${model.name} = ${head}${tail}.extend({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n } else {\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n }\n\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n return lines;\n}\n\n/** Builds a Zod extension chain \"Head.extend(B.shape).extend(C.shape)...\" for a list of base names,\n * applying a per-base name resolver (e.g. choosing \"BaseInput\" for bases that have an Input variant). */\nfunction buildExtendChain(bases: string[], resolveName: (b: string) => string): { head: string; tail: string } {\n const head = resolveName(bases[0]!);\n const tail = bases\n .slice(1)\n .map(b => `.extend(${resolveName(b)}.shape)`)\n .join('');\n return { head, tail };\n}\n\nfunction collectEffectiveWritableFieldNames(modelName: string, modelMap: Map<string, ModelNode>): Set<string> {\n const model = modelMap.get(modelName);\n if (!model || model.type) return new Set();\n const result = new Set<string>();\n for (const base of model.bases ?? []) {\n for (const f of collectEffectiveWritableFieldNames(base, modelMap)) result.add(f);\n }\n for (const field of model.fields) {\n if (field.visibility === 'readonly') result.delete(field.name);\n else result.add(field.name);\n }\n return result;\n}\n\nfunction generateThreeSchemaModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n const lines: string[] = [];\n const name = model.name;\n\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const allFields = model.fields;\n\n const bases = model.bases ?? [];\n\n // Read schema — omit writeonly fields; extends parent read schema\n const readFields = allFields.filter(f => f.visibility !== 'writeonly');\n const readBody = renderFields(readFields, model.mode);\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => b);\n lines.push(`export const ${name} = ${head}${tail}.extend({`);\n } else {\n lines.push(`export const ${name} = ${wrapper}({`);\n }\n lines.push(...readBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name} = z.infer<typeof ${name}>;`);\n lines.push('');\n\n // Write schema — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read schema\n const writeFields = allFields.filter(f => f.visibility !== 'readonly');\n const writeBody = modelsWithInput ? renderInputFields(writeFields, modelsWithInput, model.mode) : renderFields(writeFields, model.mode);\n // Fields that become readonly in this model but were writable in a base must be omitted from\n // the base Input schema — Zod's .extend() cannot remove inherited fields.\n const fieldsToOmit = new Set<string>();\n if (bases.length > 0 && modelMap) {\n for (const field of allFields) {\n if (field.visibility === 'readonly') {\n for (const base of bases) {\n if (collectEffectiveWritableFieldNames(base, modelMap).has(field.name)) {\n fieldsToOmit.add(field.name);\n break;\n }\n }\n }\n }\n }\n const omitClause =\n fieldsToOmit.size > 0\n ? `.omit({ ${[...fieldsToOmit].map(f => `${quoteKey(f)}: true`).join(', ')} })`\n : '';\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => (modelsWithInput?.has(b) ? `${b}Input` : b));\n lines.push(`export const ${name}Input = ${head}${tail}${omitClause}.extend({`);\n } else {\n lines.push(`export const ${name}Input = ${wrapper}({`);\n }\n lines.push(...writeBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name}Input = z.infer<typeof ${name}Input>;`);\n\n return lines;\n}\n\n// ─── Fields ────────────────────────────────────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!caseTransform || caseTransform === 'camel') return name;\n if (caseTransform === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\nfunction renderFields(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderField(f, defaultMode));\n}\n\nfunction renderFieldsAsPascalCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const pascalKey = camelToPascal(f.name);\n let expr = renderType(f.type, 'pascal', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(pascalKey)}: ${expr},`;\n });\n}\n\nfunction renderFieldsAsSnakeCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const snakeKey = camelToSnake(f.name);\n let expr = renderType(f.type, 'snake', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n // .nullish() accepts null or undefined from the API; the transform coerces null → undefined\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(snakeKey)}: ${expr},`;\n });\n}\n\n/**\n * Append the modifier chain a declared field carries: nullability, then a default or optionality,\n * then the description.\n *\n * Takes a structural subset of `FieldNode` rather than the node itself, so an `OpParamNode` — which\n * is a `FieldNode` minus `visibility`, `deprecated` and `override` — can be rendered through the\n * same path. That is what lets the router, the SDK and OpenAPI agree on what an inline `query:` or\n * `headers:` field means.\n *\n * A default and `optional` are mutually exclusive on purpose: `.default()` already makes the input\n * side optional, and adding `.optional()` on top would widen the *output* type to include\n * `undefined`, which is exactly what a default exists to prevent.\n */\nexport function applyFieldModifiers(expr: string, field: Pick<FieldNode, 'nullable' | 'default' | 'optional' | 'description'>): string {\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n return expr;\n}\n\nfunction renderField(field: FieldNode, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderType(field.type, undefined, defaultMode);\n\n expr = applyFieldModifiers(expr, field);\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\n// ─── Type rendering ────────────────────────────────────────────────────────\n\n/**\n * Render a ContractKit AST type node as a Zod schema expression string.\n *\n * @param parseCaseTransform - When set, generates a `.transform()` that remaps incoming keys from\n * the given casing (`'snake'` | `'pascal'`) to camelCase for `inlineObject` types.\n * @param defaultMode - Fallback object mode (`'strict'` | `'strip'` | `'loose'`) when the node\n * doesn't specify its own mode.\n */\nexport function renderType(type: ContractTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderScalar(type);\n case 'array':\n return renderArray(type, parseCaseTransform, defaultMode);\n case 'tuple':\n return renderTuple(type);\n case 'record':\n return renderRecord(type);\n case 'enum':\n return renderEnum(type);\n case 'literal':\n return renderLiteral(type);\n case 'union':\n return renderUnion(type, parseCaseTransform, defaultMode);\n case 'discriminatedUnion':\n return renderDiscriminatedUnion(type, parseCaseTransform, defaultMode);\n case 'intersection':\n return renderIntersection(type, parseCaseTransform, defaultMode);\n case 'ref':\n return type.name;\n case 'lazy':\n return `z.lazy(() => ${renderType(type.inner, parseCaseTransform, defaultMode)})`;\n case 'inlineObject':\n return renderInlineObject(type, parseCaseTransform, defaultMode);\n default:\n return 'z.unknown()';\n }\n}\n\n/**\n * Render a regex source as a JS regex literal for `.regex(...)`. If the source already has\n * anchors (`^` at the start and/or an unescaped `$` at the end) we trust the user's intent\n * and emit it as-is; otherwise we wrap with `^...$` so contracts default to full-match\n * semantics. Forward slashes are always escaped since `/` is the literal delimiter.\n */\nfunction renderRegexLiteral(source: string): string {\n const body = source.replace(/\\//g, '\\\\/');\n if (regexHasAnchor(source)) return `/${body}/`;\n return `/^${body}$/`;\n}\n\nfunction regexHasAnchor(source: string): boolean {\n if (source.startsWith('^')) return true;\n if (!source.endsWith('$')) return false;\n // The trailing `$` is an anchor only if it isn't escaped — count immediately preceding\n // backslashes; an even count (including zero) means `$` is unescaped.\n let i = source.length - 2;\n let backslashes = 0;\n while (i >= 0 && source[i] === '\\\\') {\n backslashes++;\n i--;\n }\n return backslashes % 2 === 0;\n}\n\n/**\n * Coercion for the numeric scalars: convert a non-empty string, pass everything else through for\n * `z.number()` to judge.\n *\n * `z.coerce.number()` is `Number(v)`, which accepts far more than a number. `[]` and `''` become\n * `0`, `null` becomes `0`, `true` becomes `1` — so `{\"quantity\": []}` validated as `0` and the\n * handler ran on a value the client never sent. Only the string case is a real coercion; it exists\n * because query strings and headers arrive as text, and it stays because a JSON body carrying\n * `\"42\"` is common enough that rejecting it would break working callers.\n *\n * The `boolean` scalar below already has this shape and needed no change: its preprocess maps only\n * the two literal strings and hands everything else to `z.boolean()`, which rejects it.\n */\nconst NUMERIC_PREPROCESS = `(v) => (typeof v === 'string' && v.trim() !== '' ? Number(v) : v)`;\n\nfunction renderScalar(s: ScalarTypeNode): string {\n switch (s.name) {\n case 'string': {\n let e = 'z.string()';\n if (s.min !== undefined && s.max !== undefined) e += `.min(${s.min}).max(${s.max})`;\n else if (s.min !== undefined) e += `.min(${s.min})`;\n else if (s.max !== undefined) e += `.max(${s.max})`;\n if (s.len !== undefined) e += `.length(${s.len})`;\n if (s.regex) e += `.regex(${renderRegexLiteral(s.regex)})`;\n return e;\n }\n case 'number':\n case 'int': {\n // Constraints go on the inner schema, not the outer expression: `z.preprocess` returns\n // a ZodPipe, which has no `.min()`. Same shape as the `bigint` case below.\n let inner = s.name === 'int' ? 'z.number().int()' : 'z.number()';\n if (s.min !== undefined) inner += `.min(${s.min})`;\n if (s.max !== undefined) inner += `.max(${s.max})`;\n return `z.preprocess(${NUMERIC_PREPROCESS}, ${inner})`;\n }\n case 'bigint': {\n let inner = 'z.bigint()';\n if (s.min !== undefined) inner += `.min(${s.min}n)`;\n if (s.max !== undefined) inner += `.max(${s.max}n)`;\n return `z.preprocess((val) => typeof val === 'string' ? BigInt(val.replace(/n$/, '')) : val, ${inner})`;\n }\n case 'decimal': {\n // Deliberately no output `.transform()`: `isRevalidatable` in codegen-operation treats\n // every scalar as idempotent under re-parse, which `server.validateResponses` relies on.\n // Preprocess passes an already-`Decimal` value straight through, so parse(parse(x)) is\n // stable. Modelling this on `_ZodInterval` — which does transform — would break that.\n const checks: string[] = [];\n if (s.scale !== undefined) checks.push(`v.decimalPlaces() <= ${s.scale}`);\n if (s.min !== undefined) checks.push(`v.gte('${escapeString(String(s.min))}')`);\n if (s.max !== undefined) checks.push(`v.lte('${escapeString(String(s.max))}')`);\n if (checks.length === 0) return '_ZodDecimal';\n const messageParts: string[] = [];\n if (s.scale !== undefined) messageParts.push(`at most ${s.scale} decimal place${s.scale === 1 ? '' : 's'}`);\n if (s.min !== undefined) messageParts.push(`at least ${s.min}`);\n if (s.max !== undefined) messageParts.push(`at most ${s.max}`);\n return `_ZodDecimal.refine((v) => ${checks.join(' && ')}, { message: 'Must be ${escapeString(messageParts.join(', '))}' })`;\n }\n case 'boolean':\n return `z.preprocess((v) => v === 'true' ? true : v === 'false' ? false : v, z.boolean())`;\n case 'date': {\n const fmt = s.format ?? 'yyyy-MM-dd';\n 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)}' }))`;\n }\n case 'time': {\n const fmt = s.format ?? 'HH:mm:ss';\n 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)}' }))`;\n }\n case 'datetime':\n return '_ZodDatetime';\n case 'interval':\n return '_ZodInterval';\n case 'duration': {\n const validParts = [`val instanceof Duration && val.isValid`];\n if (s.min !== undefined) validParts.push(`val.toMillis() >= Duration.fromISO('${s.min}').toMillis()`);\n if (s.max !== undefined) validParts.push(`val.toMillis() <= Duration.fromISO('${s.max}').toMillis()`);\n const validation = validParts.join(' && ');\n let message = 'Must be an ISO 8601 duration';\n if (s.min !== undefined && s.max !== undefined) message += ` between ${s.min} and ${s.max}`;\n else if (s.min !== undefined) message += ` of at least ${s.min}`;\n else if (s.max !== undefined) message += ` of at most ${s.max}`;\n return `z.preprocess((val) => typeof val === 'string' ? Duration.fromISO(val) : val, z.custom<Duration>((val) => ${validation}, { message: '${message}' }))`;\n }\n case 'email':\n return 'z.email()';\n case 'url':\n return 'z.url()';\n case 'uuid':\n return 'z.uuid()';\n case 'unknown':\n return 'z.unknown()';\n case 'null':\n return 'z.null()';\n case 'object':\n return 'z.record(z.string(), z.unknown())';\n case 'binary':\n return '_ZodBinary';\n case 'json':\n return '_ZodJson';\n default: {\n const _exhaustive: never = s.name;\n throw new Error(`plugin-typescript: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\nfunction renderArray(a: ArrayTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n let e = `z.array(${renderType(a.item, parseCaseTransform, defaultMode)})`;\n if (a.min !== undefined) e += `.min(${a.min})`;\n if (a.max !== undefined) e += `.max(${a.max})`;\n return e;\n}\n\nfunction renderTuple(t: TupleTypeNode): string {\n return `z.tuple([${t.items.map(i => renderType(i)).join(', ')}])`;\n}\n\nfunction renderRecord(r: RecordTypeNode): string {\n return `z.record(${renderType(r.key)}, ${renderType(r.value)})`;\n}\n\nfunction renderEnum(e: EnumTypeNode): string {\n const vals = e.values.map(v => `\"${escapeString(v)}\"`).join(', ');\n return `z.enum([${vals}])`;\n}\n\nfunction renderLiteral(l: LiteralTypeNode): string {\n if (typeof l.value === 'string') return `z.literal(\"${escapeString(l.value)}\")`;\n return `z.literal(${l.value})`;\n}\n\nfunction renderUnion(u: UnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.union([${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderDiscriminatedUnion(u: DiscriminatedUnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.discriminatedUnion(\"${escapeString(u.discriminator)}\", [${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderIntersection(i: IntersectionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const [first, ...rest] = i.members;\n // When the pattern is ref & (ref | inlineObject)*, use .extend() chains to\n // produce a single ZodObject. .and() breaks strict objects — each strict side\n // rejects the other side's keys during intersection parsing, and ZodIntersection\n // has no .strict() method.\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n expr += `.extend(${member.name}.shape)`;\n } else {\n const m = member as InlineObjectTypeNode;\n const fieldLines =\n parseCaseTransform === 'snake'\n ? renderFieldsAsSnakeCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : parseCaseTransform === 'pascal'\n ? renderFieldsAsPascalCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : m.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderType(first!, parseCaseTransform, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderType(member, parseCaseTransform, defaultMode)})`;\n }\n return expr;\n}\n\nfunction renderInlineObject(o: InlineObjectTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const wrapper = modeToWrapper(o.mode ?? defaultMode ?? 'strict');\n if (parseCaseTransform === 'snake') {\n const snakeLines = renderFieldsAsSnakeCase(o.fields, defaultMode);\n const joined = snakeLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const snakeKey = camelToSnake(f.name);\n // Optional fields use .nullish() on input. Conditional spread (instead of `?? undefined`)\n // keeps the key optional in the inferred output type (`k?: T`) rather than widening to\n // required-nullable (`k: T | undefined`).\n if (f.optional) {\n return ` ...(data.${snakeKey} != null ? { ${quoteKey(f.name)}: data.${snakeKey} } : {}),`;\n }\n return ` ${quoteKey(f.name)}: data.${snakeKey},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n if (parseCaseTransform === 'pascal') {\n const pascalLines = renderFieldsAsPascalCase(o.fields, defaultMode);\n const joined = pascalLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const pascalKey = camelToPascal(f.name);\n if (f.optional) {\n return ` ...(data.${pascalKey} != null ? { ${quoteKey(f.name)}: data.${pascalKey} } : {}),`;\n }\n return ` ${quoteKey(f.name)}: data.${pascalKey},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n const fields = o.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${wrapper}({\\n${fields}\\n})`;\n}\n\n// ─── Input type rendering ─────────────────────────────────────────────────\n\n/**\n * The request-side rendering of a scalar. A pure passthrough today, and the seam where a genuine\n * input/wire split would live.\n *\n * The docstring here used to claim it \"coerces from string input\", describing a distinction the\n * body does not make: `XInput` is a single exported `const`, and `generateParamValidation`'s ref\n * branch uses that same schema for `query: X` that the body path uses for\n * `request: { application/json: X }`. Making it strict would break query-by-model; leaving it\n * coercing leaves a JSON body accepting string-shaped numbers. A real split needs a second emitted\n * variant (`XInputWire`) plus the import plumbing to reach it, which is separate work — the\n * narrowed coercion in `renderScalar` closes the soundness hole in the meantime.\n */\nfunction renderInputScalar(s: ScalarTypeNode): string {\n return renderScalar(s);\n}\n\n/**\n * Like renderType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers, and coerces scalars from strings.\n * Used for Input (write) schema fields so that sub-type references also\n * point to their Input variants.\n */\nexport function renderInputType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderInputScalar(type);\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n let e = `z.array(${renderInputType(type.item, modelsWithInput, defaultMode)})`;\n if (type.min !== undefined) e += `.min(${type.min})`;\n if (type.max !== undefined) e += `.max(${type.max})`;\n return e;\n }\n case 'tuple':\n return `z.tuple([${type.items.map(i => renderInputType(i, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'record':\n return `z.record(${renderInputType(type.key, modelsWithInput, defaultMode)}, ${renderInputType(type.value, modelsWithInput, defaultMode)})`;\n case 'union':\n return `z.union([${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'discriminatedUnion':\n return `z.discriminatedUnion(\"${escapeString(type.discriminator)}\", [${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderInputField(f, modelsWithInput ?? new Set(), defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderInputType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderInputType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'lazy':\n return `z.lazy(() => ${renderInputType(type.inner, modelsWithInput, defaultMode)})`;\n case 'inlineObject': {\n const fields = type.fields\n .flatMap(f => renderInputField(f, modelsWithInput ?? new Set(), defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n default:\n return renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderInputType(field.type, modelsWithInput, defaultMode);\n\n expr = applyFieldModifiers(expr, field);\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\nfunction renderInputFields(fields: FieldNode[], modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderInputField(f, modelsWithInput, defaultMode));\n}\n\n// ─── Query type rendering ─────────────────────────────────────────────────\n\n/**\n * Like renderType, but wraps array types with z.preprocess to handle\n * query strings where a single value arrives as a string instead of a string[].\n * Also uses Input variants for model refs when modelsWithInput is provided.\n */\nexport function renderQueryType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'array': {\n const inner = modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n return `z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner})`;\n }\n case 'inlineObject': {\n const fields = type.fields.map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`).join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderQueryType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderQueryType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n default:\n return modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderQueryField(field: FieldNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n let expr =\n field.type.kind === 'array'\n ? renderQueryType(field.type, modelsWithInput, defaultMode)\n : modelsWithInput\n ? renderInputType(field.type, modelsWithInput, defaultMode)\n : renderType(field.type, undefined, defaultMode);\n\n expr = applyFieldModifiers(expr, field);\n\n return `${quoteKey(field.name)}: ${expr},`;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\nfunction quoteKey(name: string): string {\n return isValidIdentifier(name) ? name : `'${name}'`;\n}\n\n// ─── String escaping ──────────────────────────────────────────────────────\n\nfunction escapeString(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r');\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction rootNeedsDateTime(root: ContractRootNode): boolean {\n return root.models.some(m => (m.type && typeNeedsDateTime(m.type)) || m.fields.some(f => typeNeedsDateTime(f.type)));\n}\n\n/** Returns true if `type` (recursively) contains a scalar with the given `name`. */\nexport function typeNeedsScalar(type: ContractTypeNode, name: string): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === name;\n case 'array':\n return typeNeedsScalar(type.item, name);\n case 'tuple':\n return type.items.some(i => typeNeedsScalar(i, name));\n case 'record':\n return typeNeedsScalar(type.key, name) || typeNeedsScalar(type.value, name);\n case 'union':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'discriminatedUnion':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'intersection':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'lazy':\n return typeNeedsScalar(type.inner, name);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsScalar(f.type, name));\n default:\n return false;\n }\n}\n\n/** Returns true if any model in `root` uses a scalar with the given `name`. */\nexport function rootNeedsScalar(root: ContractRootNode, name: string): boolean {\n return root.models.some(m => (m.type && typeNeedsScalar(m.type, name)) || m.fields.some(f => typeNeedsScalar(f.type, name)));\n}\n\n/** Returns true if `type` (recursively) contains a `date`, `time`, or `datetime` scalar. */\nexport function typeNeedsDateTime(type: ContractTypeNode): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === 'date' || type.name === 'time' || type.name === 'datetime';\n case 'array':\n return typeNeedsDateTime(type.item);\n case 'union':\n return type.members.some(typeNeedsDateTime);\n case 'discriminatedUnion':\n return type.members.some(typeNeedsDateTime);\n case 'intersection':\n return type.members.some(typeNeedsDateTime);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsDateTime(f.type));\n default:\n return false;\n }\n}\n\n/** Collect model names referenced in `root` that are not defined locally (need to be imported). */\nexport function collectExternalRefs(root: ContractRootNode): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (model.bases?.[0] && !localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n }\n\n for (const name of localNames) refs.delete(name);\n return [...refs].sort();\n}\n\n/** Collect external Input variant refs needed for Input schema fields. */\nexport function collectExternalInputRefs(root: ContractRootNode, modelsWithInput: Set<string>): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (!modelsWithInput.has(model.name)) continue;\n // Type alias: collect Input refs from the aliased type expression.\n if (model.type) {\n collectInputTypeRefs(model.type, refs, modelsWithInput);\n continue;\n }\n // When a model extends an external parent that has an Input variant,\n // the write schema extends ParentInput — so we need to import it.\n if (model.bases?.[0] && modelsWithInput.has(model.bases?.[0]) && !localNames.has(model.bases?.[0])) {\n refs.add(`${model.bases?.[0]}Input`);\n }\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n for (const field of writeFields) {\n collectInputTypeRefs(field.type, refs, modelsWithInput);\n }\n }\n\n // Remove locally defined Input variants (generated in this file)\n for (const name of localNames) {\n refs.delete(`${name}Input`);\n }\n\n return [...refs].sort();\n}\n\nfunction collectInputTypeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(i => collectInputTypeRefs(i, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeRefs(type.key, out, modelsWithInput);\n collectInputTypeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\n/**\n * Topologically sort models so dependencies are emitted before dependents.\n * Falls back to source order for cycles (which would need z.lazy at runtime).\n */\nexport function topoSortModels(models: ModelNode[]): ModelNode[] {\n const localNames = new Set(models.map(m => m.name));\n const modelMap = new Map(models.map(m => [m.name, m]));\n\n // Build adjacency: model name → set of local model names it depends on\n const deps = new Map<string, Set<string>>();\n for (const model of models) {\n const refs = new Set<string>();\n if (model.bases?.[0] && localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // Keep only local dependencies\n const localDeps = new Set<string>();\n for (const r of refs) {\n if (localNames.has(r) && r !== model.name) localDeps.add(r);\n }\n deps.set(model.name, localDeps);\n }\n\n // Kahn's algorithm\n const inDegree = new Map<string, number>();\n for (const name of localNames) inDegree.set(name, 0);\n for (const [, d] of deps) {\n for (const dep of d) {\n inDegree.set(dep, (inDegree.get(dep) ?? 0) + 1);\n }\n }\n\n // Note: inDegree counts how many models *depend on* this model,\n // but for Kahn's we need how many dependencies each model has.\n // Re-do: inDegree = number of unresolved deps for each model.\n const remaining = new Map<string, Set<string>>();\n for (const [name, d] of deps) {\n remaining.set(name, new Set(d));\n }\n\n const queue: string[] = [];\n for (const name of localNames) {\n if (remaining.get(name)!.size === 0) queue.push(name);\n }\n\n const sorted: ModelNode[] = [];\n while (queue.length > 0) {\n const name = queue.shift()!;\n sorted.push(modelMap.get(name)!);\n // Remove this model from all dependents' remaining sets\n for (const [other, rem] of remaining) {\n if (rem.delete(name) && rem.size === 0) {\n queue.push(other);\n }\n }\n }\n\n // Append any models not yet emitted (cycles)\n for (const model of models) {\n if (!sorted.includes(model)) sorted.push(model);\n }\n\n return sorted;\n}\n\n/**\n * Resolve the import path for an external model reference.\n * When a codegen context is available, computes the correct relative path\n * from the current file to the referenced model's output file.\n * Falls back to same-directory PascalCase → dot.case convention.\n */\nexport function resolveImportPath(refName: string, context?: ContractCodegenContext): string {\n if (context) {\n const refOutPath = context.modelOutPaths.get(refName);\n if (refOutPath) {\n const fromDir = dirname(context.currentOutPath);\n let rel = relative(fromDir, refOutPath);\n // Replace .ts extension with .js for ESM imports\n rel = rel.replace(/\\.ts$/, '.js');\n // Ensure relative path starts with ./ or ../\n if (!rel.startsWith('.')) rel = './' + rel;\n return rel;\n }\n }\n // Fallback: assume same directory, use PascalCase → dot.case convention\n const moduleName = pascalToDotCase(refName);\n return `./${moduleName}.js`;\n}\n\n/** Convert PascalCase to dot-separated lowercase: CounterpartyAccount → counterparty.account */\nexport function pascalToDotCase(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/g, '$1.$2').toLowerCase();\n}\n","import { dirname, relative } from 'node:path';\nimport type { ContractTypeNode, FieldNode, ScalarTypeNode } from '@contractkit/core';\n\n/** Declaration emitted into generated files that reference the `json` scalar. */\nexport const JSON_VALUE_TYPE_DECL = 'export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };';\n\n/** Quote a property name unless it is already a valid bare TypeScript identifier. */\nexport function quoteKey(name: string): string {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? name : `'${name}'`;\n}\n\n/** Escape text for safe inclusion inside a JSDoc block comment: neutralize the\n * block-comment terminator sequence and split embedded newlines into separate\n * ` * ` continuation lines. Returns the content lines (WITHOUT a leading prefix). */\nexport function escapeJsDocLines(text: string): string[] {\n return text.replace(/\\*\\//g, '*\\\\/').split('\\n');\n}\n\n/** Escape a string for inclusion inside a single-quoted TypeScript string literal. */\nexport function escapeSingleQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r');\n}\n\n/**\n * Render the markdown link back to the `.ck` declaration a generated construct came from, as\n * `[label](./path/to/file.ck#L12)`. Returns the link only; callers supply the surrounding prose\n * and comment prefix, since some sites emit it inside a JSDoc block and others inside a `//` line.\n *\n * The path is relative to the emitted file's own directory, so it resolves when the reader clicks\n * it from wherever the file was written. `outPath` is optional because codegen can run without a\n * destination (the prettier plugin, and several tests), in which case the source path is used\n * as-is.\n *\n * Not `file://./path`: `file://` opens an authority component, so the `.` parses as the host and\n * the link resolves to nothing. A plain relative path is the correct form.\n */\nexport function sourceLink(label: string, outPath: string | undefined, sourceFile: string, line?: number): string {\n const rel = outPath ? relative(dirname(outPath), sourceFile) : sourceFile;\n const href = rel.startsWith('.') ? rel : `./${rel}`;\n return `[${label}](${href}${line === undefined ? '' : `#L${line}`})`;\n}\n\n/** Convert an HTTP header name (e.g. `preference-applied`, `X-Request-ID`, `ETag`) to camelCase for use as a JS property. */\nexport function headerNameToProperty(name: string): string {\n const parts = name.split(/[-_]/).filter(Boolean);\n return parts\n .map((p, i) => {\n const lower = p.toLowerCase();\n return i === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);\n })\n .join('');\n}\n\n// ─── TypeScript type rendering ────────────────────────────────────────────\n\n/**\n * Which runtime the emitted types describe. A few scalars have no single correct TypeScript\n * type: `binary` is a `Blob` in a fetch-based client but a `Buffer` on a Node server. Everything\n * else renders identically for both targets. Defaults to `'client'`.\n */\nexport type TsRenderTarget = 'client' | 'server';\n\n/**\n * Render a contract type as a plain TypeScript type expression. Model refs render as their bare\n * name; use `renderInputTsType` / `renderOutputTsType` to substitute Input/Output variants.\n *\n * @param target Runtime the type describes; only `binary` differs (`Buffer` vs `Blob`).\n */\nexport function renderTsType(type: ContractTypeNode, target: TsRenderTarget = 'client'): string {\n switch (type.kind) {\n case 'scalar':\n return renderTsScalar(type.name, target);\n case 'array': {\n const inner = renderTsType(type.item, target);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'tuple':\n return `[${type.items.map(i => renderTsType(i, target)).join(', ')}]`;\n case 'record':\n return `Record<${renderTsType(type.key, target)}, ${renderTsType(type.value, target)}>`;\n case 'enum':\n return type.values.map(v => `'${escapeSingleQuoted(v)}'`).join(' | ');\n case 'literal':\n return typeof type.value === 'string' ? `'${escapeSingleQuoted(type.value)}'` : String(type.value);\n case 'union':\n return type.members.map(m => renderTsType(m, target)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderTsType(m, target)).join(' | ');\n case 'intersection':\n return type.members.map(m => renderTsType(m, target)).join(' & ');\n case 'ref':\n return type.name;\n case 'lazy':\n return renderTsType(type.inner, target);\n case 'inlineObject':\n return renderTsInlineObject(type.fields, target);\n default:\n return 'unknown';\n }\n}\n\nfunction renderTsScalar(name: ScalarTypeNode['name'], target: TsRenderTarget): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n return 'string';\n case 'number':\n case 'int':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'decimal':\n // The one scalar whose wire view and server view agree — see the note on this\n // function and on `serverTsScalar`. A `decimal` travels as a quoted string, and both\n // the router (via `_ZodDecimal`) and the SDK (via the generated `reviveX` functions)\n // hand the developer a real `Decimal`, so there is no `target` split to make.\n return 'Decimal';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'time':\n case 'datetime':\n // Luxon objects on both sides. The router parses them via `_ZodDatetime`, and the SDK\n // rehydrates them in its generated revivers, so `string` was a claim neither honoured.\n return 'DateTime';\n case 'duration':\n return 'Duration';\n case 'interval':\n // The exception: `_ZodInterval` transforms back to an ISO string on output, so a\n // string is genuinely what a consumer receives.\n return 'string';\n case 'null':\n return 'null';\n case 'unknown':\n return 'unknown';\n case 'object':\n return 'Record<string, unknown>';\n case 'binary':\n // Node servers hand the handler a Buffer (matching `_ZodBinary`); fetch clients get a Blob.\n return target === 'server' ? 'Buffer' : 'Blob';\n case 'json':\n return 'JsonValue';\n default: {\n const _exhaustive: never = name;\n throw new Error(`plugin-typescript: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\nfunction renderTsInlineObject(fields: FieldNode[], target: TsRenderTarget): string {\n const entries = fields.map(f => {\n const opt = f.optional ? '?' : '';\n return `${quoteKey(f.name)}${opt}: ${renderTsType(f.type, target)}`;\n });\n return `{ ${entries.join('; ')} }`;\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers. Used for request-side types\n * (body, params, query, headers).\n *\n * @param target Runtime the type describes; only `binary` differs (`Buffer` vs `Blob`).\n */\nexport function renderInputTsType(type: ContractTypeNode, modelsWithInput?: Set<string>, target: TsRenderTarget = 'client'): string {\n if (!modelsWithInput || modelsWithInput.size === 0) return renderTsType(type, target);\n switch (type.kind) {\n case 'ref':\n return modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n const inner = renderInputTsType(type.item, modelsWithInput, target);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderInputTsType(m, modelsWithInput, target)).join(' & ');\n case 'union':\n return type.members.map(m => renderInputTsType(m, modelsWithInput, target)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderInputTsType(m, modelsWithInput, target)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderInputTsType(f.type, modelsWithInput, target)}`).join('; ')} }`;\n case 'lazy':\n return renderInputTsType(type.inner, modelsWithInput, target);\n default:\n return renderTsType(type, target);\n }\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Output variant\n * (post-transform wire shape) when the model has format(output=...) or\n * transitively references one. Used for response-side types in routers\n * and SDK return types.\n *\n * @param target Runtime the type describes; only `binary` differs (`Buffer` vs `Blob`).\n */\nexport function renderOutputTsType(type: ContractTypeNode, modelsWithOutput?: Set<string>, target: TsRenderTarget = 'client'): string {\n if (!modelsWithOutput || modelsWithOutput.size === 0) return renderTsType(type, target);\n switch (type.kind) {\n case 'ref':\n return modelsWithOutput.has(type.name) ? `${type.name}Output` : type.name;\n case 'array': {\n const inner = renderOutputTsType(type.item, modelsWithOutput, target);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput, target)).join(' & ');\n case 'union':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput, target)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput, target)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderOutputTsType(f.type, modelsWithOutput, target)}`).join('; ')} }`;\n case 'lazy':\n return renderOutputTsType(type.inner, modelsWithOutput, target);\n default:\n return renderTsType(type, target);\n }\n}\n","/**\n * The emitted decimal.js runtime shared by every generator that renders a `decimal` scalar.\n *\n * `_ZodBinary`/`_ZodDatetime`/`_ZodInterval` are duplicated as literals across codegen-contract,\n * codegen-operation and codegen-mcp, and have already drifted once (the three files emit their\n * luxon import lists in two different orders). The decimal runtime is defined once here so the\n * three call sites cannot disagree about it; each still decides *whether* to emit it with its own\n * detection strategy, which is the part that legitimately differs between them.\n */\n\n/**\n * The decimal.js import — **named, not default**.\n *\n * `decimal.d.ts` declares `Decimal` three times over: a class, a namespace, and a function, with\n * `export default Decimal` alongside. Under the `NodeNext` resolution the scaffolded SDK uses\n * (`module: NodeNext` + `\"type\": \"module\"`), the default export resolves to the *namespace*\n * meaning, so `import Decimal from 'decimal.js'` fails to compile with \"Cannot use namespace\n * 'Decimal' as a type\" and \"Property 'set' does not exist\". The named import binds the merged\n * class and is the only form that typechecks.\n */\nexport const DECIMAL_IMPORT = `import { Decimal } from 'decimal.js';`;\n\n/**\n * Global decimal.js configuration, emitted in **every** file that imports `Decimal` — plain-types\n * mode included, where there is no Zod schema but `String(value)` and `JSON.stringify` still run.\n *\n * Load-bearing, not cosmetic. decimal.js switches to exponential\n * notation outside `toExpNeg`/`toExpPos` (defaults -7/21), so without it `new Decimal('0.00000001')`\n * serializes as `\"1e-8\"` and any peer validating `^-?\\d+(\\.\\d+)?$` rejects it. It is the only lever\n * that reaches the `JSON.stringify` Koa runs over `ctx.body`, which we do not otherwise control.\n *\n */\nexport const DECIMAL_CONFIG_LINE = `Decimal.set({ toExpNeg: -9e15, toExpPos: 9e15 });`;\n\n/**\n * The Zod schema for a `decimal`.\n *\n * Deliberately has no output `.transform()`. `isRevalidatable` in codegen-operation treats every\n * scalar as idempotent under re-parse — the assumption `server.validateResponses` rests on — and\n * preprocess passes an already-`Decimal` value through untouched, so it holds.\n *\n * A raw JSON number fails validation rather than being coerced: by the time one reaches us it has\n * already been through an IEEE-754 double, which is the loss this scalar exists to prevent. Bad\n * strings are returned unchanged from preprocess rather than throwing, so they surface as an\n * ordinary Zod issue instead of a `DecimalError` escaping the parse.\n */\nexport const DECIMAL_ZOD_SCHEMA_LINE = `const _ZodDecimal = z.preprocess((val) => { if (typeof val !== 'string') return val; try { return new Decimal(val); } catch { return val; } }, z.custom<Decimal>((val) => Decimal.isDecimal(val), { message: 'Must be an exact decimal sent as a quoted string, e.g. \"1250.00\"' }));`;\n\n/** The decimal runtime for a file that also holds Zod schemas, in emission order. */\nexport const DECIMAL_PRELUDE_LINES: readonly string[] = [DECIMAL_CONFIG_LINE, DECIMAL_ZOD_SCHEMA_LINE];\n","import type { ContractTypeNode, FieldNode, ModelNode, ScalarTypeNode } from '@contractkit/core';\n\n/**\n * Emitters for the `reviveX` functions that rehydrate `decimal` fields in an SDK response.\n *\n * A decimal arrives as a quoted JSON string, but the generated types say `Decimal`, so something\n * has to construct one. The SDK cannot do it the way `bigint` does — `bigIntReviver` works only\n * because bigint invented a tagged `\"123n\"` wire encoding, and `\"10.50\"` is indistinguishable from\n * an ordinary string without knowing the schema. Nor can it re-parse the response through the Zod\n * schema: `XOutput` is a `z.output<>` type alias with no runtime value behind it, and models\n * default to `z.strictObject`, so any field the server added would throw in every deployed client.\n *\n * So the knowledge lives in generated code instead: one function per model that walks to the field\n * positions a decimal can occupy and converts in place. Mutating rather than rebuilding keeps the\n * cost proportional to the number of decimal fields, and preserves unknown server-added keys —\n * the forward compatibility a strict re-parse would destroy.\n *\n * Emitted from the AST, so zod mode and plain-types mode produce identical runtime behaviour.\n */\n\nexport interface ReviveCodegenOptions {\n /** Models that carry a revivable scalar, directly or transitively. Only these get a reviver. */\n modelsWithDecimal: Set<string>;\n /**\n * Which scalars need rehydrating from their wire form. Defaults to `decimal`, the only scalar\n * whose runtime type currently differs from what `JSON.parse` produces.\n *\n * A set rather than a boolean because the question a reviver asks is not \"does this reach a\n * decimal\" but \"which conversion does this leaf need\" — and the answer becomes plural as soon\n * as a second scalar joins.\n */\n revivableScalars?: ReadonlySet<ScalarTypeNode['name']>;\n /** Models with an `Output` variant, which need a second reviver keyed by the output casing. */\n modelsWithOutput?: Set<string>;\n /** Every model in scope, for resolving discriminated-union members to their literal tag. */\n modelMap?: Map<string, ModelNode>;\n}\n\n/**\n * The per-file coercion helpers, keyed by the call prefix that identifies them in emitted text.\n *\n * A file gets only the helpers its revivers actually call, decided by scanning the emitted lines\n * — the same text-derived idiom the reviver and type imports use, and for the same reason: a\n * predicate computed separately can drift and leave an unused local behind.\n *\n * Each one takes the raw JSON value and throws a `TypeError` naming the path rather than\n * returning something invalid, because a silently wrong `DateTime` surfaces much further from\n * the cause than a throw at the boundary does.\n */\nexport const COERCE_DECLS: Record<string, string[]> = {\n '__dec(': [\n `const __dec = (v: unknown, path: string): Decimal => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected a decimal string at '\\${path}', received \\${typeof v} — decimals must be sent as quoted JSON strings.\\`);`,\n ` }`,\n ` try {`,\n ` return new Decimal(v);`,\n ` } catch {`,\n ` throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' is not a valid decimal.\\`);`,\n ` }`,\n `};`,\n ],\n '__dt(': [\n `const __dt = (v: unknown, path: string): DateTime => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected an ISO 8601 string at '\\${path}', received \\${typeof v}.\\`);`,\n ` }`,\n ` const d = DateTime.fromISO(v);`,\n ` if (!d.isValid) throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' is not a valid ISO 8601 datetime.\\`);`,\n ` return d;`,\n `};`,\n ],\n '__dtf(': [\n `const __dtf = (v: unknown, path: string, fmt: string): DateTime => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected a string at '\\${path}' in format \\${fmt}, received \\${typeof v}.\\`);`,\n ` }`,\n ` const d = DateTime.fromFormat(v, fmt);`,\n ` if (!d.isValid) throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' does not match format \\${fmt}.\\`);`,\n ` return d;`,\n `};`,\n ],\n '__dur(': [\n `const __dur = (v: unknown, path: string): Duration => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected an ISO 8601 duration string at '\\${path}', received \\${typeof v}.\\`);`,\n ` }`,\n ` const d = Duration.fromISO(v);`,\n ` if (!d.isValid) throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' is not a valid ISO 8601 duration.\\`);`,\n ` return d;`,\n `};`,\n ],\n};\n\n/** Back-compat alias: the decimal helper alone, which several call sites still name directly. */\nexport const DECIMAL_COERCE_DECL = COERCE_DECLS['__dec(']!;\n\n/** The helper declarations `lines` actually calls, in a stable order. */\nexport function coerceDeclsFor(lines: string[]): string[] {\n const haystack = lines.join('\\n');\n return Object.entries(COERCE_DECLS)\n .filter(([prefix]) => haystack.includes(prefix))\n .flatMap(([, decl]) => decl);\n}\n\n/** Luxon classes referenced by the helpers `lines` calls, for the importing file to bring in. */\nexport function coerceLuxonImports(lines: string[]): string[] {\n const haystack = lines.join('\\n');\n const needed = new Set<string>();\n if (haystack.includes('__dt(') || haystack.includes('__dtf(')) needed.add('DateTime');\n if (haystack.includes('__dur(')) needed.add('Duration');\n return [...needed].sort();\n}\n\n/** `reviveInvoice` / `reviveInvoiceOutput`. */\nexport function reviveFnName(model: string, variant: 'base' | 'output' = 'base'): string {\n return `revive${model}${variant === 'output' ? 'Output' : ''}`;\n}\n\nfunction applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!caseTransform || caseTransform === 'camel') return name;\n if (caseTransform === 'snake') return name.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/**\n * Scalars whose runtime type differs from what `JSON.parse` produces, and which a reviver\n * therefore has to rehydrate. The default of {@link ReviveCodegenOptions.revivableScalars}.\n *\n * `interval` is excluded: `_ZodInterval` ends in `.transform(v => v.toISO()!)`, so its inferred\n * output type is already `string` and there is nothing to revive it to. Covering it means making\n * that round-trip idempotent first, which the router's `isRevalidatable` also depends on.\n */\nexport const DEFAULT_REVIVABLE_SCALARS: ReadonlySet<ScalarTypeNode['name']> = new Set([\n 'decimal',\n 'date',\n 'time',\n 'datetime',\n 'duration',\n]);\n\n/** Whether a type reaches a revivable scalar, following refs through `modelsWithDecimal`. */\nexport function typeReachesDecimal(type: ContractTypeNode, opts: ReviveCodegenOptions): boolean {\n switch (type.kind) {\n case 'scalar':\n return (opts.revivableScalars ?? DEFAULT_REVIVABLE_SCALARS).has(type.name);\n case 'ref':\n return opts.modelsWithDecimal.has(type.name);\n case 'array':\n return typeReachesDecimal(type.item, opts);\n case 'lazy':\n return typeReachesDecimal(type.inner, opts);\n case 'tuple':\n return type.items.some(t => typeReachesDecimal(t, opts));\n case 'record':\n // Value only, deliberately unlike `typeHasScalar` in core, which also checks the key.\n // That one answers \"is this scalar mentioned\", which decides imports; this one answers\n // \"is there a value to rehydrate\", and a JSON object key is always a string — there is\n // nothing at a key position for a reviver to convert.\n return typeReachesDecimal(type.value, opts);\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n return type.members.some(t => typeReachesDecimal(t, opts));\n case 'inlineObject':\n return type.fields.some(f => typeReachesDecimal(f.type, opts));\n default:\n return false;\n }\n}\n\n/**\n * The statement that rehydrates one scalar leaf, or nothing when the scalar needs no conversion.\n *\n * `date` and `time` carry their format on the node, and the reviver has to parse with the same\n * format the schema validates against — which is why the helper takes it as an argument rather\n * than baking one in. Defaults match `renderTsScalar`'s.\n *\n * `interval` is deliberately absent. `_ZodInterval` ends in `.transform(v => v.toISO()!)`, so its\n * inferred output is a string and there is nothing to revive it to; covering it means making that\n * round-trip idempotent first, which `isRevalidatable` in the router also depends on.\n */\nfunction scalarCoercion(type: ScalarTypeNode, slot: string, path: string, opts: ReviveCodegenOptions): string[] {\n if (!(opts.revivableScalars ?? DEFAULT_REVIVABLE_SCALARS).has(type.name)) return [];\n switch (type.name) {\n case 'decimal':\n return [`${slot} = __dec(${slot}, '${path}');`];\n case 'datetime':\n return [`${slot} = __dt(${slot}, '${path}');`];\n case 'duration':\n return [`${slot} = __dur(${slot}, '${path}');`];\n case 'date':\n return [`${slot} = __dtf(${slot}, '${path}', '${type.format ?? 'yyyy-MM-dd'}');`];\n case 'time':\n return [`${slot} = __dtf(${slot}, '${path}', '${type.format ?? 'HH:mm:ss'}');`];\n default:\n return [];\n }\n}\n\n/** Fresh local names, so nested loops in one function body cannot collide. */\nclass Scope {\n private n = 0;\n next(prefix: string): string {\n return `__${prefix}${this.n++}`;\n }\n}\n\n/**\n * Statements that hydrate `slot` — an assignable expression — in place.\n *\n * `path` is threaded purely for the error message; it is what tells a consumer *which* field of a\n * large response was malformed.\n */\nfunction emit(slot: string, type: ContractTypeNode, path: string, opts: ReviveCodegenOptions, scope: Scope, variant: 'base' | 'output'): string[] {\n switch (type.kind) {\n case 'scalar':\n return scalarCoercion(type, slot, path, opts);\n\n case 'ref':\n return opts.modelsWithDecimal.has(type.name) ? [`${reviveRefName(type.name, opts, variant)}(${slot} as never);`] : [];\n\n case 'lazy':\n return emit(slot, type.inner, path, opts, scope, variant);\n\n case 'array': {\n if (!typeReachesDecimal(type.item, opts)) return [];\n const arr = scope.next('a');\n const i = scope.next('i');\n const inner = emit(`${arr}[${i}]`, type.item, `${path}[]`, opts, scope, variant);\n return [\n `{`,\n ` const ${arr} = ${slot} as unknown[];`,\n ` for (let ${i} = 0; ${i} < ${arr}.length; ${i}++) {`,\n ...inner.map(l => ` ${l}`),\n ` }`,\n `}`,\n ];\n }\n\n case 'tuple': {\n const items = type.items.flatMap((t, idx) =>\n typeReachesDecimal(t, opts) ? emit(`(${slot} as unknown[])[${idx}]`, t, `${path}[${idx}]`, opts, scope, variant) : [],\n );\n return items;\n }\n\n case 'record': {\n if (!typeReachesDecimal(type.value, opts)) return [];\n const rec = scope.next('r');\n const k = scope.next('k');\n const inner = emit(`${rec}[${k}]`, type.value, `${path}{}`, opts, scope, variant);\n return [\n `{`,\n ` const ${rec} = ${slot} as Record<string, unknown>;`,\n ` for (const ${k} of Object.keys(${rec})) {`,\n ...inner.map(l => ` ${l}`),\n ` }`,\n `}`,\n ];\n }\n\n case 'inlineObject': {\n const relevant = type.fields.filter(f => typeReachesDecimal(f.type, opts));\n if (relevant.length === 0) return [];\n const obj = scope.next('o');\n const body = relevant.flatMap(f => fieldStatements(obj, f, path, opts, scope, variant, undefined));\n return [`{`, ` const ${obj} = ${slot} as Record<string, unknown>;`, ...body.map(l => ` ${l}`), `}`];\n }\n\n case 'intersection':\n return type.members.flatMap(m => emit(slot, m, path, opts, scope, variant));\n\n case 'union': {\n // `validateDecimal` rejects a decimal in a union with more than one non-null member, so\n // anything reaching here is `T | null`: hydrate the single real member behind a guard.\n const real = type.members.filter(m => !(m.kind === 'scalar' && m.name === 'null'));\n const target = real.find(m => typeReachesDecimal(m, opts));\n if (!target) return [];\n const inner = emit(slot, target, path, opts, scope, variant);\n return [`if (${slot} != null) {`, ...inner.map(l => ` ${l}`), `}`];\n }\n\n case 'discriminatedUnion': {\n const branches: string[] = [];\n const disc = scope.next('d');\n for (const member of type.members) {\n if (!typeReachesDecimal(member, opts)) continue;\n const tag = discriminatorTag(member, type.discriminator, opts);\n const inner = emit(slot, member, path, opts, scope, variant);\n if (inner.length === 0) continue;\n if (tag === undefined) {\n // No resolvable literal: hydrating unconditionally could apply the wrong arm's\n // shape, so skip it rather than risk corrupting a sibling member's field.\n continue;\n }\n branches.push(` if (${disc} === ${JSON.stringify(tag)}) {`, ...inner.map(l => ` ${l}`), ` }`);\n }\n if (branches.length === 0) return [];\n return [`{`, ` const ${disc} = (${slot} as Record<string, unknown>)[${JSON.stringify(type.discriminator)}];`, ...branches, `}`];\n }\n\n default:\n return [];\n }\n}\n\n/** The literal value that selects `member` in a discriminated union, when it can be resolved. */\nfunction discriminatorTag(member: ContractTypeNode, discriminator: string, opts: ReviveCodegenOptions): string | number | boolean | undefined {\n const fields: FieldNode[] | undefined =\n member.kind === 'inlineObject' ? member.fields : member.kind === 'ref' ? opts.modelMap?.get(member.name)?.fields : undefined;\n const field = fields?.find(f => f.name === discriminator);\n if (field?.type.kind === 'literal') return field.type.value;\n // A single-valued enum is the other way a discriminator gets written.\n if (field?.type.kind === 'enum' && field.type.values.length === 1) return field.type.values[0];\n return undefined;\n}\n\n/** Statements for one field of an object held in `objVar`. */\nfunction fieldStatements(\n objVar: string,\n field: FieldNode,\n path: string,\n opts: ReviveCodegenOptions,\n scope: Scope,\n variant: 'base' | 'output',\n outputCase: 'camel' | 'snake' | 'pascal' | undefined,\n): string[] {\n const key = variant === 'output' ? applyCase(field.name, outputCase) : field.name;\n const slot = `${objVar}[${JSON.stringify(key)}]`;\n const inner = emit(slot, field.type, `${path}.${key}`, opts, scope, variant);\n if (inner.length === 0) return [];\n // A union already emits its own null guard; adding a second would just nest.\n if (field.type.kind === 'union') return inner;\n if (field.optional || field.nullable) {\n return [`if (${slot} != null) {`, ...inner.map(l => ` ${l}`), `}`];\n }\n return inner;\n}\n\n/**\n * Pick the reviver for a referenced model.\n *\n * Mirrors `renderOutputTsType`: inside an output reviver, a referenced model uses its *own* output\n * reviver only if it has one. `computeModelsWithOutput` propagates referrer→referenced, so a child\n * of a transformed parent is not itself transformed and keeps camelCase keys.\n */\nfunction reviveRefName(name: string, opts: ReviveCodegenOptions, variant: 'base' | 'output'): string {\n if (variant === 'output' && opts.modelsWithOutput?.has(name)) return reviveFnName(name, 'output');\n return reviveFnName(name, 'base');\n}\n\n/**\n * A standalone reviver for an arbitrary type node — used for a response body that is not a plain\n * model reference (an inline object, a record, a tuple), where there is no `reviveX` to call.\n *\n * Returns `null` when the type holds no decimal, so the caller emits nothing at all.\n */\nexport function renderInlineReviver(\n fnName: string,\n tsType: string,\n type: ContractTypeNode,\n opts: ReviveCodegenOptions,\n variant: 'base' | 'output' = 'output',\n): string[] | null {\n if (!typeReachesDecimal(type, opts)) return null;\n const scope = new Scope();\n const body = emit('__v[0]', type, fnName.replace(/^__revive/, ''), opts, scope, variant);\n if (body.length === 0) return null;\n return [\n `/** Rehydrates the \\`decimal\\` fields of one response body. Mutates and returns \\`raw\\`. */`,\n `function ${fnName}(raw: ${tsType}): ${tsType} {`,\n ` const __v = [raw] as unknown[];`,\n ...body.map(l => ` ${l}`),\n ` return __v[0] as ${tsType};`,\n `}`,\n ];\n}\n\n/** The `reviveX` (and `reviveXOutput`) declarations for one model, or `[]` if it holds no decimal. */\nexport function renderReviveFunctions(model: ModelNode, opts: ReviveCodegenOptions): string[] {\n if (!opts.modelsWithDecimal.has(model.name)) return [];\n const lines = renderOne(model, opts, 'base');\n if (opts.modelsWithOutput?.has(model.name)) {\n lines.push('');\n lines.push(...renderOne(model, opts, 'output'));\n }\n return lines;\n}\n\nfunction renderOne(model: ModelNode, opts: ReviveCodegenOptions, variant: 'base' | 'output'): string[] {\n const scope = new Scope();\n const typeName = `${model.name}${variant === 'output' ? 'Output' : ''}`;\n const fnName = reviveFnName(model.name, variant);\n\n // A type-alias model has no fields — hydrate the aliased type as a whole.\n if (model.type) {\n const body = emit('__v[0]', model.type, model.name, opts, scope, variant);\n if (body.length === 0) return [];\n return [\n `/** Rehydrates every wire-encoded scalar in a ${typeName} into its runtime type. Mutates and returns \\`raw\\`. */`,\n `export function ${fnName}(raw: ${typeName}): ${typeName} {`,\n ` const __v = [raw] as unknown[];`,\n ...body.map(l => ` ${l}`),\n ` return __v[0] as ${typeName};`,\n `}`,\n ];\n }\n\n const obj = scope.next('o');\n const body = model.fields.flatMap(f =>\n typeReachesDecimal(f.type, opts) ? fieldStatements(obj, f, model.name, opts, scope, variant, model.outputCase) : [],\n );\n if (body.length === 0) return [];\n\n return [\n `/** Rehydrates every wire-encoded scalar in a ${typeName} into its runtime type. Mutates and returns \\`raw\\`. */`,\n `export function ${fnName}(raw: ${typeName}): ${typeName} {`,\n ` const ${obj} = raw as unknown as Record<string, unknown>;`,\n ...body.map(l => ` ${l}`),\n ` return raw;`,\n `}`,\n ];\n}\n","import type {\n OpRootNode,\n OpRouteNode,\n OpOperationNode,\n OpResponseNode,\n OpResponseHeaderNode,\n ContractTypeNode,\n ScalarTypeNode,\n ParamSource,\n ObjectMode,\n} from '@contractkit/core';\nimport { resolveModifiers, resolveSecurity, SECURITY_NONE, classifyContentType, emittedResponses, PATH_PARAM_RE_G, toIdentifier } from '@contractkit/core';\nimport {\n renderType,\n renderInputType,\n renderQueryType,\n applyFieldModifiers,\n pascalToDotCase,\n modeToWrapper,\n} from './codegen-contract.js';\nimport { renderOutputTsType, quoteKey, headerNameToProperty, escapeJsDocLines, escapeSingleQuoted, sourceLink } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_PRELUDE_LINES } from './decimal-runtime.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Content-type helpers ──────────────────────────────────────────────────\n\n/** Map a request MIME type to the koa-bodyparser parser token used in middleware. */\nfunction bodyParserToken(contentType: string): string {\n switch (classifyContentType(contentType)) {\n case 'urlencoded':\n return 'urlencoded';\n case 'multipart':\n return 'multipart';\n case 'text':\n return 'text';\n case 'binary':\n // koa-bodyparser has no native binary token; fall back to text so the body is\n // still readable as a string. Services handling binary uploads should switch to\n // multipart/form-data.\n return 'text';\n default:\n return 'json';\n }\n}\n\n/**\n * Deep structural equality on ContractTypeNode, ignoring source locations on inline fields.\n * Used to decide whether multiple declared request MIMEs can share a single validate path.\n */\nexport function bodyTypesStructurallyEqual(a: ContractTypeNode, b: ContractTypeNode): boolean {\n if (a.kind !== b.kind) return false;\n switch (a.kind) {\n case 'scalar': {\n const bb = b as typeof a;\n return (\n a.name === bb.name &&\n a.min === bb.min &&\n a.max === bb.max &&\n a.len === bb.len &&\n a.scale === bb.scale &&\n a.regex === bb.regex &&\n a.format === bb.format\n );\n }\n case 'array': {\n const bb = b as typeof a;\n return a.min === bb.min && a.max === bb.max && bodyTypesStructurallyEqual(a.item, bb.item);\n }\n case 'tuple': {\n const bb = b as typeof a;\n return a.items.length === bb.items.length && a.items.every((x, i) => bodyTypesStructurallyEqual(x, bb.items[i]!));\n }\n case 'record': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.key, bb.key) && bodyTypesStructurallyEqual(a.value, bb.value);\n }\n case 'enum': {\n const bb = b as typeof a;\n return a.values.length === bb.values.length && a.values.every((v, i) => v === bb.values[i]);\n }\n case 'literal': {\n const bb = b as typeof a;\n return a.value === bb.value;\n }\n case 'union':\n case 'intersection': {\n const bb = b as typeof a;\n return a.members.length === bb.members.length && a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!));\n }\n case 'discriminatedUnion': {\n const bb = b as typeof a;\n return (\n a.discriminator === bb.discriminator &&\n a.members.length === bb.members.length &&\n a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!))\n );\n }\n case 'ref': {\n const bb = b as typeof a;\n return a.name === bb.name && !!a.lazy === !!bb.lazy;\n }\n case 'lazy': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.inner, bb.inner);\n }\n case 'inlineObject': {\n const bb = b as typeof a;\n if (a.mode !== bb.mode) return false;\n if (a.fields.length !== bb.fields.length) return false;\n return a.fields.every((f, i) => {\n const g = bb.fields[i]!;\n return (\n f.name === g.name &&\n f.optional === g.optional &&\n f.nullable === g.nullable &&\n f.visibility === g.visibility &&\n f.default === g.default &&\n !!f.deprecated === !!g.deprecated &&\n bodyTypesStructurallyEqual(f.type, g.type)\n );\n });\n }\n }\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/** Options controlling how {@link generateOp} renders a Koa router module. */\nexport interface OpCodegenOptions {\n servicePathTemplate?: string;\n typeImportPathTemplate?: string;\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /**\n * Whether to emit handlers for operations marked `internal`. Defaults to `true` because\n * the server still needs routes for internal endpoints; set to `false` to omit them\n * from the generated router entirely.\n */\n includeInternal?: boolean;\n /**\n * Re-parse the service result through its declared response schema before writing `ctx.body`,\n * and write the parsed value. Requires the type file to hold Zod schemas (`server.zod`) —\n * plain interfaces are types, with no runtime schema value to validate against. Default false.\n */\n validateResponses?: boolean;\n /**\n * Set of model names whose schema applies a `format(...)` key transform, directly or through a\n * referenced model. Response bodies touching one are left unvalidated: the service returns the\n * post-transform shape, which the schema itself cannot re-parse.\n */\n modelsWithTransform?: Set<string>;\n}\n\n/**\n * Generate a Koa router module for every operation in `root`, including the imports, type\n * aliases, and handler list.\n *\n * Imports are derived from the generated body — each candidate symbol is emitted only if it\n * actually appears in the output. Deciding them from predicates over the AST instead means any\n * drift between predicate and codegen leaves an unused import in every generated file, which\n * trips `noUnusedLocals` and lint downstream.\n */\nexport function generateOp(root: OpRootNode, options: OpCodegenOptions = {}): string {\n // Collect all referenced types across all routes\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput);\n const services = collectServices(root);\n const routerName = deriveRouterName(root.file);\n\n const lines: string[] = [];\n\n lines.push('');\n lines.push('/**');\n lines.push(` * generated from ${sourceLink(basename(root.file), options.outPath, root.file)}`);\n lines.push('*/');\n lines.push(`export const ${routerName} = ServerKitRouter();`);\n lines.push('');\n\n const includeInternal = options.includeInternal ?? true;\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n lines.push(...generateHandler(route, op, root, options));\n lines.push('');\n }\n }\n\n // Helpers and imports are both decided from the code we just generated, not from predicates\n // over the AST that have to be kept in step with it by hand. A predicate that drifts leaves an\n // unused declaration in every generated file, which trips `noUnusedLocals` and lint in\n // consuming projects — `opNeedsScalar(root, 'binary')` over-approximates exactly that way,\n // since a binary *response* body is a plain `Buffer` annotation with no schema behind it.\n const handlerBody = lines.join('\\n');\n const references = (symbol: string) => new RegExp(`\\\\b${symbol}\\\\b`).test(handlerBody);\n\n const helpers: string[] = [];\n if (references('_ZodBinary')) {\n helpers.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (references('_ZodDatetime')) {\n helpers.push(\n `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' }));`,\n );\n }\n if (references('_ZodDecimal')) {\n helpers.push(...DECIMAL_PRELUDE_LINES);\n }\n if (references('_ZodInterval')) {\n helpers.push(\n `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()!);`,\n );\n }\n // `_ZodJson`'s own declaration is annotated with `_JsonValue`, so the type alias comes along\n // with it; the alias is also needed on its own for a `json` body's server-side annotation.\n const needsZodJson = references('_ZodJson');\n if (needsZodJson || references('_JsonValue')) {\n helpers.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n }\n if (needsZodJson) {\n helpers.push(\n `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)]));`,\n );\n }\n\n const generated = [...(helpers.length ? ['', ...helpers] : []), ...lines].join('\\n');\n const uses = (symbol: string) => new RegExp(`\\\\b${symbol}\\\\b`).test(generated);\n\n const body: string[] = [];\n\n const koaImports = ['ServerKitRouter', 'bodyParserMiddleware', 'requirePolicy', 'requireSignature'].filter(uses);\n if (koaImports.length > 0) {\n body.push(`import { ${koaImports.join(', ')} } from '@maroonedsoftware/koa';`);\n }\n\n // Services and model names come from the AST, which over-approximates two ways: a model with an\n // Input/Output variant contributes its base name even when only the variant is ever annotated,\n // and `collectServices`/`collectTypes` walk every operation including the `internal` ones\n // `includeInternal: false` drops. Filtering through `uses` — the same gate every symbol above\n // goes through — keeps the import list to what the handlers actually reference, so generated\n // code does not trip `noUnusedLocals` in the consuming project.\n for (const svc of services.filter(uses)) {\n const modulePath = root.services?.[svc] ?? root.meta[svc] ?? deriveModulePath(svc, options.servicePathTemplate);\n body.push(`import { ${svc} } from '${modulePath}';`);\n }\n\n const usedTypes = types.filter(uses);\n if (usedTypes.length > 0) {\n body.push(...generateTypeImports(usedTypes, root.file, options));\n }\n\n // luxon is needed for date/time/datetime (DateTime), duration (Duration) and interval (Interval);\n // the rendered Zod schemas and the service-result annotations both reference these classes.\n const luxonImports = ['DateTime', 'Duration', 'Interval'].filter(uses);\n if (luxonImports.length > 0) {\n body.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n }\n\n // Same `uses` gate: `Decimal` appears in the `_ZodDecimal` helper and in service-result\n // annotations via `serverTsScalar`, and the helper text is folded into `generated` above.\n if (uses('Decimal')) {\n body.push(DECIMAL_IMPORT);\n }\n\n if (uses('parseAndValidate')) {\n body.push(`import { parseAndValidate } from '@maroonedsoftware/zod';`);\n }\n\n if (uses('MultipartBody')) {\n body.push(`import { MultipartBody } from '@maroonedsoftware/multipart';`);\n }\n\n const allContent = [...body, ...(helpers.length ? ['', ...helpers] : []), ...lines].join('\\n');\n const needsZod = /\\bz\\./.test(allContent);\n return (needsZod ? `import { z } from 'zod';\\n` : '') + allContent;\n}\n\n// ─── Handler generation ────────────────────────────────────────────────────\n\nfunction generateHandler(route: OpRouteNode, op: OpOperationNode, root: OpRootNode, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const file = root.file;\n const outPath = options.outPath;\n const modelsWithInput = options.modelsWithInput;\n\n lines.push('/**');\n\n // JSDoc from description\n const desc = op.description ?? route.description;\n if (desc) {\n for (const l of escapeJsDocLines(desc)) lines.push(` * ${l}`);\n }\n // Source location comment\n lines.push(` * from ${sourceLink(basename(file), outPath, file, op.loc.line)}`);\n\n // Security annotation (operation-level wins; falls back to route → file level)\n const effectiveSecurity = resolveSecurity(route, op, root);\n if (effectiveSecurity === SECURITY_NONE) {\n lines.push(` * anonymous access, no security required`);\n }\n\n // Modifier annotations\n const mods = resolveModifiers(route, op);\n if (mods.includes('internal')) lines.push(` * @internal`);\n if (mods.includes('deprecated')) lines.push(` * @deprecated`);\n\n lines.push('*/');\n\n const method = op.method;\n // `:name` from `{name}`, mapped to a valid identifier. Unlike a query parameter or a header,\n // a path placeholder's name never reaches the wire — Koa matches by position — so renaming it\n // is free, and it is what lets `ctx.params` be destructured at all.\n const path = route.path.replace(PATH_PARAM_RE_G, (_m, name: string) => `:${toIdentifier(name)}`);\n const bodies = op.request?.bodies ?? [];\n const hasBody = bodies.length > 0;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n\n // Middleware list\n const middlewares: string[] = [];\n if (effectiveSecurity !== SECURITY_NONE) {\n const policy = effectiveSecurity?.policy;\n const args =\n policy === undefined\n ? ''\n : policy === false\n ? '{ policy: false }'\n : `{ policy: '${policy}' }`;\n middlewares.push(`requirePolicy(${args})`);\n }\n if (hasBody) {\n const parserTokens = Array.from(new Set(bodies.map(b => bodyParserToken(b.contentType))));\n const tokensExpr = parserTokens.map(t => `'${t}'`).join(', ');\n middlewares.push(`bodyParserMiddleware([${tokensExpr}])`);\n }\n if (op.signature) {\n const sigArgs = op.signaturePolicy\n ? `'${escapeSingleQuoted(op.signature)}', { policy: '${escapeSingleQuoted(op.signaturePolicy)}' }`\n : `'${escapeSingleQuoted(op.signature)}'`;\n middlewares.push(`requireSignature(${sigArgs})`);\n }\n const middlewareStr = middlewares.length > 0 ? `, ${middlewares.join(', ')},` : ',';\n\n lines.push(`${deriveRouterName(file)}.${method}('${path}'${middlewareStr} async ctx => {`);\n\n // Params / query / headers validation (request-side — use Input variants)\n lines.push(...generateParamValidation(route.params, 'ctx.params', 'params', route.paramsMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.query, 'ctx.query', 'query', op.queryMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.headers, 'ctx.headers', 'headers', op.headersMode ?? 'strip', '', modelsWithInput));\n\n // Body validation (request-side — use Input variants)\n if (hasBody && op.request) {\n if (isSingleMultipart) {\n lines.push(` const multipartBody = ctx.parsedBody as MultipartBody;`);\n lines.push('');\n } else if (bodies.length === 1) {\n lines.push(` const body = await parseAndValidate(ctx.parsedBody, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n // All declared MIMEs share the same body shape — single validation suffices\n lines.push(` const body = await parseAndValidate(ctx.parsedBody, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else {\n // Different body types per MIME — dispatch on Content-Type\n const annotation = bodies\n .map(b =>\n b.contentType === 'multipart/form-data' ? 'MultipartBody' : `z.infer<typeof ${renderInputType(b.bodyType, modelsWithInput)}>`,\n )\n .join(' | ');\n lines.push(` let body!: ${annotation};`);\n lines.push(` switch (ctx.request.type) {`);\n for (const b of bodies) {\n lines.push(` case '${b.contentType}':`);\n if (b.contentType === 'multipart/form-data') {\n lines.push(` body = ctx.parsedBody as MultipartBody;`);\n } else {\n lines.push(` body = await parseAndValidate(ctx.parsedBody, ${renderInputType(b.bodyType, modelsWithInput)});`);\n }\n lines.push(` break;`);\n }\n lines.push(` }`);\n lines.push('');\n }\n }\n\n // Service call. `emittedResponses` decides which of the declared statuses the service is\n // responsible for producing; the rest are documentation, or the thrown-error path.\n const emitted = emittedResponses(op);\n const serviceParts = inferService(op, route, file);\n const call = `await service.${serviceParts.methodName}(${buildArgs(route, op)})`;\n\n if (emitted.length > 1) {\n lines.push(...generateMultiStatusResult(emitted, serviceParts.className, call, options));\n } else {\n lines.push(...generateSingleStatusResult(emitted[0], op, serviceParts.className, call, options));\n }\n\n lines.push(`});`);\n\n return lines;\n}\n\n/**\n * The service produces exactly one status (or none): the result is the body itself, or\n * `{ body, headers }` when the status declares headers, and `ctx.status` is a constant.\n *\n * A status declaring several mimes also gains a `contentType` the service picks, which is the\n * only thing here that can turn `ctx.type` from a literal into an expression.\n */\nfunction generateSingleStatusResult(\n resp: OpResponseNode | undefined,\n op: OpOperationNode,\n className: string,\n call: string,\n options: OpCodegenOptions,\n): string[] {\n const lines: string[] = [];\n const bodies = resp ? resp.bodies : [];\n const respHeaders = resp?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersAnnotation = hasRespHeaders ? renderHeadersAnnotation(respHeaders, options.modelsWithOutput) : '';\n\n let bodySchema: string | undefined;\n\n if (bodies.length === 1) {\n const { annotation, prelude } = formatTypeAnnotation(bodies[0]!.bodyType, options.modelsWithOutput);\n if (prelude) lines.push(` ${prelude}`);\n bodySchema = responseBodySchema(bodies[0]!.bodyType, options, prelude ? 'resultType' : undefined);\n lines.push(` const service = ctx.container.get(${className});`);\n if (hasRespHeaders) {\n lines.push(` const result: { body: ${annotation}; headers: ${headersAnnotation} } = ${call};`);\n } else {\n lines.push(` const result: ${annotation} = ${call};`);\n }\n } else if (bodies.length > 1) {\n const rendered = renderResponseMembers(resp!, options, { includeStatus: false, varPrefix: 'result' });\n const { members, preludes } = rendered;\n bodySchema = rendered.bodySchema;\n for (const prelude of preludes) lines.push(` ${prelude}`);\n lines.push(` const service = ctx.container.get(${className});`);\n lines.push(` const result: ${members.join(' | ')} = ${call};`);\n } else {\n lines.push(` const service = ctx.container.get(${className});`);\n if (hasRespHeaders) {\n lines.push(` const result: { headers: ${headersAnnotation} } = ${call};`);\n } else {\n lines.push(` ${call};`);\n }\n }\n\n lines.push('');\n // 204 when the operation emits nothing. Falling back to the first *declared* status wrote an\n // error code on the success path, since a documentation-only block starts at a 4xx. 204 is\n // also what aligns the three generators: `observableResponses` excludes a bare `400:` too, so\n // the SDK already types such a method `Promise<void>` and `thrownResponses` puts the 400 in\n // `@throws`. A bodyless 204 success is exactly what `Promise<void>` means.\n lines.push(` ctx.status = ${resp?.statusCode ?? 204};`);\n lines.push(...headerSetLines(respHeaders, ' '));\n\n if (bodies.length === 1) {\n lines.push(` ctx.type = '${bodies[0]!.contentType}';`);\n lines.push(` ctx.body = ${responseBodyExpr(hasRespHeaders ? 'result.body' : 'result', bodySchema)};`);\n } else if (bodies.length > 1) {\n lines.push(` ctx.type = result.contentType;`);\n lines.push(` ctx.body = ${responseBodyExpr('result.body', bodySchema)};`);\n }\n\n return lines;\n}\n\n/**\n * The service chooses between several statuses: the result is a union discriminated on\n * `status`, and the handler switches on it so each status writes only its own headers, mime\n * and body.\n */\nfunction generateMultiStatusResult(emitted: OpResponseNode[], className: string, call: string, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const members: string[] = [];\n const preludes: string[] = [];\n\n const bodySchemas = new Map<number, string | undefined>();\n\n for (const resp of emitted) {\n const rendered = renderResponseMembers(resp, options, { includeStatus: true, varPrefix: `result${resp.statusCode}` });\n members.push(...rendered.members);\n preludes.push(...rendered.preludes);\n bodySchemas.set(resp.statusCode, rendered.bodySchema);\n }\n\n for (const prelude of preludes) lines.push(` ${prelude}`);\n lines.push(` const service = ctx.container.get(${className});`);\n lines.push(` const result:`);\n for (const member of members) lines.push(` | ${member}`);\n lines.push(` = ${call};`);\n lines.push('');\n lines.push(` ctx.status = result.status;`);\n lines.push(` switch (result.status) {`);\n for (const resp of emitted) {\n lines.push(` case ${resp.statusCode}:`);\n lines.push(...headerSetLines(resp.headers ?? [], ' '));\n if (resp.bodies.length > 0) {\n lines.push(` ctx.type = result.contentType;`);\n lines.push(` ctx.body = ${responseBodyExpr('result.body', bodySchemas.get(resp.statusCode))};`);\n }\n lines.push(` break;`);\n }\n lines.push(` }`);\n\n return lines;\n}\n\n/**\n * Render one status as the members of the service-result union — its `contentType`, `body` and\n * `headers`, plus `status` when the operation emits more than one.\n *\n * A status declaring several mimes collapses to a single member with a union of mime literals\n * when the bodies are structurally identical (`image/png` and `image/jpeg` both `binary`).\n * When they differ, it produces one member per mime so `contentType` and `body` stay correlated.\n */\nfunction renderResponseMembers(\n resp: OpResponseNode,\n options: OpCodegenOptions,\n opts: { includeStatus: boolean; varPrefix: string },\n): { members: string[]; preludes: string[]; bodySchema?: string } {\n const bodies = resp.bodies;\n const headers = resp.headers ?? [];\n const leading = opts.includeStatus ? [`status: ${resp.statusCode}`] : [];\n const trailing = headers.length > 0 ? [`headers: ${renderHeadersAnnotation(headers, options.modelsWithOutput)}`] : [];\n const preludes: string[] = [];\n\n if (bodies.length === 0) {\n return { members: [`{ ${[...leading, ...trailing].join('; ')} }`], preludes };\n }\n\n const uniform = bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType));\n if (uniform) {\n const { annotation, prelude } = formatTypeAnnotation(bodies[0]!.bodyType, options.modelsWithOutput, `${opts.varPrefix}Type`);\n if (prelude) preludes.push(prelude);\n const bodySchema = responseBodySchema(bodies[0]!.bodyType, options, prelude ? `${opts.varPrefix}Type` : undefined);\n const contentType = bodies.map(b => `'${b.contentType}'`).join(' | ');\n return {\n members: [`{ ${[...leading, `contentType: ${contentType}`, `body: ${annotation}`, ...trailing].join('; ')} }`],\n preludes,\n bodySchema,\n };\n }\n\n // One member per mime: `contentType` and `body` stay correlated, so validating would need a\n // second switch on `result.contentType` nested inside the status switch. Left unvalidated —\n // note the absent `bodySchema` in the return below.\n const members = bodies.map((b, i) => {\n const { annotation, prelude } = formatTypeAnnotation(b.bodyType, options.modelsWithOutput, `${opts.varPrefix}Type${i}`);\n if (prelude) preludes.push(prelude);\n return `{ ${[...leading, `contentType: '${b.contentType}'`, `body: ${annotation}`, ...trailing].join('; ')} }`;\n });\n return { members, preludes };\n}\n\nfunction renderHeadersAnnotation(headers: OpResponseHeaderNode[], modelsWithOutput?: Set<string>): string {\n const fields = headers.map(\n h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput, 'server')}`,\n );\n return `{ ${fields.join('; ')} }`;\n}\n\n/** `ctx.set(...)` calls for a status's declared response headers, guarding the optional ones. */\nfunction headerSetLines(headers: OpResponseHeaderNode[], indent: string): string[] {\n return headers.map(h => {\n const accessor = `result.headers[${JSON.stringify(headerNameToProperty(h.name))}]`;\n return h.optional\n ? `${indent}if (${accessor} !== undefined) ctx.set('${h.name}', String(${accessor}));`\n : `${indent}ctx.set('${h.name}', String(${accessor}));`;\n });\n}\n\n// ─── Inference helpers ─────────────────────────────────────────────────────\n\n/**\n * Resolve the service class and method a handler should delegate to.\n *\n * Uses the operation's explicit `service: Class.method` declaration when present; otherwise derives\n * the class from the contract file name (`ledger.categories.ck` → `LedgerCategoriesService`) and the\n * method from the HTTP verb and whether the path carries a parameter (`get` → `list` / `getById`).\n *\n * @param file Path of the `.ck` file the operation came from.\n */\nexport function inferService(op: OpOperationNode, route: OpRouteNode, file: string): { className: string; methodName: string } {\n // If explicitly declared: service: ServiceClass.methodName\n if (op.service) {\n const [cls = '', method] = op.service.split('.');\n return { className: cls, methodName: method ?? 'handle' };\n }\n\n // Infer from file name + method + path\n const baseName = deriveBaseName(file); // e.g. \"ledger.categories\" -> \"LedgerCategories\"\n const className = `${baseName}Service`;\n const methodName = inferMethodName(op.method, route.path);\n return { className, methodName };\n}\n\nfunction inferMethodName(method: string, path: string): string {\n const hasParam = path.includes('{');\n switch (method) {\n case 'get':\n return hasParam ? 'getById' : 'list';\n case 'post':\n return 'create';\n case 'put':\n return 'replace';\n case 'patch':\n return 'update';\n case 'delete':\n return 'delete';\n default:\n return 'handle';\n }\n}\n\n/**\n * Build the comma-separated argument list passed to the service method in a generated handler.\n *\n * Order is params, body, query, headers. Inline path params are spread as individual identifiers;\n * a referenced/compound params type is passed as a single `params` object. A lone\n * `multipart/form-data` request body is passed as `multipartBody` rather than `body`.\n *\n * @returns The rendered argument list, or an empty string when the method takes no arguments.\n */\nexport function buildArgs(route: OpRouteNode, op: OpOperationNode): string {\n const args: string[] = [];\n // Path params: spread individually (inline) or pass 'params' object (type-ref/ContractTypeNode)\n if (route.params) {\n if (route.params.kind === 'params') {\n args.push(...route.params.nodes.map(p => toIdentifier(p.name)));\n } else {\n args.push('params');\n }\n }\n // Body\n if (op.request && op.request.bodies.length > 0) {\n const bodies = op.request.bodies;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n args.push(isSingleMultipart ? 'multipartBody' : 'body');\n }\n // Query\n if (op.query) args.push('query');\n // Headers\n if (op.headers) args.push('headers');\n return args.join(', ');\n}\n\n/**\n * Map a `.ck` scalar to the TypeScript type a server handler sees, i.e. `z.infer` of the schema\n * `renderType` emits for that scalar. This is deliberately NOT `renderTsScalar` from ts-render:\n * that one describes the wire/SDK view (`binary` → `Blob`, dates → `string`), while the router\n * runs on Node against the parsed Zod output (`binary` → `Buffer`, dates → luxon `DateTime`).\n */\nfunction serverTsScalar(name: ScalarTypeNode['name']): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n return 'string';\n case 'number':\n case 'int':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'decimal':\n // Unlike the date scalars, this matches `renderTsScalar`'s wire view — `_ZodDecimal`\n // has no output transform, so `z.infer` is a `Decimal` on both sides.\n return 'Decimal';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'time':\n case 'datetime':\n return 'DateTime';\n case 'duration':\n return 'Duration';\n case 'interval':\n // _ZodInterval transforms to an ISO string, so the inferred output type is string.\n return 'string';\n case 'binary':\n return 'Buffer';\n case 'json':\n return '_JsonValue';\n case 'object':\n return 'Record<string, unknown>';\n case 'null':\n return 'null';\n case 'unknown':\n return 'unknown';\n default: {\n const _exhaustive: never = name;\n throw new Error(`plugin-typescript: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\n/**\n * @param varName Name for the extracted schema variable. Distinct per status and per mime when\n * an operation emits several, so two complex bodies in one handler cannot collide.\n */\nfunction formatTypeAnnotation(bodyType: ContractTypeNode, modelsWithOutput?: Set<string>, varName = 'resultType'): { annotation: string; prelude?: string } {\n if (bodyType.kind === 'array') {\n const inner = formatTypeAnnotation(bodyType.item, modelsWithOutput, varName);\n return { annotation: `${inner.annotation}[]`, prelude: inner.prelude };\n }\n if (bodyType.kind === 'ref') {\n const name = modelsWithOutput?.has(bodyType.name) ? `${bodyType.name}Output` : bodyType.name;\n return { annotation: name };\n }\n if (bodyType.kind === 'scalar') return { annotation: serverTsScalar(bodyType.name) };\n // For complex types, extract schema into a variable so the result line stays readable\n const schema = renderType(bodyType);\n return {\n annotation: `z.infer<typeof ${varName}>`,\n prelude: `const ${varName} = ${schema};`,\n };\n}\n\n/**\n * Whether a response body can be soundly re-parsed through the schema `renderType` emits for it.\n *\n * False for anything transitively touching a model with a `format(...)` key transform — the service\n * returns the post-transform value while the schema expects the pre-transform one — and for an\n * intersection outside `renderIntersection`'s `.extend()` fast path, where `.and()` of two strict\n * objects rejects every value because each side sees the other's keys as unrecognized.\n */\nfunction isRevalidatable(type: ContractTypeNode, modelsWithOutput?: Set<string>, modelsWithTransform?: Set<string>): boolean {\n const rec = (t: ContractTypeNode): boolean => isRevalidatable(t, modelsWithOutput, modelsWithTransform);\n switch (type.kind) {\n case 'ref':\n return !modelsWithOutput?.has(type.name) && !modelsWithTransform?.has(type.name);\n case 'array':\n return rec(type.item);\n case 'tuple':\n return type.items.every(rec);\n case 'record':\n return rec(type.key) && rec(type.value);\n case 'intersection': {\n // Mirrors renderIntersection: a lone member renders as itself, `ref & (ref|object)*`\n // renders as an `.extend()` chain, and anything else falls back to `.and()`.\n const [first, ...rest] = type.members;\n if (!first) return true;\n if (rest.length === 0) return rec(first);\n const usesExtendChain = first.kind === 'ref' && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject');\n return usesExtendChain && type.members.every(rec);\n }\n case 'union':\n case 'discriminatedUnion':\n return type.members.every(rec);\n case 'inlineObject':\n return type.fields.every(f => rec(f.type));\n case 'lazy':\n return rec(type.inner);\n default:\n // scalar, enum, literal — identity or idempotent under re-parse\n return true;\n }\n}\n\n/**\n * The runtime schema a handler validates a response body against, or `undefined` when the body\n * cannot be soundly re-parsed and validation must be skipped.\n *\n * @param preludeVar The schema const {@link formatTypeAnnotation} already emitted for this body\n * (complex types only — `undefined` when it returned no prelude). Reusing it keeps a large object\n * literal from appearing twice in the same handler.\n */\nfunction responseBodySchema(bodyType: ContractTypeNode, options: OpCodegenOptions, preludeVar: string | undefined): string | undefined {\n if (!options.validateResponses) return undefined;\n if (!isRevalidatable(bodyType, options.modelsWithOutput, options.modelsWithTransform)) return undefined;\n return preludeVar ?? renderType(bodyType);\n}\n\n/**\n * The `ctx.body = ...` right-hand side for a response body: the raw result expression, or a\n * `parseAndValidate` of it. The `500` is deliberate — a service returning a shape its own contract\n * rejects is a server fault, not a client one, and `@maroonedsoftware/zod` routes the field-level\n * detail to `internalDetails` (log-only) rather than the response body at 5xx.\n */\nfunction responseBodyExpr(value: string, schema: string | undefined): string {\n return schema ? `await parseAndValidate(${value}, ${schema}, 500)` : value;\n}\n\nfunction generateParamValidation(\n source: ParamSource | undefined,\n ctxExpr: string,\n varName: string,\n mode: ObjectMode,\n suffix = '',\n modelsWithInput?: Set<string>,\n): string[] {\n if (!source) return [];\n const lines: string[] = [];\n const isQuery = ctxExpr === 'ctx.query';\n if (source.kind === 'ref') {\n // Type reference — apply mode as a method call on the schema\n const typeName = modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;\n lines.push(` const ${varName} = await parseAndValidate(${ctxExpr}, ${typeName}.${mode}());`);\n lines.push('');\n } else if (source.kind === 'params') {\n // Inline param declarations — wrap with the appropriate z.*Object constructor\n if (source.nodes.length > 0) {\n // Destructure only for params (spread individually in service call);\n // query/headers are passed as whole objects.\n // Path params are destructured and spread into the service call; query and headers pass\n // as whole objects.\n const isPathParams = ctxExpr === 'ctx.params';\n const bind = (name: string) => (isPathParams ? toIdentifier(name) : name);\n const lhs = varName === 'params' ? `{ ${source.nodes.map(p => bind(p.name)).join(', ')} }` : varName;\n lines.push(` const ${lhs} = await parseAndValidate(`);\n lines.push(` ${ctxExpr},`);\n lines.push(` ${modeToWrapper(mode)}({`);\n for (const param of source.nodes) {\n // For path params the key must match the name in the route pattern above, which\n // is what `ctx.params` is keyed by. For query and headers it is the wire name,\n // quoted when that is not an identifier — those the client actually sends.\n const bound = bind(param.name);\n const key = isValidIdentifier(bound) ? bound : `'${bound}'`;\n // Delegating to renderQueryType rather than hand-rolling the array preprocess here:\n // it is the same rule, and a second copy is a second thing to keep in sync. The\n // modifier chain then comes from the shared helper, so an inline param means the\n // same thing to the router as a model field does.\n const base = isQuery ? renderQueryType(param.type, modelsWithInput) : renderInputType(param.type, modelsWithInput);\n lines.push(` ${key}: ${applyFieldModifiers(base, param)},`);\n }\n lines.push(` })${suffix},`);\n lines.push(` );`);\n lines.push('');\n }\n } else {\n // ContractTypeNode — use query-aware rendering for query params (coerces single string → array),\n // otherwise use Input variant rendering; apply mode as a method call\n const schema = isQuery ? renderQueryType(source.node, modelsWithInput) : renderInputType(source.node, modelsWithInput);\n lines.push(` const ${varName} = await parseAndValidate(${ctxExpr}, (${schema}).${mode}());`);\n lines.push('');\n }\n return lines;\n}\n\n// ─── Type import resolution ────────────────────────────────────────────────\n\n/**\n * Generate per-file type import statements.\n * When modelOutPaths is available, groups types by their actual output file\n * and computes correct relative paths. Falls back to the template-based\n * single-import approach for types not found in the map.\n */\nfunction generateTypeImports(types: string[], opFile: string, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n // Group types by their output file\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n // Emit one import per source file with a relative path\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import { ${names.sort().join(', ')} } from '${rel}';`);\n }\n\n // Fallback for types not in the map\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import { ${type} } from './${moduleName}.js';`);\n }\n } else {\n // No resolution context — fall back to template-based single import\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\n// ─── Collection helpers ────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of route.operations) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n for (const body of resp.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectOutputTypeNodeRefs(body.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'tuple':\n type.items.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'record':\n collectOutputTypeNodeRefs(type.key, out, modelsWithOutput);\n collectOutputTypeNodeRefs(type.value, out, modelsWithOutput);\n break;\n case 'union':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'intersection':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'type') {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeNodeRefs(type.key, out, modelsWithInput);\n collectInputTypeNodeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\nfunction collectServices(root: OpRootNode): string[] {\n const services = new Set<string>();\n const inferredService = `${deriveBaseName(root.file)}Service`;\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (op.service) {\n services.add(op.service.split('.')[0] ?? op.service);\n } else {\n services.add(inferredService);\n }\n }\n }\n return [...services].sort();\n}\n\n\n\n\n\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\n/**\n * Derive the PascalCase base name used for router, service, and type names from a contract file path.\n *\n * Strips directories and the `.op`/`.ck` extension, then PascalCases each dot-separated segment\n * (`contracts/ledger.categories.ck` → `LedgerCategories`). Falls back to `Resource` for an empty path.\n */\nexport function deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n // ledger.categories -> LedgerCategories\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction deriveRouterName(file: string): string {\n return `${deriveBaseName(file)}Router`;\n}\n\n/**\n * Resolve the import specifier for a service class.\n *\n * Drops the trailing `Service` suffix and kebab-cases the remainder, then applies `template` if given\n * (`{name}` → `Ledger`, `{kebab}` → `ledger`). Without a template, defaults to\n * `#modules/<kebab>/<kebab>.service.js`.\n *\n * @param template Optional `servicePathTemplate` from the plugin config.\n */\nexport function deriveModulePath(serviceName: string, template?: string): string {\n // LedgerService -> #modules/ledger/ledger.service.js\n const base = serviceName.replace(/Service$/, '');\n const kebab = base.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`).replace(/^-/, '');\n if (template) {\n return template.replace(/\\{name\\}/g, base).replace(/\\{kebab\\}/g, kebab);\n }\n return `#modules/${kebab}/${kebab}.service.js`;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n","import type {\n OpRootNode,\n OpRouteNode,\n OpOperationNode,\n OpRequestBodyNode,\n OpResponseNode,\n OpResponseBodyNode,\n OpResponseHeaderNode,\n ContractTypeNode,\n ModelNode,\n OpParamNode,\n ParamSource,\n ScalarTypeNode,\n} from '@contractkit/core';\nimport { resolveModifiers, isJsonMime, classifyContentType, observableResponses, thrownResponses, PATH_PARAM_RE_G, toIdentifier } from '@contractkit/core';\nimport {\n renderInputTsType,\n renderOutputTsType,\n quoteKey,\n headerNameToProperty,\n escapeJsDocLines,\n sourceLink,\n JSON_VALUE_TYPE_DECL,\n} from './ts-render.js';\nimport { pascalToDotCase, typeNeedsScalar } from './codegen-contract.js';\nimport { bodyTypesStructurallyEqual } from './codegen-operation.js';\nimport { reviveFnName, renderInlineReviver, typeReachesDecimal, coerceDeclsFor, coerceLuxonImports } from './codegen-revive.js';\nimport { DECIMAL_IMPORT, DECIMAL_CONFIG_LINE } from './decimal-runtime.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Body strategy ────────────────────────────────────────────────────────\n\ntype BodyStrategy =\n | { kind: 'none' }\n | { kind: 'single'; body: OpRequestBodyNode }\n | { kind: 'multi-equal'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-formdata-detect'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-required-arg'; bodies: OpRequestBodyNode[] };\n\n/** Serialize expression for a single MIME, given the source body var (e.g. 'body'). */\nfunction jsonOrFormSerialize(varName: string, contentType: string): string {\n if (contentType === 'application/x-www-form-urlencoded') {\n return `new URLSearchParams(${varName} as unknown as Record<string, string>).toString()`;\n }\n if (contentType === 'multipart/form-data') {\n return `(${varName} as FormData)`;\n }\n // application/json + any `+json` structured suffix — JSON.stringify with bigint support.\n return `JSON.stringify(${varName}, bigIntReplacer)`;\n}\n\n/**\n * Build a runtime expression that picks the right serialization based on a contentType variable.\n * Used by the SDK when the caller passes (or defaults to) a content-type at call time.\n */\nfunction renderSerializeExpr(varName: string, bodies: OpRequestBodyNode[], ctVar: string): string {\n // Build a chained ternary, last MIME is the fallback\n const arms = bodies.slice(0, -1);\n const last = bodies[bodies.length - 1]!;\n let expr = jsonOrFormSerialize(varName, last.contentType);\n for (let i = arms.length - 1; i >= 0; i--) {\n const arm = arms[i]!;\n expr = `${ctVar} === '${arm.contentType}' ? ${jsonOrFormSerialize(varName, arm.contentType)} : ${expr}`;\n }\n return expr;\n}\n\nfunction classifyBodyStrategy(op: OpOperationNode): BodyStrategy {\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 0) return { kind: 'none' };\n if (bodies.length === 1) return { kind: 'single', body: bodies[0]! };\n if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n return { kind: 'multi-equal', bodies };\n }\n if (bodies.some(b => b.contentType === 'multipart/form-data')) {\n return { kind: 'multi-formdata-detect', bodies };\n }\n return { kind: 'multi-required-arg', bodies };\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/** Options shared by every SDK code-generation entry point. */\nexport interface SdkCodegenOptions {\n /** Template for type import paths when `modelOutPaths` is not provided. Supports `{module}` and `{base}`. */\n typeImportPathTemplate?: string;\n /** Absolute path of the file currently being generated. Used to compute relative imports. */\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Absolute path to the shared sdk-options.ts file (if set, imports SdkOptions instead of defining inline) */\n sdkOptionsPath?: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /** Model names carrying a `decimal`, whose response bodies need rehydrating client-side. */\n modelsWithDecimal?: Set<string>;\n /** Model names carrying a `bigint`, directly or transitively. Selects the JSON reviver. */\n modelsWithBigInt?: Set<string>;\n /** Every model in scope, for resolving discriminated-union members inside an inline reviver. */\n modelMap?: Map<string, ModelNode>;\n /**\n * Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —\n * internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`\n * to include them (e.g. for an internal-use SDK).\n */\n includeInternal?: boolean;\n /**\n * Override the generated client class name. When omitted, falls back to\n * `deriveClientClassName(root.file)` (the legacy per-file name). The aggregator\n * uses this to emit `<Area><Subarea>Client` for area+subarea leaf files.\n */\n clientClassName?: string;\n}\n\n/**\n * Returns true if the root contains at least one operation eligible for SDK emission.\n * With `includeInternal: false` (default) that means at least one non-internal op; with\n * `includeInternal: true` any op qualifies.\n */\nexport function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;\n }\n }\n return false;\n}\n\n/**\n * Generate a complete `*.client.ts` file for one operation root: imports, the client class\n * declaration, and one method per public operation. Used for top-level (no-area) files and\n * for subarea-leaf files. Area-level files are NOT routed through this — their methods get\n * inlined into the SDK aggregator via {@link generateClientMethods} + {@link generateSdkAggregator}.\n */\nexport function generateSdk(root: OpRootNode, options: SdkCodegenOptions = {}): string {\n const lines: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput, includeInternal);\n const clientClassName = options.clientClassName ?? deriveClientClassName(root.file);\n\n // The method bodies are generated first so the imports can be read off them, the same way\n // codegen-operation decides its imports from the code it just emitted. A reviver import that\n // came from a predicate instead could drift and leave an unused local behind.\n const inlineRevivers = new Map<string, string[]>();\n const classBody: string[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n classBody.push('');\n classBody.push(...generateMethod(route, op, root.file, options, inlineRevivers));\n }\n }\n\n const inlineReviverDecls = [...inlineRevivers.values()].flat();\n const decimalPrelude = decimalPreludeFor(inlineReviverDecls);\n // Computed here rather than at its splice point below, so the import filter can see the\n // aliases: an error-body alias is a genuine reference to a model type.\n const errorAliases = generateErrorBodyAliases(root, options);\n\n // Type-only imports, plus the model revivers the methods actually call.\n //\n // `collectTypes` walks the AST and so reports every model a request body names, including one\n // carried by a `multipart/form-data` body — which `buildMethodParams` types as `FormData`, so\n // the model is never mentioned in the emitted code and its import is unused. Rather than\n // special-casing multipart in `collectTypes`, which validating multipart bodies would later\n // have to undo, keep only the types the emitted text actually names. This is the same\n // text-derived idiom the reviver imports already use just below.\n const referenced = referencedTypes(types, [...classBody, ...errorAliases, ...inlineReviverDecls]);\n if (referenced.length > 0) {\n lines.push(...generateTypeImports(referenced, root.file, options, usedRevivers(classBody)));\n }\n lines.push(...decimalPrelude.imports);\n const headerLuxon = headerLuxonImport(classBody, decimalPrelude.imports);\n if (headerLuxon) lines.push(headerLuxon);\n\n // SdkOptions import (from shared file) or inline fallback\n if (options.sdkOptionsPath && options.outPath) {\n let rel = relative(dirname(options.outPath), options.sdkOptionsPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const jsonImport = sdkNeedsJson(root, includeInternal) ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${rel}';`);\n const valueImports: string[] = [];\n if (sdkNeedsBigIntReplacer(root, includeInternal)) valueImports.push('bigIntReplacer');\n // Aliased rather than emitted at each call site: the method bodies are identical either\n // way, and the import line is where the choice is legible.\n if (sdkParsesJsonResponse(root, includeInternal)) {\n valueImports.push(sdkResponsesUseBigInt(root, options, includeInternal) ? 'parseJsonWithBigInt as parseJson' : 'parseJson');\n }\n if (sdkNeedsQueryString(root, includeInternal)) valueImports.push('buildQueryString');\n if (sdkNeedsReadContentType(root, includeInternal)) valueImports.push('readContentType');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${rel}';`);\n }\n } else {\n lines.push('');\n lines.push('export class SdkError<TBody = unknown> extends Error {');\n lines.push(' constructor(');\n lines.push(' public readonly status: number,');\n lines.push(' public readonly statusText: string,');\n lines.push(' public readonly body: TBody,');\n lines.push(' public readonly headers: Headers,');\n lines.push(' ) {');\n lines.push(' super(`${status} ${statusText}`);');\n lines.push(\" this.name = 'SdkError';\");\n lines.push(' }');\n lines.push('}');\n lines.push('');\n lines.push('export interface SdkRequestInit extends RequestInit {');\n lines.push(' /**');\n lines.push(' * Statuses this operation declares as values rather than errors — a 304 from');\n lines.push(' * conditional-GET middleware, or an error status the service returns deliberately.');\n lines.push(' * Anything else at or above 400 still throws SdkError.');\n lines.push(' */');\n lines.push(' expectStatuses?: number[];');\n lines.push('}');\n lines.push('');\n lines.push('export type SdkFetch = (url: string, init: SdkRequestInit) => Promise<Response>;');\n lines.push('');\n lines.push('export interface SdkOptions {');\n lines.push(' baseUrl: string;');\n lines.push(' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);');\n lines.push(' fetch?: SdkFetch;');\n lines.push(' /** Called once per request to produce a unique X-Request-ID header value */');\n lines.push(' requestIdFactory?: () => string;');\n lines.push('}');\n lines.push('');\n lines.push('export function readContentType(res: Response): string {');\n lines.push(\" return res.headers.get('content-type')?.split(';')[0]?.trim() ?? '';\");\n lines.push('}');\n lines.push('');\n lines.push('export function createSdkFetch(options: SdkOptions): SdkFetch {');\n lines.push(' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());');\n lines.push(' return async (url: string, init: SdkRequestInit): Promise<Response> => {');\n lines.push(\" const baseHeaders = typeof options.headers === 'function'\");\n lines.push(' ? await options.headers()');\n lines.push(' : options.headers ?? {};');\n lines.push(' const res = await fetch(`${options.baseUrl}${url}`, {');\n lines.push(' ...init,');\n lines.push(\" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\");\n lines.push(' });');\n lines.push(' if (!res.ok && !(init.expectStatuses ?? []).includes(res.status)) {');\n lines.push(' const text = await res.text();');\n lines.push(' let body: unknown;');\n lines.push(' try { body = JSON.parse(text); } catch { body = text; }');\n lines.push(' throw new SdkError(res.status, res.statusText, body, res.headers);');\n lines.push(' }');\n lines.push(' return res;');\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push('export function buildQueryString(query: object | undefined): string {');\n lines.push(' const searchParams = new URLSearchParams();');\n lines.push(' if (query) {');\n lines.push(' for (const [k, v] of Object.entries(query)) {');\n lines.push(' if (v === undefined || v === null) continue;');\n lines.push(' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }');\n lines.push(' else searchParams.set(k, String(v));');\n lines.push(' }');\n lines.push(' }');\n lines.push(' const qs = searchParams.toString();');\n lines.push(\" return qs ? `?${qs}` : '';\");\n lines.push('}');\n lines.push('');\n lines.push('export async function parseJson<T>(res: Response): Promise<T> {');\n lines.push(\n sdkResponsesUseBigInt(root, options, includeInternal)\n ? ' return JSON.parse(await res.text(), bigIntReviver) as T;'\n : ' return JSON.parse(await res.text()) as T;',\n );\n lines.push('}');\n }\n\n if (sdkNeedsJson(root, includeInternal) && !(options.sdkOptionsPath && options.outPath)) {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n\n lines.push('');\n\n if (errorAliases.length > 0) {\n lines.push(...errorAliases);\n lines.push('');\n }\n\n if (decimalPrelude.decls.length > 0) {\n lines.push('');\n lines.push(...decimalPrelude.decls);\n }\n\n // Wrappers for bodies with no `reviveX` of their own — an inline object, a record, a tuple.\n for (const decl of inlineRevivers.values()) {\n lines.push('');\n lines.push(...decl);\n }\n\n // Client class\n lines.push('/**');\n lines.push(` * generated from ${sourceLink(basename(root.file), options.outPath, root.file)}`);\n lines.push(' */');\n lines.push(`export class ${clientClassName} {`);\n lines.push(' constructor(private fetch: SdkFetch) {}');\n lines.push(...classBody);\n\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Render the method-block lines for an operation file as if they were declared inside a\n * client class.\n *\n * Skips operations marked `internal` unless `options.includeInternal` is set.\n *\n * @returns `lines`, one consolidated array pre-indented for class-body level with leading blank\n * lines between methods; `methodNames`, used by the caller to detect cross-file collisions when\n * several files contribute to the same area-level client; `preludeLines`, module-level\n * declarations the methods reference (decimal revivers and their `__dec` helper) which the caller\n * must splice in above the class; and `needsDecimalImport`, true when those declarations require\n * `import { Decimal } from 'decimal.js'` in the emitting file.\n */\nexport function generateClientMethods(\n root: OpRootNode,\n options: SdkCodegenOptions,\n): { lines: string[]; methodNames: string[]; preludeLines: string[]; needsDecimalImport: boolean } {\n const lines: string[] = [];\n const methodNames: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n const inlineRevivers = new Map<string, string[]>();\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n lines.push('');\n lines.push(...generateMethod(route, op, root.file, options, inlineRevivers));\n methodNames.push(deriveMethodName(op, route));\n }\n }\n // Module-level declarations the methods reference, spliced above the class by the caller —\n // the same shape `generateErrorBodyAliases` already uses.\n const declLines = [...inlineRevivers.values()].flat();\n const { decls } = decimalPreludeFor(declLines);\n const preludeLines = [...(decls.length > 0 ? ['', ...decls] : []), ...[...inlineRevivers.values()].flatMap(decl => ['', ...decl])];\n return { lines, methodNames, preludeLines, needsDecimalImport: decls.length > 0 };\n}\n\n/**\n * Declarations a client file needs for the inline revivers it carries.\n *\n * An inline wrapper calls `__dec`, which is file-local to the *types* module and not exported, so\n * a client file that has one needs its own copy — along with the decimal.js import and the global\n * config, since nothing else in the file necessarily pulls them in.\n */\nfunction decimalPreludeFor(declLines: string[]): { imports: string[]; decls: string[] } {\n const decls = coerceDeclsFor(declLines);\n if (decls.length === 0) return { imports: [], decls: [] };\n\n const imports: string[] = [];\n const preamble: string[] = [];\n if (declLines.some(l => l.includes('__dec('))) {\n imports.push(DECIMAL_IMPORT);\n // The global config keeps decimals out of exponential notation; only decimal.js needs it.\n preamble.push(DECIMAL_CONFIG_LINE, '');\n }\n const luxon = coerceLuxonImports(declLines);\n if (luxon.length > 0) imports.push(`import { ${luxon.join(', ')} } from 'luxon';`);\n\n return { imports, decls: [...preamble, ...decls] };\n}\n\n/**\n * The `luxon` import a client needs for its response-header coercions, or undefined.\n *\n * Header conversions call `DateTime.fromISO` and friends directly rather than through a reviver,\n * so they are invisible to `decimalPreludeFor`. Decided from the emitted method bodies, like every\n * other import in these files, and skipped when the reviver prelude already brought luxon in.\n */\nfunction headerLuxonImport(methodLines: string[], existingImports: string[]): string | undefined {\n if (existingImports.some(l => l.includes(\"from 'luxon'\"))) return undefined;\n const needed = ['DateTime', 'Duration'].filter(c => methodLines.some(l => l.includes(`${c}.from`)));\n return needed.length > 0 ? `import { ${needed.join(', ')} } from 'luxon';` : undefined;\n}\n\n/** Model reviver names referenced by generated method bodies. `__revive…` wrappers are local. */\n/**\n * Narrow a collected type list to the names the emitted code actually mentions.\n *\n * Boundaries are spelled out rather than using `\\b`, so a model name containing `-`, `.` or `$`\n * is matched correctly. A name appearing only inside a doc string counts as a reference and the\n * import is kept: an unnecessary import is untidy, a missing one does not compile.\n */\nfunction referencedTypes(types: string[], emitted: string[]): string[] {\n const haystack = emitted.join('\\n');\n return types.filter(t => {\n const escaped = t.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(?<![A-Za-z0-9_$])${escaped}(?![A-Za-z0-9_$])`).test(haystack);\n });\n}\n\nfunction usedRevivers(lines: string[]): string[] {\n const found = new Set<string>();\n for (const m of lines.join('\\n').matchAll(/\\brevive[A-Z]\\w*/g)) found.add(m[0]);\n return [...found].sort();\n}\n\n// ─── Method generation ────────────────────────────────────────────────────\n\nfunction generateMethod(\n route: OpRouteNode,\n op: OpOperationNode,\n file: string,\n options: SdkCodegenOptions,\n inlineRevivers?: Map<string, string[]>,\n): string[] {\n const revive: ReviveContext | undefined =\n options.modelsWithDecimal && options.modelsWithDecimal.size > 0 && inlineRevivers\n ? {\n modelsWithDecimal: options.modelsWithDecimal,\n modelsWithOutput: options.modelsWithOutput,\n modelMap: options.modelMap,\n inlineRevivers,\n nameHint: '',\n }\n : undefined;\n const lines: string[] = [];\n const methodName = deriveMethodName(op, route);\n /** Identifies the operation in a codegen rejection, which the CLI scopes to this plugin. */\n const where = `${op.method.toUpperCase()} ${route.path}`;\n const mRevive = hint(revive, `${methodName.charAt(0).toUpperCase()}${methodName.slice(1)}`);\n const httpMethod = op.method.toUpperCase();\n const { modelsWithInput, modelsWithOutput } = options;\n\n // Build method parameters (request-side — use Input variants)\n const params = buildMethodParams(route, op, modelsWithInput);\n const paramStr = params.map(p => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ');\n\n // Determine return type — response side uses Output variants (post-transform wire shape).\n // For non-JSON responses the schema is ignored: text/* is read as string, binary as Blob.\n //\n // `observableResponses` is the client-side mirror of the router's `emittedResponses`: it also\n // covers statuses the service never writes but a client can still receive, such as a 304 from\n // conditional-GET middleware. Anything left over reaches the caller as a thrown SdkError.\n const observable = observableResponses(op);\n const thrown = thrownResponses(op);\n const isMultiStatus = observable.length > 1;\n const primaryResponse = observable[0];\n const primaryBodies = primaryResponse ? primaryResponse.bodies : [];\n const isVoid = primaryBodies.length === 0;\n const respHeaders = primaryResponse?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersShape = hasRespHeaders ? renderSdkHeadersShape(respHeaders, modelsWithOutput) : '';\n\n // A union of more than one member is broken across lines — a four-status operation runs to\n // several hundred characters on one line otherwise.\n let returnMembers: string[] | undefined;\n let returnType = '';\n if (isMultiStatus) {\n returnMembers = observable.flatMap(r => sdkResponseMembers(r, modelsWithOutput, true));\n } else if (primaryBodies.length > 1) {\n returnMembers = sdkResponseMembers(primaryResponse!, modelsWithOutput, false);\n } else {\n const dataType = isVoid ? 'void' : sdkDataType(primaryBodies[0]!, modelsWithOutput);\n returnType = hasRespHeaders ? (isVoid ? `{ headers: ${headersShape} }` : `{ data: ${dataType}; headers: ${headersShape} }`) : dataType;\n }\n if (returnMembers?.length === 1) {\n returnType = returnMembers[0]!;\n returnMembers = undefined;\n }\n\n // Statuses the shared fetch would otherwise reject. All-2xx operations pass nothing, so the\n // overwhelmingly common case keeps its existing call shape.\n const expectStatuses = observable.filter(r => r.statusCode < 200 || r.statusCode >= 300).map(r => r.statusCode);\n\n // JSDoc\n const desc = op.description ?? route.description;\n const errorBodyName = thrown.some(r => r.bodies.length > 0) ? errorBodyTypeName(route, op) : undefined;\n // `@deprecated` belongs in this block rather than in one of its own: TypeScript honours only\n // the JSDoc comment adjacent to the declaration, so a separate `/** @deprecated */` above a\n // description block is dropped by editors entirely. Tag order mirrors the router's.\n const deprecated = resolveModifiers(route, op).includes('deprecated');\n if (op.name || desc || errorBodyName || deprecated) {\n const tags: string[] = [];\n if (op.name) tags.push(`@name ${op.name}`);\n if (desc) tags.push(`@description ${desc}`);\n if (errorBodyName) tags.push(`@throws {SdkError<${errorBodyName}>} on ${thrown.map(r => r.statusCode).join(', ')}`);\n if (deprecated) tags.push('@deprecated');\n const contentLines = tags.flatMap(t => escapeJsDocLines(t));\n if (contentLines.length === 1) {\n lines.push(` /** ${contentLines[0]} */`);\n } else {\n lines.push(` /**`);\n for (const l of contentLines) lines.push(` * ${l}`);\n lines.push(` */`);\n }\n }\n\n if (returnMembers) {\n lines.push(` async ${methodName}(${paramStr}): Promise<`);\n for (const member of returnMembers) lines.push(` | ${member}`);\n lines.push(` > {`);\n } else {\n lines.push(` async ${methodName}(${paramStr}): Promise<${returnType}> {`);\n }\n\n // Build URL with path params\n const urlExpr = buildUrlExpression(route.path, route.params);\n\n // Query string\n const hasQuery = !!op.query;\n let fetchUrl = urlExpr;\n if (hasQuery) {\n lines.push(` const qs = buildQueryString(query);`);\n fetchUrl = urlExpr;\n }\n\n // Build fetch options\n const strategy = classifyBodyStrategy(op);\n const hasBody = strategy.kind !== 'none';\n const hasOpHeaders = !!op.headers;\n\n // Pre-emit serialization preludes for multi-MIME strategies\n if (strategy.kind === 'multi-equal') {\n const defaultCt = strategy.bodies[0]!.contentType;\n lines.push(` const __contentType = options?.contentType ?? '${defaultCt}';`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n } else if (strategy.kind === 'multi-formdata-detect') {\n lines.push(` const __isFormData = body instanceof FormData;`);\n const nonMultipart = strategy.bodies.find(b => b.contentType !== 'multipart/form-data')!;\n lines.push(` const __contentType: string = __isFormData ? 'multipart/form-data' : '${nonMultipart.contentType}';`);\n lines.push(\n ` const __serialized: BodyInit = __isFormData ? (body as FormData) : ${jsonOrFormSerialize('body', nonMultipart.contentType)};`,\n );\n } else if (strategy.kind === 'multi-required-arg') {\n lines.push(` const __contentType = options.contentType;`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n }\n\n const fetchArgs: string[] = [];\n\n if (hasQuery) {\n fetchArgs.push(`url: \\`${fetchUrl}\\${qs}\\``);\n } else {\n fetchArgs.push(`url: \\`${fetchUrl}\\``);\n }\n\n fetchArgs.push(`method: '${httpMethod}'`);\n\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n // FormData supplies its own Content-Type with boundary; don't override it.\n fetchArgs.push('body: body');\n } else if (cat === 'urlencoded') {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: new URLSearchParams(body as unknown as Record<string, string>).toString()');\n } else if (cat === 'text' || cat === 'binary') {\n // text/* and binary mimes pass the body through to fetch as-is — no schema serialization.\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: body');\n } else {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: JSON.stringify(body, bigIntReplacer)');\n }\n } else if (hasBody) {\n // multi-equal | multi-formdata-detect | multi-required-arg — share a __contentType / __serialized prelude\n fetchArgs.push(`headers: { 'Content-Type': __contentType }`);\n fetchArgs.push('body: __serialized');\n }\n\n if (hasOpHeaders) {\n const lastHeaderIdx = fetchArgs.findIndex(a => a.startsWith('headers:'));\n if (lastHeaderIdx !== -1) {\n const existing = fetchArgs[lastHeaderIdx]!;\n const inner = existing.slice('headers: '.length).replace(/^\\{\\s*|\\s*\\}$/g, '');\n fetchArgs[lastHeaderIdx] = `headers: { ${inner}, ...customHeaders }`;\n } else {\n fetchArgs.push('headers: customHeaders');\n }\n }\n\n if (expectStatuses.length > 0) fetchArgs.push(`expectStatuses: [${expectStatuses.join(', ')}]`);\n\n const needsResult = isMultiStatus || !isVoid || hasRespHeaders;\n const resultPrefix = needsResult ? 'const result = ' : '';\n if (fetchArgs.length === 2 && !hasBody && !hasOpHeaders && !hasQuery) {\n // Simple case — inline\n lines.push(` ${resultPrefix}await this.fetch(\\`${fetchUrl}\\`, { method: '${httpMethod}' });`);\n } else {\n lines.push(` ${resultPrefix}await this.fetch(${fetchArgs[0]!.split(': ').slice(1).join(': ')}, {`);\n for (let i = 1; i < fetchArgs.length; i++) {\n lines.push(` ${fetchArgs[i]},`);\n }\n lines.push(` });`);\n }\n\n if (isMultiStatus) {\n // The status is only known at runtime, so the caller gets a union to narrow. The lowest\n // status is the default branch, which keeps the function exhaustively returning.\n const [fallback, ...rest] = observable;\n lines.push(` switch (result.status) {`);\n for (const resp of rest) {\n lines.push(` case ${resp.statusCode}:`);\n lines.push(...sdkReturnLines(resp, modelsWithOutput, ' ', true, mRevive, where));\n }\n lines.push(` default:`);\n lines.push(...sdkReturnLines(fallback!, modelsWithOutput, ' ', true, mRevive, where));\n lines.push(` }`);\n } else if (primaryBodies.length > 1) {\n lines.push(...sdkReturnLines(primaryResponse!, modelsWithOutput, ' ', false, mRevive, where));\n } else if (hasRespHeaders) {\n const headerEntries = sdkHeaderEntries(respHeaders, where);\n if (isVoid) {\n lines.push(` return { headers: { ${headerEntries} } };`);\n } else {\n lines.push(` const data = ${sdkReadExpr(primaryBodies[0]!, modelsWithOutput, hint(mRevive, primaryResponse!.statusCode))};`);\n lines.push(` return { data, headers: { ${headerEntries} } };`);\n }\n } else if (!isVoid) {\n lines.push(` return ${sdkReadExpr(primaryBodies[0]!, modelsWithOutput, hint(mRevive, primaryResponse!.statusCode))};`);\n }\n\n lines.push(' }');\n\n return lines;\n}\n\n// ─── Response shapes ──────────────────────────────────────────────────────\n\n/** The TypeScript type a client sees for one response body. */\nfunction sdkDataType(body: OpResponseBodyNode, modelsWithOutput?: Set<string>): string {\n const category = classifyContentType(body.contentType);\n if (category === 'text') return 'string';\n if (category === 'binary') return 'Blob';\n return renderOutputTsType(body.bodyType, modelsWithOutput);\n}\n\n/**\n * How a client reads one response body off the `Response`.\n *\n * A decimal-bearing body is wrapped in its reviver: `parseJson` is a bare cast, so without this the\n * type would say `Decimal` while the runtime held a string. Bodies with no decimal are emitted\n * byte-identically to before.\n */\nfunction sdkReadExpr(body: OpResponseBodyNode, modelsWithOutput?: Set<string>, revive?: ReviveContext): string {\n const category = classifyContentType(body.contentType);\n if (category === 'text') return 'await result.text()';\n if (category === 'binary') return 'await result.blob()';\n const tsType = renderOutputTsType(body.bodyType, modelsWithOutput);\n const read = `await parseJson<${tsType}>(result)`;\n const reviver = reviveExprFor(body.bodyType, revive);\n if (!reviver) return read;\n // `.map` over an array of refs rather than a wrapper function: the reviver returns the same\n // object it mutated, so the mapped array holds the same elements.\n return reviver.kind === 'array' ? `(${read}).map(${reviver.name})` : `${reviver.name}(${read})`;\n}\n\n/**\n * Extend the inline-reviver name with one more path segment.\n *\n * Built up compositionally — method, then status, then mime index — because each of those lives in\n * a different function, and the resulting name has to be distinct per body: two operations with\n * different inline decimal bodies must not share one wrapper.\n */\nfunction hint(revive: ReviveContext | undefined, segment: string | number): ReviveContext | undefined {\n if (!revive) return undefined;\n return { ...revive, nameHint: `${revive.nameHint}${segment}` };\n}\n\n/** What `sdkReadExpr` needs to decide whether a body has to be revived, and with which function. */\ninterface ReviveContext {\n modelsWithDecimal: Set<string>;\n /** Which scalars need rehydrating; see `ReviveCodegenOptions.revivableScalars`. */\n revivableScalars?: ReadonlySet<ScalarTypeNode['name']>;\n modelsWithOutput?: Set<string>;\n /** Inline reviver declarations accumulated for the current file, keyed by function name. */\n inlineRevivers: Map<string, string[]>;\n modelMap?: Map<string, ModelNode>;\n /** Distinguishes the inline wrapper emitted for each body. */\n nameHint: string;\n}\n\n/** The reviver to apply to a response body, or `null` when the body holds nothing to rehydrate. */\nfunction reviveExprFor(bodyType: ContractTypeNode, ctx: ReviveContext | undefined): { name: string; kind: 'value' | 'array' } | null {\n if (!ctx || ctx.modelsWithDecimal.size === 0) return null;\n const opts = {\n modelsWithDecimal: ctx.modelsWithDecimal,\n revivableScalars: ctx.revivableScalars,\n modelsWithOutput: ctx.modelsWithOutput,\n modelMap: ctx.modelMap,\n };\n if (!typeReachesDecimal(bodyType, opts)) return null;\n\n const refName = (t: ContractTypeNode): string | null => (t.kind === 'ref' ? t.name : t.kind === 'lazy' ? refName(t.inner) : null);\n const pick = (name: string) => reviveFnName(name, ctx.modelsWithOutput?.has(name) ? 'output' : 'base');\n\n const direct = refName(bodyType);\n if (direct && ctx.modelsWithDecimal.has(direct)) return { name: pick(direct), kind: 'value' };\n\n if (bodyType.kind === 'array') {\n const item = refName(bodyType.item);\n if (item && ctx.modelsWithDecimal.has(item)) return { name: pick(item), kind: 'array' };\n }\n\n // Anything else — an inline object, a record, a tuple — has no `reviveX` to call, so the file\n // gets a wrapper of its own.\n const fnName = `__revive${ctx.nameHint}`;\n if (!ctx.inlineRevivers.has(fnName)) {\n const decl = renderInlineReviver(fnName, renderOutputTsType(bodyType, ctx.modelsWithOutput), bodyType, opts);\n if (!decl) return null;\n ctx.inlineRevivers.set(fnName, decl);\n }\n return { name: fnName, kind: 'value' };\n}\n\nfunction renderSdkHeadersShape(headers: OpResponseHeaderNode[], modelsWithOutput?: Set<string>): string {\n const fields = headers.map(\n h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput)}`,\n );\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * The value expression for one response header, matching the type `renderSdkHeadersShape` gives it.\n *\n * Header values always arrive as strings, but the shape is typed from the contract — so a header\n * declared `int` was typed `number` and assigned `string | undefined`, and a required one was\n * typed `T` and assigned `T | undefined`. Both are `TS2322`, in opposite directions.\n *\n * `null` is what `Headers.get` returns for an absent header. A required header is asserted rather\n * than defaulted, because the contract says the service always sends it; an optional one maps the\n * absence onto `undefined`, which is what its `?` in the shape means.\n *\n * Anything that is not one of the scalars below cannot be read from a header at all, and is\n * rejected here rather than emitted as code that does not compile. The list is shared with the\n * Python SDK, except that temporals need coercion there — `renderPyType` maps them to `datetime`\n * objects, while `renderOutputTsType` maps them to `string`.\n */\nfunction sdkHeaderEntry(h: OpResponseHeaderNode, where: string): string {\n const raw = `result.headers.get('${h.name}')`;\n const key = quoteKey(headerNameToProperty(h.name));\n const scalar = h.type.kind === 'scalar' ? h.type.name : undefined;\n\n /**\n * Wrap a conversion so an optional header maps an absent value onto `undefined`.\n *\n * The value is asserted non-null in both branches. TypeScript does not carry a narrowing from\n * `get(x) === null` across a *second* `get(x)` call, and the conversions below take a `string`\n * — so without the assertion the optional form is a TS2345 even though the ternary has\n * already excluded null.\n */\n const convert = (expr: (v: string) => string) =>\n `${key}: ${h.optional ? `${raw} === null ? undefined : ${expr(`${raw}!`)}` : expr(`${raw}!`)}`;\n\n switch (scalar) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n case 'interval':\n case 'unknown':\n return `${key}: ${raw}${h.optional ? ' ?? undefined' : '!'}`;\n // Temporals are Luxon objects since the SDK started reviving them, so the shape\n // `renderOutputTsType` produces says `DateTime` and the raw string no longer satisfies it.\n // The format for date and time comes from the contract, as it does in the reviver.\n case 'datetime':\n return convert(v => `DateTime.fromISO(${v})`);\n case 'duration':\n return convert(v => `Duration.fromISO(${v})`);\n case 'date':\n return convert(v => `DateTime.fromFormat(${v}, '${(h.type.kind === 'scalar' && h.type.format) || 'yyyy-MM-dd'}')`);\n case 'time':\n return convert(v => `DateTime.fromFormat(${v}, '${(h.type.kind === 'scalar' && h.type.format) || 'HH:mm:ss'}')`);\n case 'number':\n case 'int':\n return `${key}: ${h.optional ? `${raw} === null ? undefined : Number(${raw})` : `Number(${raw})`}`;\n case 'boolean':\n return `${key}: ${h.optional ? `${raw} === null ? undefined : ${raw} === 'true'` : `${raw} === 'true'`}`;\n case 'bigint':\n return convert(v => `BigInt(${v})`);\n default:\n throw new Error(\n `Response header '${h.name}' on ${where} is declared as ${describeHeaderType(h.type)}, which cannot be read from an HTTP header. ` +\n `Header values arrive as strings — declare it as string, email, url, uuid, a date/time type, int, number, boolean or bigint.`,\n );\n }\n}\n\n/** A short, contract-facing description of a header type, for the rejection message above. */\nfunction describeHeaderType(type: ContractTypeNode): string {\n return type.kind === 'scalar' ? `the '${type.name}' scalar` : type.kind === 'ref' ? `the model '${type.name}'` : `${type.kind === 'array' ? 'an' : 'a'} ${type.kind}`;\n}\n\nfunction sdkHeaderEntries(headers: OpResponseHeaderNode[], where: string): string {\n return headers.map(h => sdkHeaderEntry(h, where)).join(', ');\n}\n\n/**\n * Render one response as the members of the client's return union — the mirror of the router's\n * service-result members, with `data` in place of `body`.\n *\n * Collapses to a single member with a union of mime literals when every declared mime yields the\n * same data type; otherwise one member per mime, so `contentType` and `data` stay correlated.\n */\nfunction sdkResponseMembers(resp: OpResponseNode, modelsWithOutput: Set<string> | undefined, includeStatus: boolean): string[] {\n const bodies = resp.bodies;\n const headers = resp.headers ?? [];\n const leading = includeStatus ? [`status: ${resp.statusCode}`] : [];\n const trailing = headers.length > 0 ? [`headers: ${renderSdkHeadersShape(headers, modelsWithOutput)}`] : [];\n\n if (bodies.length === 0) {\n return [`{ ${[...leading, ...trailing].join('; ')} }`];\n }\n\n const dataTypes = bodies.map(b => sdkDataType(b, modelsWithOutput));\n if (dataTypes.every(t => t === dataTypes[0])) {\n const contentType = bodies.map(b => `'${b.contentType}'`).join(' | ');\n return [`{ ${[...leading, `contentType: ${contentType}`, `data: ${dataTypes[0]}`, ...trailing].join('; ')} }`];\n }\n return bodies.map((b, i) => `{ ${[...leading, `contentType: '${b.contentType}'`, `data: ${dataTypes[i]}`, ...trailing].join('; ')} }`);\n}\n\n/** The `return` statement(s) that build one response's member of the return union. */\nfunction sdkReturnLines(\n resp: OpResponseNode,\n modelsWithOutput: Set<string> | undefined,\n indent: string,\n includeStatus: boolean,\n revive: ReviveContext | undefined,\n where: string,\n): string[] {\n const bodies = resp.bodies;\n const headers = resp.headers ?? [];\n const leading = includeStatus ? [`status: ${resp.statusCode}`] : [];\n const trailing = headers.length > 0 ? [`headers: { ${sdkHeaderEntries(headers, where)} }`] : [];\n\n if (bodies.length === 0) {\n return [`${indent}return { ${[...leading, ...trailing].join(', ')} };`];\n }\n if (bodies.length === 1) {\n const fields = [\n ...leading,\n `contentType: '${bodies[0]!.contentType}'`,\n `data: ${sdkReadExpr(bodies[0]!, modelsWithOutput, hint(revive, resp.statusCode))}`,\n ...trailing,\n ];\n return [`${indent}return { ${fields.join(', ')} };`];\n }\n\n const dataTypes = bodies.map(b => sdkDataType(b, modelsWithOutput));\n if (dataTypes.every(t => t === dataTypes[0])) {\n // Every mime reads the same way, so only the label has to come off the wire.\n const cast = bodies.map(b => `'${b.contentType}'`).join(' | ');\n const fields = [\n ...leading,\n `contentType: readContentType(result) as ${cast}`,\n `data: ${sdkReadExpr(bodies[0]!, modelsWithOutput, hint(revive, resp.statusCode))}`,\n ...trailing,\n ];\n return [`${indent}return { ${fields.join(', ')} };`];\n }\n\n // The mimes read differently, so the client has to dispatch on what actually came back.\n const lines = [`${indent}switch (readContentType(result)) {`];\n for (const [i, body] of bodies.slice(1).entries()) {\n const fields = [\n ...leading,\n `contentType: '${body.contentType}'`,\n `data: ${sdkReadExpr(body, modelsWithOutput, hint(revive, `${resp.statusCode}_${i + 1}`))}`,\n ...trailing,\n ];\n lines.push(`${indent} case '${body.contentType}':`);\n lines.push(`${indent} return { ${fields.join(', ')} };`);\n }\n const first = bodies[0]!;\n const fallbackFields = [\n ...leading,\n `contentType: '${first.contentType}'`,\n `data: ${sdkReadExpr(first, modelsWithOutput, hint(revive, `${resp.statusCode}_0`))}`,\n ...trailing,\n ];\n lines.push(`${indent} default:`);\n lines.push(`${indent} return { ${fallbackFields.join(', ')} };`);\n lines.push(`${indent}}`);\n return lines;\n}\n\n// ─── Error body typing ────────────────────────────────────────────────────\n\nfunction errorBodyTypeName(route: OpRouteNode, op: OpOperationNode): string {\n const method = deriveMethodName(op, route);\n return `${method.charAt(0).toUpperCase()}${method.slice(1)}ErrorBody`;\n}\n\n/**\n * Module-level `…ErrorBody` aliases for every operation whose thrown statuses declare a body.\n *\n * TypeScript cannot type a `throw`, so the alias plus the method's `@throws` tag is as far as the\n * error contract can be carried: it gives callers something to narrow `SdkError.body` to instead\n * of leaving them with `unknown`.\n */\nexport function generateErrorBodyAliases(root: OpRootNode, options: SdkCodegenOptions): string[] {\n const includeInternal = options.includeInternal ?? false;\n const lines: string[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n const types = new Set<string>();\n for (const resp of thrownResponses(op)) {\n for (const body of resp.bodies) types.add(sdkDataType(body, options.modelsWithOutput));\n }\n if (types.size === 0) continue;\n lines.push(`export type ${errorBodyTypeName(route, op)} = ${[...types].join(' | ')};`);\n }\n }\n return lines;\n}\n\n// ─── URL building ─────────────────────────────────────────────────────────\n\n/**\n * Render a route path as the template-literal body that produces the request URL.\n *\n * `params` says where each value lives. `buildMethodParams` spreads a `params { … }` block across\n * the signature, so those interpolate by bare name; but for `params: SomeModel` it emits a single\n * argument called `params`, and interpolating the bare name then refers to nothing that exists.\n *\n * The placeholder pattern matches what the `.ck` grammar allows rather than just\n * `[a-zA-Z_]\\w*`, so a hyphenated `{payment-id}` is interpolated instead of being left in the URL\n * verbatim. Such a name is not a valid property accessor either, hence the bracket form.\n */\nfunction buildUrlExpression(path: string, params?: ParamSource): string {\n return path.replace(PATH_PARAM_RE_G, (_m, name: string) => {\n // Spread across the signature: interpolate the identifier `buildMethodParams` bound.\n if (!params || params.kind === 'params') return `\\${encodeURIComponent(${toIdentifier(name)})}`;\n // Behind one `params` argument: read the model's field, which keeps its declared spelling\n // and so may need bracket access. `String(...)` because that field may be typed something\n // `encodeURIComponent` does not accept.\n const access = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? `params.${name}` : `params[${JSON.stringify(name)}]`;\n return `\\${encodeURIComponent(String(${access}))}`;\n });\n}\n\n// ─── Method parameters ────────────────────────────────────────────────────\n\ninterface MethodParam {\n name: string;\n type: string;\n optional: boolean;\n}\n\nfunction buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {\n const params: MethodParam[] = [];\n\n // Path params — always first, always required (request-side — use Input variants)\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const p of route.params.nodes) {\n params.push({ name: toIdentifier(p.name), type: renderInputTsType(p.type, modelsWithInput), optional: false });\n }\n } else if (route.params.kind === 'ref') {\n const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;\n params.push({ name: 'params', type: typeName, optional: false });\n } else {\n params.push({ name: 'params', type: renderInputTsType(route.params.node, modelsWithInput), optional: false });\n }\n }\n\n // Body (request-side — use Input variants)\n const strategy = classifyBodyStrategy(op);\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n params.push({ name: 'body', type: 'FormData', optional: false });\n } else if (cat === 'text') {\n params.push({ name: 'body', type: 'string', optional: false });\n } else if (cat === 'binary') {\n params.push({ name: 'body', type: 'Blob | ArrayBuffer | Uint8Array | string', optional: false });\n } else {\n params.push({ name: 'body', type: renderInputTsType(body.bodyType, modelsWithInput), optional: false });\n }\n } else if (strategy.kind === 'multi-equal') {\n const bodies = strategy.bodies;\n const bodyType = renderInputTsType(bodies[0]!.bodyType, modelsWithInput);\n params.push({ name: 'body', type: bodyType, optional: false });\n const ctUnion = bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType?: ${ctUnion} }`, optional: true });\n } else if (strategy.kind === 'multi-formdata-detect') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n } else if (strategy.kind === 'multi-required-arg') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n const ctUnion = strategy.bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType: ${ctUnion} }`, optional: false });\n }\n\n // Query and custom headers (request-side — use Input variants)\n if (op.query) params.push(inlineArgParam('query', op.query, modelsWithInput));\n if (op.headers) params.push(inlineArgParam('customHeaders', op.headers, modelsWithInput));\n\n return normaliseOptionalOrder(params);\n}\n\n/**\n * One whole-object argument built from a `query:` or `headers:` source.\n *\n * A field is optional only when the contract says so — with `?`, or by carrying a default, which\n * the caller may equally omit. The argument itself is optional only when every field is, since a\n * caller cannot omit an object that must supply something. Both were previously hardcoded\n * optional, which was wrong in both directions at once: it let a caller omit a value the router\n * demanded, and typed a required field as one you could leave out.\n *\n * A `ref` or a whole type node stays optional. Deciding needs the model's own fields, which\n * `buildMethodParams` has no access to.\n */\nfunction inlineArgParam(name: string, source: ParamSource, modelsWithInput?: Set<string>): MethodParam {\n if (source.kind === 'params') {\n const isOptional = (p: OpParamNode) => Boolean(p.optional) || p.default !== undefined;\n const fields = source.nodes\n .map(p => `${quoteKey(p.name)}${isOptional(p) ? '?' : ''}: ${renderInputTsType(p.type, modelsWithInput)}`)\n .join('; ');\n return { name, type: `{ ${fields} }`, optional: source.nodes.every(isOptional) };\n }\n if (source.kind === 'ref') {\n const typeName = modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;\n return { name, type: typeName, optional: true };\n }\n return { name, type: renderInputTsType(source.node, modelsWithInput), optional: true };\n}\n\n/**\n * Clear `optional` on every parameter before the last required one.\n *\n * Parameter order is path, then body, then query, then customHeaders. An optional parameter\n * cannot precede a required one in TypeScript (`TS1016`), so an operation with an all-optional\n * `query:` and an all-required `headers:` would emit `async m(query?: Q, customHeaders: H)` and\n * fail to compile. Widening the earlier argument to required is the only option that keeps the\n * positional order the call sites depend on.\n *\n * This could not arise while every query and header argument was hardcoded optional; it becomes\n * reachable the moment optionality is read from the contract.\n */\nfunction normaliseOptionalOrder(params: MethodParam[]): MethodParam[] {\n const lastRequired = params.reduce((last, p, i) => (p.optional ? last : i), -1);\n return params.map((p, i) => (i < lastRequired ? { ...p, optional: false } : p));\n}\n\n// ─── Method name inference ────────────────────────────────────────────────\n\nfunction deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {\n if (op.sdk) return op.sdk;\n if (op.name) return nameToMethodName(op.name);\n return inferMethodName(op.method, route.path);\n}\n\nfunction nameToMethodName(name: string): string {\n const parts = name.split(/[\\s\\-_]+/).filter(Boolean);\n return parts.map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join('');\n}\n\nfunction inferMethodName(method: string, path: string): string {\n // Build a name from the path segments + method\n // e.g. GET /users/:id → getUsersById\n // e.g. POST /users → postUsers\n // e.g. DELETE /users/:id → deleteUsersById\n const segments = path.split('/').filter(s => s.length > 0);\n const parts: string[] = [method.toLowerCase()];\n\n for (const seg of segments) {\n if (seg.startsWith('{')) {\n // {id} → ById, {accountId} → ByAccountId\n const paramName = seg.slice(1, -1);\n parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));\n } else {\n // Regular segment — camelCase it\n const segParts = seg.split(/[.-]/).filter(Boolean);\n for (const sp of segParts) {\n parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));\n }\n }\n }\n\n return parts[0]! + parts.slice(1).join('');\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\nfunction deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\n/** Derive a client class name from a `.ck` file path, e.g. `users.ck` → `UsersClient`. Used for legacy flat (no-area) files. */\nexport function deriveClientClassName(file: string): string {\n return `${deriveBaseName(file)}Client`;\n}\n\n/** Camel-cased property name for a flat client on the SDK aggregator, e.g. `users.ck` → `users`. */\nexport function deriveClientPropertyName(file: string): string {\n const base = deriveBaseName(file);\n return base.charAt(0).toLowerCase() + base.slice(1);\n}\n\n/**\n * Pull `area` / `subarea` from a file's `root.meta` (set via `options { keys: { ... } }`).\n * Both are optional. `area` drives top-level SDK grouping; `subarea` drives nesting under\n * an area's client class.\n */\nexport function getAreaSubarea(root: OpRootNode): { area?: string; subarea?: string } {\n return { area: root.meta?.area, subarea: root.meta?.subarea };\n}\n\nfunction pascal(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction camel(value: string): string {\n const p = pascal(value);\n return p.charAt(0).toLowerCase() + p.slice(1);\n}\n\n/** Class name for the area-level client, e.g. `area=identity` → `IdentityClient`. */\nexport function deriveAreaClientClassName(area: string): string {\n return `${pascal(area)}Client`;\n}\n\n/** Property name on the SDK aggregator for an area, e.g. `area=identity` → `identity`. */\nexport function deriveAreaPropertyName(area: string): string {\n return camel(area);\n}\n\n/** Class name for a leaf subarea client, e.g. `(identity, invitations)` → `IdentityInvitationsClient`. */\nexport function deriveSubareaClientClassName(area: string, subarea: string): string {\n return `${pascal(area)}${pascal(subarea)}Client`;\n}\n\n/** Property name on the area client for a subarea, e.g. `subarea=invitations` → `invitations`. */\nexport function deriveSubareaPropertyName(subarea: string): string {\n return camel(subarea);\n}\n\n// ─── Type collection ──────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>, includeInternal = false): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n const publicOps = route.operations.filter(op => includeInternal || !resolveModifiers(route, op).includes('internal'));\n if (publicOps.length === 0) continue;\n // Only collect path-param types if there are public ops on this route\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of publicOps) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n for (const body of resp.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectOutputTypeNodeRefs(body.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectOutputTypeNodeRefs(m, out, modelsWithOutput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectInputTypeNodeRefs(param.type, out, modelsWithInput);\n }\n } else {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeNodeRefs(m, out, modelsWithInput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** True if any emitted operation has query params (drives the `buildQueryString` import). */\nfunction sdkNeedsQueryString(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n if (op.query) return true;\n }\n }\n return false;\n}\n\n/**\n * True if any emitted operation has a status declaring several mimes, so the client has to read\n * the actual content type off the response to know which it got.\n */\nfunction sdkNeedsReadContentType(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n if (observableResponses(op).some(r => r.bodies.length > 1)) return true;\n }\n }\n return false;\n}\n\n/** True if any emitted operation serializes a JSON request body (uses bigIntReplacer). */\nfunction sdkNeedsBigIntReplacer(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n if (op.request && op.request.bodies.some(b => isJsonMime(b.contentType))) return true;\n }\n }\n return false;\n}\n\n/** True if any public operation parses a JSON response body, and so calls `parseJson`. */\nfunction sdkParsesJsonResponse(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n // Only JSON-shaped responses use parseJson — text/binary read raw.\n if (op.responses.some(r => r.bodies.some(b => classifyContentType(b.contentType) === 'json'))) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * True if a public operation's JSON *response* carries a `bigint`, so the client needs the\n * `123n` reviver when parsing one.\n *\n * Response bodies only: the request side is handled by `bigIntReplacer` on the way out. This is\n * the test the reviver always needed and never made — it was applied to every client that read\n * any JSON at all, so a contract with no bigint anywhere still had a legitimate string like\n * \"123n\" silently converted.\n */\nfunction sdkResponsesUseBigInt(root: OpRootNode, options: SdkCodegenOptions, includeInternal = false): boolean {\n const tainted = options.modelsWithBigInt;\n const reachesBigInt = (type: ContractTypeNode): boolean => {\n // `typeNeedsScalar` stops at a `ref` leaf, so the transitive answer has to come from the\n // precomputed set — a bigint two models down still arrives on the wire as `123n`.\n switch (type.kind) {\n case 'ref':\n return tainted?.has(type.name) ?? false;\n case 'array':\n return reachesBigInt(type.item);\n case 'lazy':\n return reachesBigInt(type.inner);\n case 'tuple':\n return type.items.some(reachesBigInt);\n case 'record':\n return reachesBigInt(type.value);\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n return type.members.some(reachesBigInt);\n case 'inlineObject':\n return type.fields.some(f => reachesBigInt(f.type));\n default:\n return typeNeedsScalar(type, 'bigint');\n }\n };\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n for (const resp of op.responses) {\n for (const body of resp.bodies) {\n if (classifyContentType(body.contentType) === 'json' && reachesBigInt(body.bodyType)) return true;\n }\n }\n }\n }\n return false;\n}\n\nfunction sdkNeedsJson(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n const check = (src: ParamSource | undefined) => {\n if (!src || src.kind === 'ref') return false;\n if (src.kind === 'params') return src.nodes.some(p => typeNeedsScalar(p.type, 'json'));\n return typeNeedsScalar(src.node, 'json');\n };\n if (\n !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, 'json')) ||\n op.responses.some(r => r.bodies.some(b => typeNeedsScalar(b.bodyType, 'json'))) ||\n check(op.query) ||\n check(op.headers) ||\n check(route.params)\n )\n return true;\n }\n }\n return false;\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\n// ─── Type import resolution ───────────────────────────────────────────────\n\nfunction generateTypeImports(types: string[], opFile: string, options: SdkCodegenOptions, revivers: string[] = []): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import type { ${names.sort().join(', ')} } from '${rel}';`);\n // Revivers are values, so they need a second, non-type import from the same module.\n const fromHere = revivers.filter(r => modelOutPaths.get(reviverModelName(r, names)) === typeOutPath);\n if (fromHere.length > 0) lines.push(`import { ${fromHere.sort().join(', ')} } from '${rel}';`);\n }\n\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import type { ${type} } from './${moduleName}.js';`);\n }\n } else {\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import type { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\n/**\n * The model a reviver belongs to. `reviveInvoiceOutput` can come from either `Invoice` (with an\n * `Output` variant) or a model literally called `InvoiceOutput`, so the names actually imported\n * from the module decide it.\n */\nfunction reviverModelName(reviver: string, namesInModule: string[]): string {\n const stem = reviver.replace(/^revive/, '');\n if (namesInModule.includes(stem)) return stem;\n const base = stem.replace(/Output$/, '');\n return namesInModule.includes(base) ? base : stem;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n\n// ─── Shared SDK files ──────────────────────────────────────────────────────\n\n/** Generate the shared SdkOptions interface file. */\nexport function generateSdkOptions(): string {\n return [\n 'export class SdkError<TBody = unknown> extends Error {',\n ' constructor(',\n ' public readonly status: number,',\n ' public readonly statusText: string,',\n ' public readonly body: TBody,',\n ' public readonly headers: Headers,',\n ' ) {',\n ' super(`${status} ${statusText}`);',\n \" this.name = 'SdkError';\",\n ' }',\n '}',\n '',\n 'export interface SdkRequestInit extends RequestInit {',\n ' /**',\n ' * Statuses this operation declares as values rather than errors — a 304 from',\n ' * conditional-GET middleware, or an error status the service returns deliberately.',\n ' * Anything else at or above 400 still throws SdkError.',\n ' */',\n ' expectStatuses?: number[];',\n '}',\n '',\n 'export type SdkFetch = (url: string, init: SdkRequestInit) => Promise<Response>;',\n '',\n 'export interface SdkOptions {',\n ' baseUrl: string;',\n ' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);',\n ' fetch?: SdkFetch;',\n ' /** Called once per request to produce a unique X-Request-ID header value */',\n ' requestIdFactory?: () => string;',\n '}',\n '',\n 'export const bigIntReplacer = (_: string, value: any): any => {',\n \" if (typeof value === 'bigint') {\",\n \" return value.toString() + 'n';\",\n ' }',\n ' return value;',\n '};',\n '',\n 'export const bigIntReviver = (_: string, value: any): any => {',\n \" if (typeof value === 'string' && /^-?\\\\d+n$/.test(value)) {\",\n ' return BigInt(value.slice(0, -1));',\n ' }',\n ' return value;',\n '};',\n '',\n JSON_VALUE_TYPE_DECL,\n '',\n 'export function readContentType(res: Response): string {',\n \" return res.headers.get('content-type')?.split(';')[0]?.trim() ?? '';\",\n '}',\n '',\n 'export function createSdkFetch(options: SdkOptions): SdkFetch {',\n ' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());',\n ' return async (url: string, init: SdkRequestInit): Promise<Response> => {',\n \" const baseHeaders = typeof options.headers === 'function'\",\n ' ? await options.headers()',\n ' : options.headers ?? {};',\n ' const res = await fetch(`${options.baseUrl}${url}`, {',\n ' ...init,',\n \" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\",\n ' });',\n ' if (!res.ok && !(init.expectStatuses ?? []).includes(res.status)) {',\n ' const text = await res.text();',\n ' let body: unknown;',\n ' try { body = JSON.parse(text); } catch { body = text; }',\n ' throw new SdkError(res.status, res.statusText, body, res.headers);',\n ' }',\n ' return res;',\n ' };',\n '}',\n '',\n 'export function buildQueryString(query: object | undefined): string {',\n ' const searchParams = new URLSearchParams();',\n ' if (query) {',\n ' for (const [k, v] of Object.entries(query)) {',\n ' if (v === undefined || v === null) continue;',\n ' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }',\n ' else searchParams.set(k, String(v));',\n ' }',\n ' }',\n ' const qs = searchParams.toString();',\n \" return qs ? `?${qs}` : '';\",\n '}',\n '',\n '/**',\n ' * Read a JSON response body.',\n ' *',\n ' * No reviver: `bigIntReviver` matches any string of the form `123n` anywhere in the',\n ' * document, so a contract with no bigint field would still have a legitimate string like',\n ' * \"123n\" silently turned into a BigInt. Clients whose contracts do use bigint import',\n ' * `parseJsonWithBigInt` under this name instead.',\n ' */',\n 'export async function parseJson<T>(res: Response): Promise<T> {',\n ' return JSON.parse(await res.text()) as T;',\n '}',\n '',\n '/** `parseJson` for contracts that declare a bigint, applying the `123n` reviver. */',\n 'export async function parseJsonWithBigInt<T>(res: Response): Promise<T> {',\n ' return JSON.parse(await res.text(), bigIntReviver) as T;',\n '}',\n '',\n ].join('\\n');\n}\n\n// ─── Scaffold files (package.json / tsconfig.json) ─────────────────────────\n\n/** Pinned dependency ranges for scaffolded SDK packages. Kept in one place so they're easy to bump. */\nconst SCAFFOLD_DEP_VERSIONS = {\n zod: '^4.3.6',\n luxon: '^3.5.0',\n decimalJs: '^10.4.3',\n typesLuxon: '^3.4.2',\n typescript: '^6.0.3',\n} as const;\n\n/** Which optional runtime deps the generated SDK references, derived from the contracts it covers. */\nexport interface SdkScaffoldDeps {\n /** Zod schema files are emitted (`config.zod`) — the SDK imports `zod`. */\n zod: boolean;\n /** Any covered model uses a `date`/`time`/`datetime`/`duration`/`interval` scalar — the SDK imports `luxon`. */\n luxon: boolean;\n /** Any covered model uses a `decimal` scalar — the SDK imports `decimal.js`. */\n decimal: boolean;\n}\n\n/**\n * Generate a starter `package.json` for a generated SDK package. Emitted with\n * `ifAbsent` semantics — written once, then owned by the user — so the dependency\n * ranges here are only ever a starting point, never re-applied on later builds.\n */\nexport function generateSdkPackageJson(input: { name: string; deps: SdkScaffoldDeps }): string {\n const dependencies: Record<string, string> = {};\n if (input.deps.zod) dependencies.zod = SCAFFOLD_DEP_VERSIONS.zod;\n if (input.deps.luxon) dependencies.luxon = SCAFFOLD_DEP_VERSIONS.luxon;\n // No `@types/` half — decimal.js ships its own declarations.\n if (input.deps.decimal) dependencies['decimal.js'] = SCAFFOLD_DEP_VERSIONS.decimalJs;\n\n const devDependencies: Record<string, string> = { typescript: SCAFFOLD_DEP_VERSIONS.typescript };\n if (input.deps.luxon) devDependencies['@types/luxon'] = SCAFFOLD_DEP_VERSIONS.typesLuxon;\n\n const pkg = {\n name: input.name,\n version: '0.0.0',\n type: 'module',\n main: './dist/index.js',\n types: './dist/index.d.ts',\n exports: {\n '.': {\n types: './dist/index.d.ts',\n import: './dist/index.js',\n },\n },\n files: ['dist'],\n scripts: {\n build: 'tsc -p tsconfig.json',\n },\n ...(Object.keys(dependencies).length > 0 ? { dependencies } : {}),\n devDependencies,\n };\n return JSON.stringify(pkg, null, 4) + '\\n';\n}\n\n/**\n * Generate a standalone `tsconfig.json` for a generated SDK package. Deliberately\n * self-contained (no workspace `extends`) so the scaffold works in a freshly\n * `npm init`'d package outside this monorepo. Emitted with `ifAbsent` semantics.\n */\nexport function generateSdkTsconfig(): string {\n const tsconfig = {\n compilerOptions: {\n target: 'ES2022',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n declaration: true,\n outDir: './dist',\n rootDir: './src',\n strict: true,\n esModuleInterop: true,\n skipLibCheck: true,\n forceConsistentCasingInFileNames: true,\n },\n include: ['src'],\n exclude: ['dist', 'node_modules'],\n };\n return JSON.stringify(tsconfig, null, 4) + '\\n';\n}\n\n/**\n * Reference to a per-file leaf client emitted to its own `*.client.ts`. Used by the\n * aggregator to import the class and wire it as either a top-level `sdk.<prop>` or a\n * nested `sdk.<area>.<subarea>` property.\n */\nexport interface SdkClientInfo {\n /** Client class name (e.g. `UsersClient`, `IdentityInvitationsClient`). */\n className: string;\n /** Property name to expose this client under (e.g. `users`, `invitations`). */\n propertyName: string;\n /** Module specifier for the leaf file, relative to `sdk.ts` and `.js`-suffixed. */\n importPath: string;\n}\n\n/**\n * One area-level (no-subarea) `.ck` file whose methods are merged into the area's\n * `<Area>Client` (emitted to its own `<area>.client.ts`).\n */\nexport interface SdkAreaInlineFile {\n /** Parsed AST. */\n root: OpRootNode;\n /** Codegen options for this file (must have `outPath` pointing at the area client file so type-import paths resolve correctly). */\n codegenOptions: SdkCodegenOptions;\n}\n\n/** A grouping of files that share the same `keys.area`. */\nexport interface SdkAreaInfo {\n area: string;\n /**\n * Reference to the `<Area>Client` class — the file that holds it lives at\n * `client.importPath` (relative to `sdk.ts`) and is generated separately by\n * {@link generateAreaClient}. The aggregator just imports it.\n */\n client: SdkClientInfo;\n}\n\nexport interface SdkAggregatorInput {\n /** Files with no `keys.area` — kept as flat `Sdk.<filename>` properties (legacy behavior). */\n topLevelClients: SdkClientInfo[];\n /** One entry per `keys.area`. */\n areas: SdkAreaInfo[];\n /** Path to `sdk-options.ts` to import `SdkOptions`/`createSdkFetch`/etc. from. */\n sdkOptionsImportPath?: string;\n /** Name of the top-level aggregator class. Defaults to `Sdk`. */\n sdkClassName?: string;\n}\n\n/** Inputs to {@link generateAreaClient}. */\nexport interface AreaClientInput {\n /** Area name (e.g. `payments`). Drives the generated class name (`PaymentsClient`). */\n area: string;\n /** Output path of the generated `<area>.client.ts` file. Used to resolve relative type / leaf-client / sdk-options imports. */\n outPath: string;\n /** Files contributing inlined methods to the area client (typically area-level files with no subarea). */\n inlineFiles: SdkAreaInlineFile[];\n /** Subarea leaf clients exposed as named properties on the area client. */\n subareaClients: { propertyName: string; client: SdkClientInfo }[];\n /** Path to `sdk-options.ts`, used for `SdkFetch` and runtime helpers. */\n sdkOptionsPath: string;\n}\n\n/**\n * Generate a complete `<area>.client.ts` file: the `<Area>Client` class with\n * subarea property fields, a constructor that wires them, and inlined methods\n * merged from every area-level file in `inlineFiles`.\n *\n * Emitted by the plugin alongside the per-leaf `*.client.ts` files. The SDK\n * aggregator just imports the resulting class — see {@link generateSdkAggregator}.\n *\n * @throws if two area-level files contribute the same method name to the area —\n * disambiguate via `sdk:` on the operation, or move one into a subarea.\n */\nexport function generateAreaClient(input: AreaClientInput): string {\n const { area, outPath, inlineFiles, subareaClients, sdkOptionsPath } = input;\n const className = deriveAreaClientClassName(area);\n\n // ── Merge inputs across all inline files ────────────────────────────────\n const collectedMethodLines: string[] = [];\n const collectedRevivePrelude: string[] = [];\n let areaNeedsDecimalImport = false;\n /** Reviver value imports, grouped the same way `typesByImportPath` groups the type imports. */\n const reviversByImportPath = new Map<string, Set<string>>();\n // Aliases are keyed off method names, which already collide-check below, so a Set is enough.\n const collectedErrorAliases = new Set<string>();\n const seenMethods = new Set<string>();\n const typesByImportPath = new Map<string, Set<string>>();\n const unresolvedTypes = new Set<string>();\n let needsJson = false;\n let needsBigIntReplacer = false;\n let needsParseJson = false;\n let needsBigIntReviver = false;\n let needsQueryString = false;\n let needsReadContentType = false;\n\n for (const inline of inlineFiles) {\n const includeInternal = inline.codegenOptions.includeInternal ?? false;\n const { lines: methodLines, methodNames, preludeLines, needsDecimalImport } = generateClientMethods(inline.root, inline.codegenOptions);\n collectedRevivePrelude.push(...preludeLines);\n if (needsDecimalImport) areaNeedsDecimalImport = true;\n for (const name of methodNames) {\n if (seenMethods.has(name)) {\n throw new Error(\n `[sdk] duplicate method '${name}' in area '${area}': two area-level files contribute the same method. Disambiguate via 'sdk:' or move one into a subarea.`,\n );\n }\n seenMethods.add(name);\n }\n collectedMethodLines.push(...methodLines);\n for (const alias of generateErrorBodyAliases(inline.root, inline.codegenOptions)) collectedErrorAliases.add(alias);\n if (sdkNeedsJson(inline.root, includeInternal)) needsJson = true;\n if (sdkNeedsBigIntReplacer(inline.root, includeInternal)) needsBigIntReplacer = true;\n if (sdkParsesJsonResponse(inline.root, includeInternal)) needsParseJson = true;\n if (sdkResponsesUseBigInt(inline.root, inline.codegenOptions, includeInternal)) needsBigIntReviver = true;\n if (sdkNeedsQueryString(inline.root, includeInternal)) needsQueryString = true;\n if (sdkNeedsReadContentType(inline.root, includeInternal)) needsReadContentType = true;\n\n // Revivers this file's methods call, resolved against the same modelOutPaths. Derived from\n // the emitted lines, exactly as `generateSdk` does, so the two paths cannot disagree.\n for (const reviver of usedRevivers(methodLines)) {\n const stem = reviver.replace(/^revive/, '');\n const modelOut = inline.codegenOptions.modelOutPaths?.get(stem) ?? inline.codegenOptions.modelOutPaths?.get(stem.replace(/Output$/, ''));\n if (!modelOut) continue;\n let rel = relative(dirname(outPath), modelOut).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const set = reviversByImportPath.get(rel) ?? new Set<string>();\n set.add(reviver);\n reviversByImportPath.set(rel, set);\n }\n\n // Resolve each file's type refs against THIS file's modelOutPaths, but\n // produce import paths relative to the area client's outPath (not the\n // contributing file's outPath, which pointed at the now-defunct sdk.ts).\n // Filtered against this file's own emitted text for the same reason `generateSdk` filters\n // its own — a multipart body's model is collected but never named in the output.\n const typesForFile = referencedTypes(\n collectTypes(inline.root, inline.codegenOptions.modelsWithInput, inline.codegenOptions.modelsWithOutput, includeInternal),\n [...methodLines, ...generateErrorBodyAliases(inline.root, inline.codegenOptions), ...preludeLines],\n );\n const { modelOutPaths } = inline.codegenOptions;\n if (modelOutPaths) {\n const fromDir = dirname(outPath);\n for (const t of typesForFile) {\n const typeOutPath = modelOutPaths.get(t);\n if (typeOutPath) {\n let rel = relative(fromDir, typeOutPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const set = typesByImportPath.get(rel) ?? new Set();\n set.add(t);\n typesByImportPath.set(rel, set);\n } else {\n unresolvedTypes.add(t);\n }\n }\n }\n }\n\n // ── Imports ─────────────────────────────────────────────────────────────\n let sdkOptionsRel = relative(dirname(outPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!sdkOptionsRel.startsWith('.')) sdkOptionsRel = './' + sdkOptionsRel;\n\n const lines: string[] = [];\n const jsonImport = needsJson ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${sdkOptionsRel}';`);\n const valueImports: string[] = [];\n if (needsBigIntReplacer) valueImports.push('bigIntReplacer');\n if (needsParseJson) valueImports.push(needsBigIntReviver ? 'parseJsonWithBigInt as parseJson' : 'parseJson');\n if (needsQueryString) valueImports.push('buildQueryString');\n if (needsReadContentType) valueImports.push('readContentType');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${sdkOptionsRel}';`);\n }\n\n for (const path of [...typesByImportPath.keys()].sort()) {\n const names = [...typesByImportPath.get(path)!].sort();\n lines.push(`import type { ${names.join(', ')} } from '${path}';`);\n const revivers = reviversByImportPath.get(path);\n if (revivers && revivers.size > 0) lines.push(`import { ${[...revivers].sort().join(', ')} } from '${path}';`);\n }\n for (const t of [...unresolvedTypes].sort()) {\n lines.push(`import type { ${t} } from './${pascalToDotCase(t)}.js';`);\n }\n\n if (areaNeedsDecimalImport) lines.push(DECIMAL_IMPORT);\n const areaHeaderLuxon = headerLuxonImport(collectedMethodLines, collectedRevivePrelude);\n if (areaHeaderLuxon) lines.push(areaHeaderLuxon);\n\n // Leaf client imports (subareas only — top-level clients live next to sdk.ts).\n const importedClients = new Set<string>();\n for (const sc of subareaClients) {\n const key = `${sc.client.className}|${sc.client.importPath}`;\n if (importedClients.has(key)) continue;\n importedClients.add(key);\n lines.push(`import { ${sc.client.className} } from '${sc.client.importPath}';`);\n }\n lines.push('');\n\n if (collectedErrorAliases.size > 0) {\n lines.push(...collectedErrorAliases);\n lines.push('');\n }\n\n if (collectedRevivePrelude.length > 0) {\n lines.push(...collectedRevivePrelude);\n lines.push('');\n }\n\n // ── <Area>Client class ──────────────────────────────────────────────────\n lines.push(`export class ${className} {`);\n for (const sc of subareaClients) {\n lines.push(` readonly ${sc.propertyName}: ${sc.client.className};`);\n }\n if (subareaClients.length > 0) lines.push('');\n if (collectedMethodLines.length > 0 || subareaClients.length > 0) {\n const fetchModifier = collectedMethodLines.length > 0 ? 'private ' : '';\n lines.push(` constructor(${fetchModifier}fetch: SdkFetch) {`);\n for (const sc of subareaClients) {\n lines.push(` this.${sc.propertyName} = new ${sc.client.className}(fetch);`);\n }\n lines.push(' }');\n }\n for (const ln of collectedMethodLines) lines.push(ln);\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the SDK aggregator (`sdk.ts`) — the entry-point file consumers import.\n *\n * Imports every `<Area>Client` (one per area, generated by {@link generateAreaClient}\n * to its own `<area>.client.ts`) and every leaf top-level client, then emits a\n * `class Sdk` that exposes them as properties.\n */\nexport function generateSdkAggregator(input: SdkAggregatorInput): string {\n const sdkOptionsImportPath = input.sdkOptionsImportPath ?? './sdk-options.js';\n const sdkClassName = input.sdkClassName ?? 'Sdk';\n\n const lines: string[] = [];\n lines.push(`import type { SdkOptions } from '${sdkOptionsImportPath}';`);\n lines.push(`import { createSdkFetch } from '${sdkOptionsImportPath}';`);\n\n const importedClients = new Set<string>();\n const pushClientImport = (c: SdkClientInfo): void => {\n const key = `${c.className}|${c.importPath}`;\n if (importedClients.has(key)) return;\n importedClients.add(key);\n lines.push(`import { ${c.className} } from '${c.importPath}';`);\n };\n // Areas first, then top-level — keeps the aggregator's import order stable.\n for (const area of input.areas) pushClientImport(area.client);\n for (const c of input.topLevelClients) pushClientImport(c);\n lines.push('');\n\n lines.push(`export class ${sdkClassName} {`);\n for (const area of input.areas) {\n lines.push(` readonly ${deriveAreaPropertyName(area.area)}: ${area.client.className};`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` readonly ${c.propertyName}: ${c.className};`);\n }\n lines.push('');\n lines.push(' constructor(options: SdkOptions) {');\n lines.push(' const sdkFetch = options.fetch ?? createSdkFetch(options);');\n for (const area of input.areas) {\n lines.push(` this.${deriveAreaPropertyName(area.area)} = new ${area.client.className}(sdkFetch);`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` this.${c.propertyName} = new ${c.className}(sdkFetch);`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n","import type { ContractRootNode, ModelNode, FieldNode } from '@contractkit/core';\nimport { computeModelsWithOutput, collectExternalOutputRefs } from '@contractkit/core';\nimport type { ContractCodegenContext } from './codegen-contract.js';\nimport {\n collectExternalRefs,\n collectExternalInputRefs,\n computeModelsWithInput,\n topoSortModels,\n resolveImportPath,\n rootNeedsScalar,\n} from './codegen-contract.js';\nimport { renderTsType, renderInputTsType, renderOutputTsType, quoteKey, escapeJsDocLines, sourceLink, JSON_VALUE_TYPE_DECL } from './ts-render.js';\nimport type { TsRenderTarget } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_CONFIG_LINE } from './decimal-runtime.js';\nimport { renderReviveFunctions, reviveFnName, coerceDeclsFor } from './codegen-revive.js';\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Generate plain TypeScript interfaces/types from a contract AST.\n * Unlike `generateContract()` which produces Zod schemas, this emits\n * vanilla TypeScript `interface` and `type` declarations suitable\n * for SDK consumers that don't need runtime validation.\n *\n * @param context Import resolution and Input/Output variant sets. `context.target` selects the\n * runtime the types describe (`'server'` renders `binary` as `Buffer`, `'client'` as `Blob`).\n */\nexport function generatePlainTypes(root: ContractRootNode, context?: ContractCodegenContext): string {\n const target: TsRenderTarget = context?.target ?? 'client';\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = computeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input/Output refs needed for variant fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? collectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n // Not `import type`: `renderTsScalar` maps `decimal` to `Decimal` in this mode too, so the class\n // is a real runtime dependency of any consumer holding one — same position as in\n // `generateContract`, which emits it ahead of the external model refs.\n const needsDecimal = rootNeedsScalar(root, 'decimal') || (context?.emitRevivers && context.modelsWithDecimal ? root.models.some(m => context.modelsWithDecimal!.has(m.name)) : false);\n if (needsDecimal) lines.push(DECIMAL_IMPORT);\n\n // Likewise for the temporal scalars: `renderTsScalar` maps them to Luxon classes, which are a\n // real runtime dependency of anyone holding one. `interval` is not among them — it renders as\n // a string, since `_ZodInterval` transforms back to ISO on output.\n const luxonImports: string[] = [];\n if (rootNeedsScalar(root, 'date') || rootNeedsScalar(root, 'time') || rootNeedsScalar(root, 'datetime')) luxonImports.push('DateTime');\n if (rootNeedsScalar(root, 'duration')) luxonImports.push('Duration');\n if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n\n // Type-only imports for external references. A cross-file model carrying a decimal also\n // contributes its reviver, which is a value and so needs a second, non-type import.\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n lines.push(`import type { ${ref} } from '${importPath}';`);\n if (context?.emitRevivers && context.modelsWithDecimal?.has(ref)) {\n lines.push(`import { ${reviveFnName(ref)} } from '${importPath}';`);\n }\n }\n if (allExternalRefs.length > 0) lines.push('');\n\n if (rootNeedsScalar(root, 'json')) {\n if (context?.jsonValueImportPath) {\n lines.push(`import type { JsonValue } from '${context.jsonValueImportPath}';`);\n } else {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n lines.push('');\n }\n\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n const reviveOpts =\n context?.emitRevivers && context.modelsWithDecimal\n ? { modelsWithDecimal: context.modelsWithDecimal, modelsWithOutput: allModelsWithOutput, modelMap }\n : undefined;\n\n const bodyLines: string[] = [];\n for (const model of topoSortModels(root.models)) {\n bodyLines.push(...generateModel(model, target, context?.currentOutPath, allModelsWithInput, allModelsWithOutput, modelMap));\n if (reviveOpts) {\n const revivers = renderReviveFunctions(model, reviveOpts);\n if (revivers.length > 0) {\n bodyLines.push('');\n bodyLines.push(...revivers);\n }\n }\n bodyLines.push('');\n }\n\n // Global decimal.js config belongs in any file holding a `Decimal`: there is no Zod schema in\n // this mode, but `String(value)` and `JSON.stringify` still have to stay out of exponential form.\n if (needsDecimal) {\n lines.push('');\n lines.push(DECIMAL_CONFIG_LINE);\n }\n\n // Same rule as in `generateContract`: a helper is emitted only if the revivers actually\n // reference it, so the two cannot drift and trip `noUnusedLocals`.\n const coerceDecls = coerceDeclsFor(bodyLines);\n if (coerceDecls.length > 0) {\n lines.push(...coerceDecls);\n lines.push('');\n }\n lines.push(...bodyLines);\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\nfunction generateModel(\n model: ModelNode,\n target: TsRenderTarget,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithOutput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, target, outPath, modelsWithInput, modelsWithOutput);\n }\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = model.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(model.name) ?? false);\n\n const lines = needsInputSplit\n ? generateVisibilityModel(model, target, outPath, modelsWithInput, modelMap)\n : generateSimpleModel(model, target, outPath, modelMap);\n\n if (modelsWithOutput?.has(model.name)) {\n lines.push('');\n lines.push(...generateOutputModel(model, target, modelsWithOutput));\n }\n return lines;\n}\n\n/** Recursively collect every field name defined on `bases` and their ancestors. Used to detect\n * fields that the child re-declares without an explicit `override` keyword — those still need an\n * `Omit<Base, …>` wrap, otherwise the child's narrower/incompatible declaration collides with the\n * inherited one. */\nfunction collectInheritedFieldNames(bases: string[], modelMap: Map<string, ModelNode>): Set<string> {\n const result = new Set<string>();\n const visit = (name: string): void => {\n const m = modelMap.get(name);\n if (!m || m.type) return;\n for (const f of m.fields) result.add(f.name);\n for (const b of m.bases ?? []) visit(b);\n };\n for (const b of bases) visit(b);\n return result;\n}\n\n/** Names of fields the child declaration overrides — explicit `override` plus any field whose\n * name shadows an inherited one. The latter catches single-base redeclarations that omit the\n * `override` keyword (e.g. narrowing `kind: BusinessRoleKind` → `kind: 'employee'`). */\nfunction computeOverrideNames(model: ModelNode, modelMap?: Map<string, ModelNode>): string[] {\n const inherited = modelMap ? collectInheritedFieldNames(model.bases ?? [], modelMap) : new Set<string>();\n return model.fields.filter(f => f.override || inherited.has(f.name)).map(f => f.name);\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n for (const l of escapeJsDocLines(model.description)) lines.push(` * ${l}`);\n }\n\n lines.push(` * generated from ${sourceLink(model.name, outPath, model.loc.file, model.loc.line)}`);\n lines.push(' */');\n return lines;\n}\n\nfunction generateTypeAlias(\n model: ModelNode,\n target: TsRenderTarget,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithOutput?: Set<string>,\n): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export type ${model.name} = ${renderTsType(model.type!, target)};`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export type ${model.name}Input = ${renderInputTsType(model.type!, modelsWithInput, target)};`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = ${renderOutputTsType(model.type!, modelsWithOutput, target)};`);\n }\n return lines;\n}\n\n/** Build the `extends` clause for a model.\n * Each entry in `overrideNames` is wrapped in `Omit<Base, 'name1' | 'name2'>` per base so the\n * subclass can legally redeclare those fields with new (possibly incompatible) types.\n * TypeScript's `Omit<T, K extends keyof any>` tolerates omit keys that don't appear on the base,\n * so we apply the same omit list to every base without per-base field-set lookup. */\nfunction buildExtendsClause(bases: string[], overrideNames: string[], baseNameResolver: (b: string) => string): string {\n if (bases.length === 0) return '';\n if (overrideNames.length === 0) return ` extends ${bases.map(baseNameResolver).join(', ')}`;\n const omitKeys = overrideNames.map(n => `'${n}'`).join(' | ');\n const wrapped = bases.map(b => `Omit<${baseNameResolver(b)}, ${omitKeys}>`);\n return ` extends ${wrapped.join(', ')}`;\n}\n\nfunction generateSimpleModel(model: ModelNode, target: TsRenderTarget, outPath?: string, modelMap?: Map<string, ModelNode>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n\n for (const field of model.fields) {\n lines.push(` ${renderField(field, target)}`);\n }\n\n lines.push('}');\n return lines;\n}\n\nfunction generateVisibilityModel(\n model: ModelNode,\n target: TsRenderTarget,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n\n // Read type — omit writeonly fields\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n for (const field of readFields) {\n lines.push(` ${renderField(field, target)}`);\n }\n lines.push('}');\n lines.push('');\n\n // Write type — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read type\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n const inputResolver = (b: string) => (modelsWithInput?.has(b) ? `${b}Input` : b);\n lines.push(`export interface ${model.name}Input${buildExtendsClause(bases, overrideNames, inputResolver)} {`);\n for (const field of writeFields) {\n lines.push(` ${modelsWithInput ? renderInputField(field, modelsWithInput, target) : renderField(field, target)}`);\n }\n lines.push('}');\n\n return lines;\n}\n\n// ─── Field rendering ──────────────────────────────────────────────────────\n\n/** Prefix a field declaration with a JSDoc comment built from `@deprecated` / description parts,\n * neutralizing any block-comment terminator and expanding embedded newlines into continuation lines. */\nfunction withFieldJsDoc(jsdocParts: string[], line: string): string {\n if (jsdocParts.length === 0) return line;\n const contentLines = escapeJsDocLines(jsdocParts.join(' '));\n if (contentLines.length === 1) {\n return `/** ${contentLines[0]} */\\n ${line}`;\n }\n const body = contentLines.map(l => ` * ${l}`).join('\\n');\n return `/**\\n${body}\\n */\\n ${line}`;\n}\n\nfunction renderField(field: FieldNode, target: TsRenderTarget): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderTsType(field.type, target);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n return withFieldJsDoc(jsdocParts, line);\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>, target: TsRenderTarget): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderInputTsType(field.type, modelsWithInput, target);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n return withFieldJsDoc(jsdocParts, line);\n}\n\n// ─── Output (post-transform wire shape) ──────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyOutputCase(name: string, c: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!c || c === 'camel') return name;\n if (c === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\n/**\n * Emit `${name}Output` for a model in the output transitive set.\n * - Direct hits (model.outputCase set): rename keys per the transform and substitute nested refs.\n * - Transitive hits: keep field names as-is but substitute nested refs with their Output variants.\n *\n * `extends` is dropped for direct-hit models because the Zod schema flattens fields when an\n * ancestor has format(...) (see `flattenFormatChain` in codegen-contract); we mirror that here\n * so the plain interface matches the wire shape produced by the Zod transform.\n */\nfunction generateOutputModel(model: ModelNode, target: TsRenderTarget, modelsWithOutput: Set<string>): string[] {\n const lines: string[] = [];\n const outputCase = model.outputCase && model.outputCase !== 'camel' ? model.outputCase : undefined;\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n\n // Transitive-only (no direct outputCase): preserve `extends` and original key names.\n if (!outputCase) {\n const baseExt =\n model.bases?.[0] && modelsWithOutput.has(model.bases?.[0])\n ? ` extends ${model.bases?.[0]}Output`\n : model.bases?.[0]\n ? ` extends ${model.bases?.[0]}`\n : '';\n lines.push(`export interface ${model.name}Output${baseExt} {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, model.outputCase, modelsWithOutput, target)}`);\n }\n lines.push('}');\n return lines;\n }\n\n // Direct hit: emit a flat interface with renamed keys.\n lines.push(`export interface ${model.name}Output {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, outputCase, modelsWithOutput, target)}`);\n }\n lines.push('}');\n return lines;\n}\n\nfunction renderOutputField(\n field: FieldNode,\n outputCase: 'camel' | 'snake' | 'pascal' | undefined,\n modelsWithOutput: Set<string>,\n target: TsRenderTarget,\n): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n const key = applyOutputCase(field.name, outputCase);\n let typeStr = renderOutputTsType(field.type, modelsWithOutput, target);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(key)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n return withFieldJsDoc(jsdocParts, line);\n}\n","import type { OpRootNode, OpRouteNode, OpOperationNode, McpConfigNode, ParamSource, ContractTypeNode } from '@contractkit/core';\nimport { resolveModifiers, emittedResponses, toIdentifier } from '@contractkit/core';\nimport { renderType, renderInputType, pascalToDotCase } from './codegen-contract.js';\nimport { inferService, deriveModulePath, buildArgs, deriveBaseName } from './codegen-operation.js';\nimport { quoteKey, escapeSingleQuoted, sourceLink } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_PRELUDE_LINES } from './decimal-runtime.js';\nimport { basename, dirname, relative } from 'node:path';\n\n// ─── Options ────────────────────────────────────────────────────────────────\n\nexport interface McpCodegenOptions {\n /** Absolute path of the file being generated. Used to compute relative imports. */\n outPath?: string;\n /** Map from schema identifier (model name / `${name}Input`) → absolute output file. */\n modelOutPaths?: Map<string, string>;\n /** Model names that have an Input variant schema. */\n modelsWithInput?: Set<string>;\n /** Model names that have an Output variant schema. */\n modelsWithOutput?: Set<string>;\n /** Import-path template for service implementations (same semantics as ServerConfig). */\n servicePathTemplate?: string;\n /** Emit tools for `internal` operations. Default false. */\n includeInternal?: boolean;\n}\n\n// ─── MCP flag helpers ─────────────────────────────────────────────────────\n\n/** The explicit settings block, if the operation used the object form of `mcp:`. */\nfunction mcpConfig(op: OpOperationNode): McpConfigNode | undefined {\n return op.mcp && typeof op.mcp === 'object' ? op.mcp : undefined;\n}\n\n/**\n * True if the root has at least one MCP-exposed operation. With `includeInternal: false`\n * (default) `internal` operations don't count. Mirrors `hasPublicOperations`.\n */\nexport function hasMcpOperations(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!op.mcp) continue;\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n return true;\n }\n }\n return false;\n}\n\n// ─── Name derivation ────────────────────────────────────────────────────────\n\n/** camelCase / PascalCase / spaced / hyphenated → snake_case. */\nfunction toSnake(s: string): string {\n return s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .toLowerCase()\n .replace(/[^a-z0-9_]/g, '')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n}\n\n/** snake_case → PascalCase. */\nfunction toPascal(s: string): string {\n return s\n .split('_')\n .filter(Boolean)\n .map(p => p.charAt(0).toUpperCase() + p.slice(1))\n .join('');\n}\n\n/** Inferred snake_case tool name from method + path, e.g. GET /payments/{id} → get_payments_by_id. */\nfunction inferToolName(method: string, path: string): string {\n const parts: string[] = [method.toLowerCase()];\n for (const seg of path.split('/').filter(Boolean)) {\n if (seg.startsWith('{')) {\n parts.push('by', toSnake(seg.slice(1, -1)));\n } else {\n parts.push(toSnake(seg));\n }\n }\n return parts.filter(Boolean).join('_');\n}\n\n/** Tool name: explicit `mcp.name` (verbatim) → `sdk` → `name` → inferred; derived forms snake_cased. */\nfunction deriveToolName(op: OpOperationNode, route: OpRouteNode): string {\n const cfg = mcpConfig(op);\n if (cfg?.name) return cfg.name;\n if (op.sdk) return toSnake(op.sdk);\n if (op.name) return toSnake(op.name);\n return inferToolName(op.method, route.path);\n}\n\n/** Tool class name — PascalCase of the tool name with an `McpTool` suffix for clarity. */\nfunction deriveToolClassName(toolName: string): string {\n return `${toPascal(toolName)}McpTool`;\n}\n\n// ─── Input args schema ────────────────────────────────────────────────────\n\ninterface ArgsProp {\n key: string;\n expr: string;\n optional: boolean;\n}\n\n/** Build the flat args properties for a tool, matching the router's `buildArgs` variable names. */\nfunction buildArgsProps(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): ArgsProp[] {\n const props: ArgsProp[] = [];\n\n // Path params — spread individually (inline) or as a single `params` object (ref/type).\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const node of route.params.nodes) {\n // The handler destructures these, so the key has to be a valid identifier. The MCP\n // input schema is ours to name — nothing on an HTTP wire depends on it.\n props.push({ key: toIdentifier(node.name), expr: renderInputType(node.type, modelsWithInput), optional: false });\n }\n } else if (route.params.kind === 'ref') {\n props.push({ key: 'params', expr: refSchema(route.params.name, modelsWithInput), optional: false });\n } else {\n props.push({ key: 'params', expr: renderInputType(route.params.node, modelsWithInput), optional: false });\n }\n }\n\n // Body — single JSON body maps to a `body` field; multipart/binary/multi bodies aren't cleanly\n // representable as JSON tool args, so they fall back to `z.unknown()` (advisory only).\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data') {\n props.push({ key: 'multipartBody', expr: 'z.unknown()', optional: false });\n } else if (bodies.length === 1) {\n props.push({ key: 'body', expr: renderInputType(bodies[0]!.bodyType, modelsWithInput), optional: false });\n } else if (bodies.length > 1) {\n props.push({ key: 'body', expr: 'z.unknown()', optional: false });\n }\n\n // Query / headers — whole objects, optional.\n if (op.query) props.push({ key: 'query', expr: paramSourceSchema(op.query, modelsWithInput), optional: true });\n if (op.headers) props.push({ key: 'headers', expr: paramSourceSchema(op.headers, modelsWithInput), optional: true });\n\n return props;\n}\n\nfunction refSchema(name: string, modelsWithInput?: Set<string>): string {\n return modelsWithInput?.has(name) ? `${name}Input` : name;\n}\n\nfunction paramSourceSchema(src: ParamSource, modelsWithInput?: Set<string>): string {\n if (src.kind === 'ref') return refSchema(src.name, modelsWithInput);\n if (src.kind === 'type') return renderInputType(src.node, modelsWithInput);\n const fields = src.nodes.map(n => `${quoteKey(n.name)}: ${renderInputType(n.type, modelsWithInput)}`).join(', ');\n return `z.object({ ${fields} })`;\n}\n\nfunction argsSchemaExpr(props: ArgsProp[]): string {\n if (props.length === 0) return 'z.object({})';\n const fields = props.map(p => `${quoteKey(p.key)}: ${p.expr}${p.optional ? '.optional()' : ''}`).join(', ');\n return `z.object({ ${fields} })`;\n}\n\n// ─── Output schema ──────────────────────────────────────────────────────────\n\n/**\n * The body an MCP tool reports as its output: the first body the service can actually return.\n *\n * Documented and thrown statuses are skipped — an MCP tool describes what a successful call\n * produces, not what the operation is allowed to document.\n */\nfunction primaryResponseBody(op: OpOperationNode): ContractTypeNode | undefined {\n for (const resp of emittedResponses(op)) {\n if (resp.bodies[0]) return resp.bodies[0].bodyType;\n }\n return undefined;\n}\n\n/** MCP output schemas must be objects — only model refs and inline objects qualify. */\nfunction outputSchemaExpr(op: OpOperationNode): string | undefined {\n const body = primaryResponseBody(op);\n if (!body) return undefined;\n if (body.kind === 'ref') return body.name;\n if (body.kind === 'inlineObject') return renderType(body);\n return undefined;\n}\n\n// ─── Annotations ────────────────────────────────────────────────────────────\n\nconst HINT_KEYS = ['readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWorldHint'] as const;\n\nfunction annotationsExpr(cfg: McpConfigNode | undefined): string | undefined {\n if (!cfg) return undefined;\n const parts: string[] = [];\n for (const key of HINT_KEYS) {\n const val = cfg[key];\n if (val !== undefined) parts.push(`${key}: ${val}`);\n }\n return parts.length > 0 ? `{ ${parts.join(', ')} }` : undefined;\n}\n\n// ─── Schema-import collection ───────────────────────────────────────────────\n\nfunction walkTypeRefs(type: ContractTypeNode, ids: Set<string>, variant: 'input' | 'read', modelsWithInput?: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n ids.add(variant === 'input' ? refSchema(type.name, modelsWithInput) : type.name);\n break;\n case 'array':\n walkTypeRefs(type.item, ids, variant, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(t => walkTypeRefs(t, ids, variant, modelsWithInput));\n break;\n case 'record':\n walkTypeRefs(type.key, ids, variant, modelsWithInput);\n walkTypeRefs(type.value, ids, variant, modelsWithInput);\n break;\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n type.members.forEach(t => walkTypeRefs(t, ids, variant, modelsWithInput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => walkTypeRefs(f.type, ids, variant, modelsWithInput));\n break;\n case 'lazy':\n walkTypeRefs(type.inner, ids, variant, modelsWithInput);\n break;\n }\n}\n\nfunction walkSourceRefs(src: ParamSource | undefined, ids: Set<string>, modelsWithInput?: Set<string>): void {\n if (!src) return;\n if (src.kind === 'ref') ids.add(refSchema(src.name, modelsWithInput));\n else if (src.kind === 'params') src.nodes.forEach(n => walkTypeRefs(n.type, ids, 'input', modelsWithInput));\n else walkTypeRefs(src.node, ids, 'input', modelsWithInput);\n}\n\n/** Collect every schema identifier the emitted tools import (input variants + read variants for output). */\nfunction collectSchemaIds(ops: { route: OpRouteNode; op: OpOperationNode }[], modelsWithInput?: Set<string>): Set<string> {\n const ids = new Set<string>();\n for (const { route, op } of ops) {\n walkSourceRefs(route.params, ids, modelsWithInput);\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 1 && bodies[0]!.contentType !== 'multipart/form-data') {\n walkTypeRefs(bodies[0]!.bodyType, ids, 'input', modelsWithInput);\n }\n walkSourceRefs(op.query, ids, modelsWithInput);\n walkSourceRefs(op.headers, ids, modelsWithInput);\n\n const body = primaryResponseBody(op);\n if (body && (body.kind === 'ref' || body.kind === 'inlineObject')) walkTypeRefs(body, ids, 'read');\n }\n return ids;\n}\n\nfunction schemaImportLines(ids: Set<string>, options: McpCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n if (ids.size === 0) return lines;\n if (modelOutPaths && outPath) {\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n for (const id of ids) {\n const p = modelOutPaths.get(id);\n if (p) {\n const group = byFile.get(p) ?? [];\n group.push(id);\n byFile.set(p, group);\n } else {\n unresolved.push(id);\n }\n }\n const fromDir = dirname(outPath);\n for (const [file, names] of byFile) {\n let rel = relative(fromDir, file).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import { ${names.sort().join(', ')} } from '${rel}';`);\n }\n for (const id of unresolved.sort()) lines.push(`import { ${id} } from './${pascalToDotCase(id)}.js';`);\n } else {\n for (const id of [...ids].sort()) lines.push(`import { ${id} } from './${pascalToDotCase(id)}.js';`);\n }\n return lines;\n}\n\n// ─── Zod scalar helper preludes ─────────────────────────────────────────────\n\nfunction scalarHelperLines(body: string): string[] {\n const lines: string[] = [];\n if (body.includes('_ZodBinary')) {\n lines.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (body.includes('_ZodDatetime')) {\n lines.push(\n `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' }));`,\n );\n }\n if (body.includes('_ZodDecimal')) {\n lines.push(...DECIMAL_PRELUDE_LINES);\n }\n if (body.includes('_ZodInterval')) {\n lines.push(\n `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()!);`,\n );\n }\n if (body.includes('_ZodJson')) {\n lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n lines.push(\n `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)]));`,\n );\n }\n return lines;\n}\n\n// ─── Per-tool codegen ─────────────────────────────────────────────────────\n\ninterface ToolPlan {\n route: OpRouteNode;\n op: OpOperationNode;\n toolName: string;\n className: string;\n argsConstName: string;\n}\n\nfunction planTools(root: OpRootNode, includeInternal: boolean): ToolPlan[] {\n const plans: ToolPlan[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!op.mcp) continue;\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n const toolName = deriveToolName(op, route);\n const className = deriveToolClassName(toolName);\n plans.push({ route, op, toolName, className, argsConstName: `${toPascal(toolName)}Args` });\n }\n }\n return plans;\n}\n\nfunction renderToolClass(plan: ToolPlan, file: string, options: McpCodegenOptions): string[] {\n const { route, op, toolName, className, argsConstName } = plan;\n const cfg = mcpConfig(op);\n const lines: string[] = [];\n\n // JSDoc source link\n lines.push('/**');\n lines.push(` * from ${sourceLink(basename(file), options.outPath, file, op.loc.line)}`);\n lines.push(' */');\n\n lines.push('@Injectable()');\n lines.push(`export class ${className} implements McpToolHandler {`);\n\n // definition\n lines.push(' readonly definition: Tool = {');\n lines.push(` name: '${escapeSingleQuoted(toolName)}',`);\n if (cfg?.title) lines.push(` title: '${escapeSingleQuoted(cfg.title)}',`);\n const desc = cfg?.description ?? op.description ?? route.description;\n if (desc) lines.push(` description: '${escapeSingleQuoted(desc)}',`);\n lines.push(` inputSchema: z.toJSONSchema(${argsConstName}, { unrepresentable: 'any' }) as Tool['inputSchema'],`);\n const outExpr = outputSchemaExpr(op);\n if (outExpr) lines.push(` outputSchema: z.toJSONSchema(${outExpr}, { unrepresentable: 'any' }) as Tool['outputSchema'],`);\n const annotations = annotationsExpr(cfg);\n if (annotations) lines.push(` annotations: ${annotations},`);\n lines.push(' };');\n lines.push('');\n\n // constructor injects the operation's service\n const service = inferService(op, route, file);\n lines.push(` constructor(private readonly service: ${service.className}) {}`);\n lines.push('');\n\n // handle\n const props = buildArgsProps(route, op, options.modelsWithInput);\n const destructure = props.map(p => p.key);\n const callArgs = buildArgs(route, op);\n const isVoid = !primaryResponseBody(op);\n const structured = !!outExpr;\n\n // No args to destructure means the parameter goes unread, which trips no-unused-vars in\n // consumers that lint generated output; the leading underscore opts it out.\n const argsParam = destructure.length > 0 ? 'args' : '_args';\n lines.push(` async handle(${argsParam}: Record<string, unknown>, _context: McpToolContext): Promise<CallToolResult> {`);\n if (destructure.length > 0) {\n lines.push(` const { ${destructure.join(', ')} } = await parseAndValidate(args, ${argsConstName});`);\n }\n if (isVoid) {\n lines.push(` await this.service.${service.methodName}(${callArgs});`);\n lines.push(` return { content: [{ type: 'text', text: 'OK' }] };`);\n } else {\n lines.push(` const result = await this.service.${service.methodName}(${callArgs});`);\n if (structured) {\n lines.push(` return { content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result };`);\n } else {\n lines.push(` return { content: [{ type: 'text', text: JSON.stringify(result) }] };`);\n }\n }\n lines.push(' }');\n lines.push('}');\n\n return lines;\n}\n\n// ─── Public entry points ────────────────────────────────────────────────────\n\n/** The exported register-fn name for an op-root file, e.g. `payments.op` → `registerPaymentsMcpTools`. */\nexport function deriveMcpRegisterFnName(file: string): string {\n return `register${deriveBaseName(file)}McpTools`;\n}\n\n/** Generate one `<filename>.mcp.ts` for an op-root: tool handler classes + a per-file register fn. */\nexport function generateMcpFile(root: OpRootNode, options: McpCodegenOptions = {}): string {\n const includeInternal = options.includeInternal ?? false;\n const plans = planTools(root, includeInternal);\n\n // Args schema consts (also drive the JSON-Schema definitions).\n const argsConsts = plans.map(p => `const ${p.argsConstName} = ${argsSchemaExpr(buildArgsProps(p.route, p.op, options.modelsWithInput))};`);\n\n // Tool classes.\n const classes = plans.map(p => renderToolClass(p, root.file, options).join('\\n'));\n\n // Per-file register fn.\n const registerFn: string[] = [];\n registerFn.push(`/** Add this file's tools to the shared catalog. */`);\n registerFn.push(`export function ${deriveMcpRegisterFnName(root.file)}(map: McpToolHandlerMap, container: Container): void {`);\n for (const p of plans) registerFn.push(` map.set('${escapeSingleQuoted(p.toolName)}', container.get(${p.className}));`);\n registerFn.push('}');\n\n const bodyCore = [argsConsts.join('\\n'), classes.join('\\n\\n'), registerFn.join('\\n')].filter(Boolean).join('\\n\\n');\n\n // Zod scalar helper consts (must precede the args consts that reference them).\n const helperConsts = scalarHelperLines(bodyCore);\n const bodyWithHelpers = [helperConsts.join('\\n'), bodyCore].filter(Boolean).join('\\n\\n');\n\n // ── Imports ──\n const needsParseAndValidate = plans.some(p => buildArgsProps(p.route, p.op, options.modelsWithInput).length > 0);\n const imports: string[] = [];\n imports.push(`import { Injectable, type Container } from 'injectkit';`);\n imports.push(`import { z } from 'zod';`);\n\n const luxon: string[] = [];\n if (/\\bDateTime\\b/.test(bodyWithHelpers)) luxon.push('DateTime');\n if (/\\bInterval\\b/.test(bodyWithHelpers)) luxon.push('Interval');\n if (/\\bDuration\\b/.test(bodyWithHelpers)) luxon.push('Duration');\n if (luxon.length > 0) imports.push(`import { ${luxon.join(', ')} } from 'luxon';`);\n if (/\\bDecimal\\b/.test(bodyWithHelpers)) imports.push(DECIMAL_IMPORT);\n\n imports.push(`import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';`);\n imports.push(`import type { McpToolHandler, McpToolHandlerMap, McpToolContext } from '@maroonedsoftware/mcp';`);\n if (needsParseAndValidate) imports.push(`import { parseAndValidate } from '@maroonedsoftware/zod';`);\n\n // Service imports (one per distinct service used by the emitted tools).\n const serviceModules = new Map<string, string>();\n for (const p of plans) {\n const svc = inferService(p.op, p.route, root.file).className;\n if (!serviceModules.has(svc)) {\n serviceModules.set(svc, root.services?.[svc] ?? root.meta[svc] ?? deriveModulePath(svc, options.servicePathTemplate));\n }\n }\n for (const [svc, mod] of [...serviceModules.entries()].sort(([a], [b]) => a.localeCompare(b))) {\n imports.push(`import { ${svc} } from '${mod}';`);\n }\n\n // Schema imports.\n imports.push(...schemaImportLines(collectSchemaIds(plans, options.modelsWithInput), options));\n\n const header = `// Auto-generated MCP tools\\n// generated from ${sourceLink(basename(root.file), options.outPath, root.file)}`;\n\n return `${header}\\n${imports.join('\\n')}\\n\\n${bodyWithHelpers}\\n`;\n}\n\n/** One entry per emitted `<filename>.mcp.ts` for the aggregator to import. */\nexport interface McpAggregatorEntry {\n /** The file's exported register fn name, e.g. `registerPaymentsMcpTools`. */\n registerFn: string;\n /** Module specifier for the file, relative to the aggregator and `.js`-suffixed. */\n importPath: string;\n}\n\n/** Generate the aggregator `mcp.tools.ts` that assembles the single McpToolHandlerMap. */\nexport function generateMcpAggregator(entries: McpAggregatorEntry[]): string {\n const sorted = [...entries].sort((a, b) => a.registerFn.localeCompare(b.registerFn));\n const lines: string[] = [];\n lines.push(`import { type Container } from 'injectkit';`);\n lines.push(`import { McpToolHandlerMap } from '@maroonedsoftware/mcp';`);\n for (const e of sorted) lines.push(`import { ${e.registerFn} } from '${e.importPath}';`);\n lines.push('');\n lines.push('/**');\n lines.push(' * Build the MCP tool catalog.');\n lines.push(' *');\n lines.push(' * Bind it to the `McpToolHandlerMap` token from a factory, which is what supplies the');\n lines.push(' * `Container` needed to resolve each handler:');\n lines.push(' *');\n lines.push(' * ```ts');\n lines.push(' * registry.register(McpToolHandlerMap).useFactory(registerMcpTools).asSingleton();');\n lines.push(' * ```');\n lines.push(' */');\n lines.push('export function registerMcpTools(container: Container): McpToolHandlerMap {');\n lines.push(' const map = new McpToolHandlerMap();');\n for (const e of sorted) lines.push(` ${e.registerFn}(map, container);`);\n lines.push(' return map;');\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\n\n/** Generate the optional `mcp.router.ts` — the standard ServerKit route wiring for the dispatcher. */\nexport function generateMcpRouter(options: { path?: string } = {}): string {\n const path = options.path ?? '/mcp';\n return `import { ServerKitRouter, bodyParserMiddleware, requireSignature } from '@maroonedsoftware/koa';\nimport { McpDispatcher, createMcpRequestContext, MCP_AUTH_POLICY } from '@maroonedsoftware/mcp';\n\n/** Mount the MCP endpoint onto a ServerKit router. Bind \\`registerMcpTools\\` to the \\`McpToolHandlerMap\\` token. */\nexport function mountMcp(router: ReturnType<typeof ServerKitRouter>): void {\n router.post('${path}', bodyParserMiddleware(['json']), requireSignature('mcp', { policy: MCP_AUTH_POLICY }), async (ctx) => {\n const dispatcher = ctx.container.get(McpDispatcher);\n const context = createMcpRequestContext({ requestId: ctx.requestId, logger: ctx.logger });\n if (dispatcher.sessionMode === 'stateful') {\n ctx.respond = false;\n await dispatcher.dispatchStateful(\n { req: ctx.req, res: ctx.res, body: ctx.parsedBody, sessionId: ctx.get('mcp-session-id') },\n context,\n );\n } else {\n const response = await dispatcher.dispatch(JSON.parse(String(ctx.rawBody)), context);\n if (response) ctx.body = response;\n else ctx.status = 202; // a notification — nothing to return\n }\n });\n}\n`;\n}\n","import { resolve, join, relative, dirname, isAbsolute } from 'node:path';\nimport type { ContractRootNode, OpRootNode } from '@contractkit/core';\nimport { collectTypeRefs, collectPublicTypeNames } from '@contractkit/core';\n\nexport const TEMPLATE_VAR_RE = /\\{\\w+\\}/;\n\n/**\n * Guard against path traversal in output-path templates. Output-path template variables\n * (`{area}`, `{dir}`, `{filename}`, `{name}`) can be sourced from a `.ck` file's\n * `options { keys }` block, so a malicious value like `../../../tmp/x` could escape the\n * plugin's output directory. After the final absolute path is computed, verify it stays\n * within `baseOutDir`; otherwise throw.\n */\nfunction assertWithinBase(baseOutDir: string, outPath: string): string {\n const rel = relative(resolve(baseOutDir), resolve(outPath));\n if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) {\n throw new Error(\n `Refusing to emit outside output directory: resolved path \"${outPath}\" escapes \"${baseOutDir}\" (check options { keys } values used in output path templates)`,\n );\n }\n return outPath;\n}\n\n/** Global-flagged twin of {@link TEMPLATE_VAR_RE}, for finding every variable in a string. */\nexport const TEMPLATE_VAR_RE_G = /\\{(\\w+)\\}/g;\n\n/**\n * Substitute `{key}` placeholders from `vars`.\n *\n * An unknown key is left in place rather than throwing, because the caller is mid-way through\n * building a path and has better context for the complaint — see the check at the emit funnel in\n * `index.ts`, which reports it against the file it would have been written to.\n */\nexport function resolveTemplate(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{(\\w+)\\}/g, (_, key) => vars[key] ?? `{${key}}`);\n}\n\nexport function includesFilename(p: string): boolean {\n const last = p.split('/').pop() ?? '';\n return last.includes('.');\n}\n\nexport function commonDir(files: string[], rootDir: string): string {\n if (files.length === 0) return resolve(rootDir);\n const parts = files.map(f => dirname(f).split('/'));\n const first = parts[0]!;\n let depth = first.length;\n for (const p of parts) {\n for (let i = 0; i < depth; i++) {\n if (p[i] !== first[i]) {\n depth = i;\n break;\n }\n }\n }\n return first.slice(0, depth).join('/') || '/';\n}\n\n// ─── Server / Zod output paths ─────────────────────────────────────────────\n\nexport function computeOpOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n const baseName = filePath.split('/').pop()!;\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n const defaultName = `${filename}${defaultSuffix}`;\n const baseOutDir = resolve(baseDir);\n\n if (output && TEMPLATE_VAR_RE.test(output)) {\n const resolved = resolveTemplate(output, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return assertWithinBase(baseOutDir, join(baseOutDir, resolved));\n return assertWithinBase(baseOutDir, join(baseOutDir, resolved, defaultName));\n }\n if (output) {\n if (includesFilename(output)) return assertWithinBase(baseOutDir, join(baseOutDir, output));\n return assertWithinBase(baseOutDir, join(baseOutDir, output, relDir, defaultName));\n }\n return assertWithinBase(baseOutDir, join(baseOutDir, relDir, defaultName));\n}\n\nexport function computeContractOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n return computeOpOutPath(filePath, baseDir, output, defaultSuffix, commonRoot, meta);\n}\n\n// ─── SDK output paths ──────────────────────────────────────────────────────\n\nexport function computeSdkOutPath(\n filePath: string,\n rootDir: string,\n clientOutput: string | undefined,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.client.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return assertWithinBase(baseOutDir, join(baseOutDir, resolved));\n return assertWithinBase(baseOutDir, join(baseOutDir, resolved, defaultOutName));\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput));\n return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput, relDir, defaultOutName));\n }\n return assertWithinBase(baseOutDir, join(baseOutDir, relDir, defaultOutName));\n}\n\n/**\n * Resolve the output path for a synthesized `<area>.client.ts` — the file holding the\n * `<Area>Client` class that aggregates an area's inlined methods and subarea wiring.\n *\n * Uses the same `output.clients` template as leaf clients, with `{filename}` and `{area}`\n * substituted to the area name and `{subarea}` substituted to the empty string. Resulting\n * double-slashes from the empty substitution are collapsed, and a final segment that\n * would otherwise begin with a dot (e.g. `.client.ts` from `{subarea}.client.ts`) is\n * prefixed with the area so the file isn't hidden.\n */\nexport function computeSdkAreaClientOutPath(area: string, rootDir: string, clientOutput: string | undefined): string {\n const filename = area;\n const baseOutDir = resolve(rootDir);\n const fixHiddenSegment = (path: string): string => {\n const segments = path.split('/');\n const last = segments[segments.length - 1] ?? '';\n if (last.startsWith('.')) segments[segments.length - 1] = `${filename}${last}`;\n return segments.join('/');\n };\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: '', ext: 'ck', area, subarea: '' });\n const cleaned = fixHiddenSegment(resolved.replace(/\\/+/g, '/').replace(/^\\//, ''));\n if (includesFilename(cleaned)) return assertWithinBase(baseOutDir, join(baseOutDir, cleaned));\n return assertWithinBase(baseOutDir, join(baseOutDir, cleaned, `${filename}.client.ts`));\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput));\n return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput, `${filename}.client.ts`));\n }\n return assertWithinBase(baseOutDir, join(baseOutDir, `${filename}.client.ts`));\n}\n\nexport function computeSdkTypeOutPath(\n filePath: string,\n rootDir: string,\n typeOutput: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (TEMPLATE_VAR_RE.test(typeOutput)) {\n const resolved = resolveTemplate(typeOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return assertWithinBase(baseOutDir, join(baseOutDir, resolved));\n return assertWithinBase(baseOutDir, join(baseOutDir, resolved, defaultOutName));\n }\n if (includesFilename(typeOutput)) return assertWithinBase(baseOutDir, join(baseOutDir, typeOutput));\n return assertWithinBase(baseOutDir, join(baseOutDir, typeOutput, relDir, defaultOutName));\n}\n\nexport function generateBarrelFiles(contractPaths: string[]): { outPath: string; content: string }[] {\n const byDir = new Map<string, string[]>();\n for (const outPath of contractPaths) {\n const dir = dirname(outPath);\n const group = byDir.get(dir) ?? [];\n group.push(outPath);\n byDir.set(dir, group);\n }\n const results: { outPath: string; content: string }[] = [];\n for (const [dir, files] of byDir) {\n const exports = files\n .map(f => `export * from './${f.split('/').pop()!.replace(/\\.ts$/, '.js')}';`)\n .sort()\n .join('\\n');\n results.push({ outPath: join(dir, 'index.ts'), content: `// Auto-generated barrel file\\n${exports}\\n` });\n }\n return results;\n}\n\nexport function computePubliclyReachableTypes(\n opAsts: OpRootNode[],\n contractAsts: ContractRootNode[],\n modelsWithInput: Set<string>,\n modelsWithOutput: Set<string> = new Set(),\n): Set<string> | null {\n if (opAsts.length === 0) return null;\n const reachable = new Set<string>();\n for (const opAst of opAsts) {\n for (const name of collectPublicTypeNames(opAst, modelsWithInput, modelsWithOutput)) reachable.add(name);\n }\n const modelDeps = new Map<string, Set<string>>();\n for (const contractAst of contractAsts) {\n for (const model of contractAst.models) {\n const deps = new Set<string>();\n if (model.bases) for (const b of model.bases) deps.add(b);\n if (model.type) collectTypeRefs(model.type, deps);\n for (const field of model.fields) collectTypeRefs(field.type, deps);\n modelDeps.set(model.name, deps);\n }\n }\n const frontier = [...reachable];\n while (frontier.length > 0) {\n const name = frontier.pop()!;\n const baseName = name.endsWith('Input') ? name.slice(0, -5) : name.endsWith('Output') ? name.slice(0, -6) : name;\n for (const dep of modelDeps.get(baseName) ?? []) {\n if (!reachable.has(dep)) {\n reachable.add(dep);\n frontier.push(dep);\n }\n if (modelsWithInput.has(dep)) {\n const inputDep = `${dep}Input`;\n if (!reachable.has(inputDep)) {\n reachable.add(inputDep);\n frontier.push(inputDep);\n }\n }\n if (modelsWithOutput.has(dep)) {\n const outputDep = `${dep}Output`;\n if (!reachable.has(outputDep)) {\n reachable.add(outputDep);\n frontier.push(outputDep);\n }\n }\n }\n }\n return reachable;\n}\n"],"mappings":";;;;AAAA,SAASA,WAAAA,UAASC,QAAAA,OAAMC,YAAAA,WAAUC,WAAAA,UAASC,YAAAA,iBAAgB;AAC3D,SAASC,YAAYC,cAAcC,eAAeC,WAA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Ae;MAAEqQ,WAAW;IAAK,CAAA;AACnDC,kBAActQ,cAAcuQ,6BAA6B9N,QAAAA,GAAW,OAAA;EACxE,QAAQ;EAER;AACJ;AAPSD;AAST,SAASlB,iBAAiBkP,UAAkB;AACxC,MAAIA,SAAS/E,WAAW,EAAG;AAC3B,QAAMgF,cAAc,oBAAI3R,IAAAA;AACxB,aAAW4R,OAAOF,UAAU;AACxB,QAAInP,WAAWqP,GAAAA,GAAM;AACjBC,aAAOD,KAAK;QAAEE,OAAO;MAAK,CAAA;AAC1BH,kBAAYzO,IAAI4G,SAAQ8H,GAAAA,CAAAA;IAC5B;EACJ;AAEA,aAAWG,OAAOJ,aAAa;AAC3B,QAAIK,UAAUD;AACd,WAAOC,QAAQrF,SAAS,GAAG;AACvB,UAAI;AACA,YAAIsF,YAAYD,OAAAA,EAASrF,WAAW,GAAG;AACnCuF,oBAAUF,OAAAA;AACVA,oBAAUlI,SAAQkI,OAAAA;QACtB,OAAO;AACH;QACJ;MACJ,QAAQ;AACJ;MACJ;IACJ;EACJ;AACJ;AAzBSxP;AA4BT,SAASsF,gBAAgBtH,QAAe;AACpC,SAAO2R,KAAKC,UAAU5R,UAAU,IAAA;AACpC;AAFSsH;","names":["resolve","join","relative","dirname","basename","existsSync","readFileSync","writeFileSync","mkdirSync","rmSync","readdirSync","rmdirSync","relative","dirname","collectTypeRefs","computeModelsWithOutput","ckComputeModelsWithOutput","collectExternalOutputRefs","ckCollectExternalOutputRefs","dirname","relative","JSON_VALUE_TYPE_DECL","quoteKey","name","test","escapeJsDocLines","text","replace","split","escapeSingleQuoted","s","sourceLink","label","outPath","sourceFile","line","rel","relative","dirname","href","startsWith","undefined","headerNameToProperty","parts","filter","Boolean","map","p","i","lower","toLowerCase","charAt","toUpperCase","slice","join","renderTsType","type","target","kind","renderTsScalar","inner","item","needsParens","items","key","value","values","v","String","members","m","renderTsInlineObject","fields","_exhaustive","Error","entries","f","opt","optional","renderInputTsType","modelsWithInput","size","has","renderOutputTsType","modelsWithOutput","DECIMAL_IMPORT","DECIMAL_CONFIG_LINE","DECIMAL_ZOD_SCHEMA_LINE","DECIMAL_PRELUDE_LINES","COERCE_DECLS","DECIMAL_COERCE_DECL","coerceDeclsFor","lines","haystack","join","Object","entries","filter","prefix","includes","flatMap","decl","coerceLuxonImports","needed","Set","add","sort","reviveFnName","model","variant","applyCase","name","caseTransform","replace","c","toLowerCase","charAt","toUpperCase","slice","DEFAULT_REVIVABLE_SCALARS","typeReachesDecimal","type","opts","kind","revivableScalars","has","modelsWithDecimal","item","inner","items","some","t","value","members","fields","f","scalarCoercion","slot","path","format","Scope","n","next","emit","scope","reviveRefName","arr","i","map","l","idx","rec","k","relevant","length","obj","body","fieldStatements","undefined","m","real","target","find","branches","disc","member","tag","discriminatorTag","discriminator","push","JSON","stringify","modelMap","get","field","values","objVar","outputCase","key","optional","nullable","modelsWithOutput","renderInlineReviver","fnName","tsType","renderReviveFunctions","renderOne","typeName","modeToWrapper","mode","computeModelsWithInput","models","externalModelsWithInput","Set","result","model","fields","some","f","visibility","add","name","changed","has","refs","field","collectTypeRefs","type","bases","b","ref","generateComments","outPath","lines","push","deprecated","description","l","escapeJsDocLines","sourceLink","loc","file","line","generateContract","root","context","needsDateTime","rootNeedsDateTime","needsDuration","rootNeedsScalar","needsInterval","needsBinary","needsDatetime","needsJson","needsDecimal","externalRefs","collectExternalRefs","modelsWithInput","localModelsWithInput","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","ckComputeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","ckCollectExternalOutputRefs","allExternalRefs","sort","luxonImports","length","join","DECIMAL_IMPORT","importPath","resolveImportPath","names","emitRevivers","modelsWithDecimal","reviveFnName","target","DECIMAL_PRELUDE_LINES","modelMap","Map","map","m","reviveOpts","undefined","bodyLines","topoSortModels","generateModel","currentOutPath","revivers","renderReviveFunctions","coerceDecls","coerceDeclsFor","flattenFormatChain","firstBase","parent","get","flatParent","parentHasFormat","inputCase","outputCase","merged","set","values","generateTypeAlias","effective","needsInputSplit","generateThreeSchemaModel","generateSimpleModel","renderType","renderInputType","wrapper","hasInputTransform","hasOutputTransform","inputBody","renderFieldsAsSnakeCase","renderFieldsAsPascalCase","renderFields","inputKey","applyCase","outputKey","optional","guard","quoteKey","typeSource","body","head","tail","slice","buildExtendChain","resolveName","collectEffectiveWritableFieldNames","modelName","base","delete","allFields","readFields","filter","readBody","writeFields","writeBody","renderInputFields","fieldsToOmit","omitClause","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","caseTransform","defaultMode","flatMap","renderField","pascalKey","expr","default","nullable","dv","escapeString","String","snakeKey","applyFieldModifiers","parseCaseTransform","kind","renderScalar","renderArray","renderTuple","renderRecord","renderEnum","renderLiteral","renderUnion","renderDiscriminatedUnion","renderIntersection","inner","renderInlineObject","renderRegexLiteral","source","regexHasAnchor","startsWith","endsWith","i","backslashes","NUMERIC_PREPROCESS","e","min","max","len","regex","checks","scale","messageParts","fmt","format","validParts","validation","message","_exhaustive","Error","a","item","t","items","r","key","value","vals","v","u","members","discriminator","first","rest","every","member","fieldLines","o","snakeLines","joined","transformEntries","pascalLines","renderInputScalar","renderInputField","renderQueryType","renderQueryField","isValidIdentifier","test","typeNeedsDateTime","typeNeedsScalar","localNames","collectInputTypeRefs","out","forEach","deps","localDeps","inDegree","d","dep","remaining","queue","sorted","shift","other","rem","includes","refName","refOutPath","modelOutPaths","fromDir","dirname","rel","relative","moduleName","pascalToDotCase","resolveModifiers","resolveSecurity","SECURITY_NONE","classifyContentType","emittedResponses","PATH_PARAM_RE_G","toIdentifier","basename","dirname","relative","bodyParserToken","contentType","classifyContentType","bodyTypesStructurallyEqual","a","b","kind","bb","name","min","max","len","scale","regex","format","item","items","length","every","x","i","key","value","values","v","members","m","discriminator","lazy","inner","mode","fields","f","g","optional","nullable","visibility","default","deprecated","type","generateOp","root","options","types","collectTypes","modelsWithInput","modelsWithOutput","services","collectServices","routerName","deriveRouterName","file","lines","push","sourceLink","basename","outPath","includeInternal","route","routes","op","operations","resolveModifiers","includes","generateHandler","handlerBody","join","references","symbol","RegExp","test","helpers","DECIMAL_PRELUDE_LINES","needsZodJson","generated","uses","body","koaImports","filter","svc","modulePath","meta","deriveModulePath","servicePathTemplate","usedTypes","generateTypeImports","luxonImports","DECIMAL_IMPORT","allContent","needsZod","desc","description","l","escapeJsDocLines","loc","line","effectiveSecurity","resolveSecurity","SECURITY_NONE","mods","method","path","replace","PATH_PARAM_RE_G","_m","toIdentifier","bodies","request","hasBody","isSingleMultipart","middlewares","policy","args","undefined","parserTokens","Array","from","Set","map","tokensExpr","t","signature","sigArgs","signaturePolicy","escapeSingleQuoted","middlewareStr","generateParamValidation","params","paramsMode","query","queryMode","headers","headersMode","renderInputType","bodyType","annotation","emitted","emittedResponses","serviceParts","inferService","call","methodName","buildArgs","generateMultiStatusResult","className","generateSingleStatusResult","resp","respHeaders","hasRespHeaders","headersAnnotation","renderHeadersAnnotation","bodySchema","prelude","formatTypeAnnotation","responseBodySchema","rendered","renderResponseMembers","includeStatus","varPrefix","preludes","statusCode","headerSetLines","responseBodyExpr","bodySchemas","Map","set","member","get","opts","leading","trailing","uniform","h","quoteKey","headerNameToProperty","renderOutputTsType","indent","accessor","JSON","stringify","service","cls","split","baseName","deriveBaseName","inferMethodName","hasParam","nodes","p","serverTsScalar","_exhaustive","Error","String","varName","has","schema","renderType","isRevalidatable","modelsWithTransform","rec","first","rest","usesExtendChain","preludeVar","validateResponses","source","ctxExpr","suffix","isQuery","typeName","isPathParams","bind","lhs","modeToWrapper","param","bound","isValidIdentifier","base","renderQueryType","applyFieldModifiers","node","opFile","modelOutPaths","byFile","unresolved","typeOutPath","group","fromDir","dirname","names","rel","relative","startsWith","sort","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","responses","collectOutputTypeNodeRefs","out","add","forEach","inferredService","pop","s","charAt","toUpperCase","slice","serviceName","template","kebab","toLowerCase","module","runIncrementalCodegen","parseIncrementalManifest","emptyIncrementalManifest","serializeIncrementalManifest","hashFingerprint","collectTransitiveModelRefs","computeModelsWithCaseTransform","computeModelsWithScalar","resolveModifiers","isJsonMime","classifyContentType","observableResponses","thrownResponses","PATH_PARAM_RE_G","toIdentifier","basename","dirname","relative","jsonOrFormSerialize","varName","contentType","renderSerializeExpr","bodies","ctVar","arms","slice","last","length","expr","i","arm","classifyBodyStrategy","op","request","kind","body","every","b","bodyTypesStructurallyEqual","bodyType","some","hasPublicOperations","root","includeInternal","route","routes","operations","resolveModifiers","includes","generateSdk","options","lines","types","collectTypes","modelsWithInput","modelsWithOutput","clientClassName","deriveClientClassName","file","inlineRevivers","Map","classBody","mods","push","generateMethod","inlineReviverDecls","values","flat","decimalPrelude","decimalPreludeFor","errorAliases","generateErrorBodyAliases","referenced","referencedTypes","generateTypeImports","usedRevivers","imports","headerLuxon","headerLuxonImport","sdkOptionsPath","outPath","rel","relative","dirname","replace","startsWith","jsonImport","sdkNeedsJson","valueImports","sdkNeedsBigIntReplacer","sdkParsesJsonResponse","sdkResponsesUseBigInt","sdkNeedsQueryString","sdkNeedsReadContentType","join","JSON_VALUE_TYPE_DECL","decls","decl","sourceLink","basename","generateClientMethods","methodNames","deriveMethodName","declLines","preludeLines","flatMap","needsDecimalImport","coerceDeclsFor","preamble","l","DECIMAL_IMPORT","DECIMAL_CONFIG_LINE","luxon","coerceLuxonImports","methodLines","existingImports","undefined","needed","filter","c","emitted","haystack","t","escaped","RegExp","test","found","Set","m","matchAll","add","sort","revive","modelsWithDecimal","size","modelMap","nameHint","methodName","where","method","toUpperCase","path","mRevive","hint","charAt","httpMethod","params","buildMethodParams","paramStr","map","p","name","optional","type","observable","observableResponses","thrown","thrownResponses","isMultiStatus","primaryResponse","primaryBodies","isVoid","respHeaders","headers","hasRespHeaders","headersShape","renderSdkHeadersShape","returnMembers","returnType","r","sdkResponseMembers","dataType","sdkDataType","expectStatuses","statusCode","desc","description","errorBodyName","errorBodyTypeName","deprecated","tags","contentLines","escapeJsDocLines","member","urlExpr","buildUrlExpression","hasQuery","query","fetchUrl","strategy","hasBody","hasOpHeaders","defaultCt","nonMultipart","find","fetchArgs","cat","classifyContentType","lastHeaderIdx","findIndex","a","existing","inner","needsResult","resultPrefix","split","fallback","rest","resp","sdkReturnLines","headerEntries","sdkHeaderEntries","sdkReadExpr","category","renderOutputTsType","tsType","read","reviver","reviveExprFor","segment","ctx","opts","revivableScalars","typeReachesDecimal","refName","pick","reviveFnName","has","direct","item","fnName","renderInlineReviver","set","fields","h","quoteKey","headerNameToProperty","sdkHeaderEntry","raw","key","scalar","convert","v","format","Error","describeHeaderType","includeStatus","leading","trailing","dataTypes","indent","cast","entries","first","fallbackFields","PATH_PARAM_RE_G","_m","toIdentifier","access","JSON","stringify","nodes","renderInputTsType","typeName","node","ctUnion","inlineArgParam","normaliseOptionalOrder","source","isOptional","Boolean","default","lastRequired","reduce","sdk","nameToMethodName","inferMethodName","parts","toLowerCase","segments","s","seg","paramName","segParts","sp","deriveBaseName","base","pop","deriveClientPropertyName","getAreaSubarea","area","meta","subarea","pascal","value","camel","deriveAreaClientClassName","deriveAreaPropertyName","deriveSubareaClientClassName","deriveSubareaPropertyName","publicOps","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","responses","collectOutputTypeNodeRefs","out","members","forEach","f","param","isJsonMime","tainted","modelsWithBigInt","reachesBigInt","items","typeNeedsScalar","check","src","opFile","revivers","modelOutPaths","byFile","unresolved","typeOutPath","get","group","fromDir","names","fromHere","reviverModelName","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","namesInModule","stem","template","module","generateSdkOptions","SCAFFOLD_DEP_VERSIONS","zod","decimalJs","typesLuxon","typescript","generateSdkPackageJson","input","dependencies","deps","decimal","devDependencies","pkg","version","main","exports","import","files","scripts","build","Object","keys","generateSdkTsconfig","tsconfig","compilerOptions","target","moduleResolution","declaration","outDir","rootDir","strict","esModuleInterop","skipLibCheck","forceConsistentCasingInFileNames","include","exclude","generateAreaClient","inlineFiles","subareaClients","className","collectedMethodLines","collectedRevivePrelude","areaNeedsDecimalImport","reviversByImportPath","collectedErrorAliases","seenMethods","typesByImportPath","unresolvedTypes","needsJson","needsBigIntReplacer","needsParseJson","needsBigIntReviver","needsQueryString","needsReadContentType","inline","codegenOptions","alias","modelOut","typesForFile","sdkOptionsRel","areaHeaderLuxon","importedClients","sc","client","importPath","propertyName","fetchModifier","ln","generateSdkAggregator","sdkOptionsImportPath","sdkClassName","pushClientImport","areas","topLevelClients","computeModelsWithOutput","collectExternalOutputRefs","generatePlainTypes","root","context","target","externalRefs","collectExternalRefs","lines","externalModelsWithInput","modelsWithInput","Set","localModelsWithInput","computeModelsWithInput","models","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","computeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","collectExternalOutputRefs","allExternalRefs","sort","needsDecimal","rootNeedsScalar","emitRevivers","modelsWithDecimal","some","m","has","name","push","DECIMAL_IMPORT","luxonImports","length","join","ref","importPath","resolveImportPath","reviveFnName","jsonValueImportPath","JSON_VALUE_TYPE_DECL","modelMap","Map","map","reviveOpts","undefined","bodyLines","model","topoSortModels","generateModel","currentOutPath","revivers","renderReviveFunctions","DECIMAL_CONFIG_LINE","coerceDecls","coerceDeclsFor","outPath","type","generateTypeAlias","needsInputSplit","fields","f","visibility","generateVisibilityModel","generateSimpleModel","generateOutputModel","collectInheritedFieldNames","bases","result","visit","get","add","b","computeOverrideNames","inherited","filter","override","generateComments","deprecated","description","l","escapeJsDocLines","sourceLink","loc","file","line","renderTsType","renderInputTsType","renderOutputTsType","buildExtendsClause","overrideNames","baseNameResolver","omitKeys","n","wrapped","field","renderField","readFields","writeFields","inputResolver","renderInputField","withFieldJsDoc","jsdocParts","contentLines","body","opt","optional","default","typeStr","nullable","quoteKey","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","slice","applyOutputCase","outputCase","baseExt","renderOutputField","key","resolveModifiers","emittedResponses","toIdentifier","basename","dirname","relative","mcpConfig","op","mcp","undefined","hasMcpOperations","root","includeInternal","route","routes","operations","resolveModifiers","includes","toSnake","s","replace","toLowerCase","toPascal","split","filter","Boolean","map","p","charAt","toUpperCase","slice","join","inferToolName","method","path","parts","seg","startsWith","push","deriveToolName","cfg","name","sdk","deriveToolClassName","toolName","buildArgsProps","modelsWithInput","props","params","kind","node","nodes","key","toIdentifier","expr","renderInputType","type","optional","refSchema","bodies","request","length","contentType","bodyType","query","paramSourceSchema","headers","has","src","fields","n","quoteKey","argsSchemaExpr","primaryResponseBody","resp","emittedResponses","outputSchemaExpr","body","renderType","HINT_KEYS","annotationsExpr","val","walkTypeRefs","ids","variant","add","item","items","forEach","t","value","members","f","inner","walkSourceRefs","collectSchemaIds","ops","Set","schemaImportLines","options","lines","modelOutPaths","outPath","size","byFile","Map","unresolved","id","get","group","set","fromDir","dirname","file","names","rel","relative","sort","pascalToDotCase","scalarHelperLines","DECIMAL_PRELUDE_LINES","planTools","plans","className","argsConstName","renderToolClass","plan","sourceLink","basename","loc","line","escapeSingleQuoted","title","desc","description","outExpr","annotations","service","inferService","destructure","callArgs","buildArgs","isVoid","structured","argsParam","methodName","deriveMcpRegisterFnName","deriveBaseName","generateMcpFile","argsConsts","classes","registerFn","bodyCore","helperConsts","bodyWithHelpers","needsParseAndValidate","some","imports","luxon","test","DECIMAL_IMPORT","serviceModules","svc","services","meta","deriveModulePath","servicePathTemplate","mod","entries","a","b","localeCompare","header","generateMcpAggregator","sorted","e","importPath","generateMcpRouter","resolve","join","relative","dirname","isAbsolute","collectTypeRefs","collectPublicTypeNames","TEMPLATE_VAR_RE","assertWithinBase","baseOutDir","outPath","rel","relative","resolve","startsWith","isAbsolute","Error","TEMPLATE_VAR_RE_G","resolveTemplate","template","vars","replace","_","key","includesFilename","p","last","split","pop","includes","commonDir","files","rootDir","length","parts","map","f","dirname","first","depth","i","slice","join","computeOpOutPath","filePath","baseDir","output","defaultSuffix","commonRoot","meta","baseName","relDir","filename","defaultName","test","resolved","dir","ext","computeContractOutPath","computeSdkOutPath","clientOutput","endsWith","defaultOutName","computeSdkAreaClientOutPath","area","fixHiddenSegment","path","segments","subarea","cleaned","computeSdkTypeOutPath","typeOutput","generateBarrelFiles","contractPaths","byDir","Map","group","get","push","set","results","exports","sort","content","computePubliclyReachableTypes","opAsts","contractAsts","modelsWithInput","modelsWithOutput","Set","reachable","opAst","name","collectPublicTypeNames","add","modelDeps","contractAst","model","models","deps","bases","b","type","collectTypeRefs","field","fields","frontier","dep","has","inputDep","outputDep","BIGINT_SCALARS","Set","TYPESCRIPT_CODEGEN_VERSION","CACHE_MANIFEST_FILENAME","plugin","name","generateTargets","inputs","ctx","config","options","runTypescriptCodegen","rootDir","createTypescriptPlugin","assertValidConfig","server","validateResponses","zod","Error","manifestPath","resolve","cacheDir","prevManifest","cacheEnabled","readManifest","emptyIncrementalManifest","units","globalFiles","collectServerOutput","sdk","collectSdkOutput","collectZodOutput","types","collectTypesOutput","mcp","collectMcpOutput","result","runIncrementalCodegen","codegenVersion","fileExists","existsSync","deleteStalePaths","deletedPaths","unresolved","relativePath","content","ifAbsent","filesToWrite","key","matchAll","TEMPLATE_VAR_RE_G","add","emitFile","undefined","entry","sort","outPath","split","warn","writeManifest","manifest","buildModelMap","contractRoots","map","Map","root","model","models","set","collectContractRootRefs","modelMap","seeds","m","type","push","f","fields","bases","b","kind","collectTransitiveModelRefs","collectOpRootRefs","route","routes","params","paramSourceTypes","op","operations","query","headers","request","body","bodies","bodyType","resp","responses","h","src","out","n","nodes","node","sliceOutPathMap","refs","modelOutPaths","modelsWithInput","modelsWithOutput","slice","ref","p","get","has","ip","sliceModelSet","ownNames","serverBase","baseDir","modelsWithTransform","computeModelsWithCaseTransform","flatMap","r","allFiles","file","opRoots","commonRoot","commonDir","subConfigKey","stableSubConfig","serverModelOutPaths","typeEntries","output","ast","typeOutPath","computeContractOutPath","meta","fingerprint","hashFingerprint","v","outPathSlice","sub","render","renderCtx","currentOutPath","target","generateContract","generatePlainTypes","computeOpOutPath","servicePathTemplate","includeInternal","generateOp","sdkBase","sdkName","sdkOutput","sdkEntryPath","join","TEMPLATE_VAR_RE","test","resolveTemplate","sdkOptionsPath","dirname","modelsWithDecimal","computeModelsWithScalar","DEFAULT_REVIVABLE_SCALARS","modelsWithBigInt","ckCommonRoot","sdkModelOutPaths","sdkTypePaths","sdkClientInfos","sdkContractEntries","publicTypes","computePubliclyReachableTypes","computeSdkTypeOutPath","some","emitRevivers","rel","relative","replace","startsWith","jsonValueImportPath","areaBuckets","topLevelEntries","clients","sdkOutPath","computeSdkOutPath","hasPublicOperations","area","subarea","getAreaSubarea","bucket","leaves","inlineRoots","entries","leaf","className","deriveSubareaClientClassName","propertyName","deriveSubareaPropertyName","generateSdk","typeImportPathTemplate","clientClassName","deriveClientClassName","deriveClientPropertyName","generateSdkOptions","hasAnything","length","size","areaClientOutPaths","sdkEntryDir","sdkOptionsRel","sdkOptionsImportPath","sdkClassName","s","charAt","toUpperCase","toClientImport","sourceDir","info","importPath","topLevelClients","e","areaInfos","sortedAreas","a","localeCompare","areaClientOutPath","computeSdkAreaClientOutPath","areaClassName","deriveAreaClientClassName","areaPropertyName","deriveAreaPropertyName","subareaClients","l","client","allInlineRefs","inlineFilesForGen","codegenOptions","generateAreaClient","inlineFiles","generateSdkAggregator","areas","sdkSrcDir","sdkTypeBarrels","generateBarrelFiles","barrel","rootExports","basename","c","scaffold","coveredRoots","deps","luxon","rootNeedsScalar","decimal","generateSdkPackageJson","generateSdkTsconfig","zodBase","typesBase","resolveMcpModelOutPaths","base","template","suffix","fullConfig","mcpBase","hasMcpOperations","tools","generateMcpFile","registerFn","deriveMcpRegisterFnName","indexPath","index","aggregatorEntries","generateMcpAggregator","emitRouter","routerPath","router","generateMcpRouter","path","parseIncrementalManifest","readFileSync","mkdirSync","recursive","writeFileSync","serializeIncrementalManifest","absPaths","removedDirs","abs","rmSync","force","dir","current","readdirSync","rmdirSync","JSON","stringify"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/codegen-contract.ts","../src/ts-render.ts","../src/decimal-runtime.ts","../src/codegen-revive.ts","../src/codegen-operation.ts","../src/server-framework-koa.ts","../src/codegen-sdk.ts","../src/codegen-plain-types.ts","../src/server-framework-fastify.ts","../src/server-framework.ts","../src/codegen-mcp.ts","../src/path-utils.ts"],"sourcesContent":["import { resolve, join, relative, dirname, basename } from 'node:path';\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, rmdirSync } from 'node:fs';\nimport { generateContract, rootNeedsScalar } from './codegen-contract.js';\nimport { generateOp } from './codegen-operation.js';\nimport type {\n ContractKitPlugin,\n PluginContext,\n ContractRootNode,\n OpRootNode,\n ModelNode,\n ScalarTypeNode,\n IncrementalManifest,\n IncrementalUnit,\n IncrementalOutputFile,\n} from '@contractkit/core';\nimport {\n runIncrementalCodegen,\n parseIncrementalManifest,\n emptyIncrementalManifest,\n serializeIncrementalManifest,\n hashFingerprint,\n collectTransitiveModelRefs,\n collectTypeRefs,\n computeModelsWithCaseTransform,\n computeModelsWithScalar,\n} from '@contractkit/core';\nimport {\n generateSdk,\n generateSdkOptions,\n generateSdkAggregator,\n generateAreaClient,\n deriveClientClassName,\n deriveClientPropertyName,\n deriveAreaClientClassName,\n deriveAreaPropertyName,\n deriveSubareaClientClassName,\n deriveSubareaPropertyName,\n getAreaSubarea,\n hasPublicOperations,\n generateSdkPackageJson,\n generateSdkTsconfig,\n type SdkClientInfo,\n type SdkAreaInfo,\n type SdkScaffoldDeps,\n} from './codegen-sdk.js';\nimport { generatePlainTypes } from './codegen-plain-types.js';\nimport { DEFAULT_REVIVABLE_SCALARS } from './codegen-revive.js';\nimport { resolveServerFramework, SERVER_FRAMEWORK_NAMES, type ServerFrameworkName } from './server-framework.js';\nexport {\n SERVER_FRAMEWORK_NAMES,\n DEFAULT_SERVER_FRAMEWORK_NAME,\n resolveServerFramework,\n SERVER_FRAMEWORKS,\n type ServerFramework,\n type ServerFrameworkName,\n} from './server-framework.js';\nexport { KOA_SERVER_FRAMEWORK } from './server-framework-koa.js';\nexport { FASTIFY_SERVER_FRAMEWORK } from './server-framework-fastify.js';\n\n/** Taint set for the SDK's bigint response reviver. */\nconst BIGINT_SCALARS: ReadonlySet<ScalarTypeNode['name']> = new Set(['bigint']);\nimport { generateMcpFile, generateMcpAggregator, generateMcpRouter, hasMcpOperations, deriveMcpRegisterFnName } from './codegen-mcp.js';\nimport {\n TEMPLATE_VAR_RE,\n TEMPLATE_VAR_RE_G,\n resolveTemplate,\n commonDir,\n computeOpOutPath,\n computeContractOutPath,\n computeSdkOutPath,\n computeSdkAreaClientOutPath,\n computeSdkTypeOutPath,\n generateBarrelFiles,\n computePubliclyReachableTypes,\n} from './path-utils.js';\n\n// ─── Sub-config interfaces ─────────────────────────────────────────────────\n\n/** Server output: routers, and the type or Zod schema files they import. */\nexport interface ServerConfig {\n /** Directory (relative to rootDir) where server files are written. Default: rootDir. */\n baseDir?: string;\n /**\n * HTTP framework the generated routers target. Also selects the flavour of the optional\n * `mcp.router.ts` the `mcp` sub-config emits. Supported: `'koa'`. Default `'koa'`.\n */\n framework?: ServerFrameworkName;\n /** When true, `output.types` emits Zod schema files (via `generateContract`). When false/omitted, emits plain TypeScript. */\n zod?: boolean;\n output?: {\n /** Path template for router files. Supports {filename}, {dir}, {area}. */\n routes?: string;\n /** Path template for type/schema files. Supports {filename}, {dir}, {area}. */\n types?: string;\n };\n /** Import path template for service implementations. */\n servicePathTemplate?: string;\n /** Whether to emit handlers for `internal` operations. Default true. */\n includeInternal?: boolean;\n /**\n * When true, each handler re-parses the service result through its declared response schema\n * before writing `ctx.body`, and writes the parsed value. Requires `zod: true` — without it\n * `output.types` emits plain interfaces, which are types with no runtime schema value.\n *\n * A body that transitively references a model with `format(input=...)`/`format(output=...)`, and\n * a status whose several mimes carry different body types, are left unvalidated. Default false.\n */\n validateResponses?: boolean;\n}\n\n/** TypeScript SDK client output: the client class, per-area operation clients, and their types. */\nexport interface SdkConfig {\n baseDir?: string;\n name?: string;\n zod?: boolean;\n output?: {\n sdk?: string;\n types?: string;\n clients?: string;\n };\n includeInternal?: boolean;\n /**\n * Emit a starter `package.json` and `tsconfig.json` at the SDK `baseDir` so the\n * generated output is a buildable, publishable package on its own. Opt-in and\n * write-once: the files are created only when absent and are never overwritten or\n * cleaned up on later builds, so any edits you make to them are preserved.\n * Dependency ranges are derived from the contracts (always `zod` when `zod: true`;\n * `luxon` when any covered model uses a date/time/datetime/duration/interval scalar;\n * `decimal.js` when any uses a decimal).\n */\n scaffold?: boolean;\n}\n\n/** Standalone Zod schema output, independent of the server and SDK sub-generators. */\nexport interface ZodConfig {\n baseDir?: string;\n output?: string;\n}\n\n/** Standalone plain TypeScript type output, independent of the server and SDK sub-generators. */\nexport interface TypesConfig {\n baseDir?: string;\n output?: string;\n /**\n * Runtime the emitted types describe. Affects scalars whose TypeScript type is runtime-specific:\n * `binary` renders as `Buffer` for `'server'` and `Blob` for `'client'`. Default `'client'`.\n * The `server` and `sdk` sub-generators set this themselves.\n */\n target?: 'client' | 'server';\n}\n\n/** MCP tool output: per-op-file handlers, the aggregator, and the optional POST route. */\nexport interface McpConfig {\n /** Directory (relative to rootDir) where MCP files are written. Default: rootDir. */\n baseDir?: string;\n output?: {\n /** Path template for per-op-file tool handlers. Supports {filename}, {dir}, {area}. Default `{filename}.mcp.ts`. */\n tools?: string;\n /** Path (or template) for the aggregator that assembles the McpToolHandlerMap. Default `mcp.tools.ts`. */\n index?: string;\n /** Path (or template) for the optional POST /mcp route file. Default `mcp.router.ts`. */\n router?: string;\n /**\n * Path template for the model **Zod schema** files the tools import (for arg validation and\n * `z.toJSONSchema`). When omitted, falls back to the `server` sub-config's `output.types`\n * (if `server.zod`) or the `zod` sub-config's output. Tools require Zod schemas, not plain types.\n */\n types?: string;\n };\n /** Emit the `mcp.router.ts` route boilerplate. Its framework follows `server.framework`. Default true. */\n emitRouter?: boolean;\n /** Mount path used in the emitted router. Default `/mcp`. */\n path?: string;\n /** Import path template for service implementations (same semantics as ServerConfig). */\n servicePathTemplate?: string;\n /** Whether to expose operations marked `internal` as MCP tools. Default false. */\n includeInternal?: boolean;\n}\n\n/** Top-level plugin config. Each sub-config that is present enables its sub-generator. */\nexport interface TypescriptPluginConfig {\n server?: ServerConfig;\n sdk?: SdkConfig;\n zod?: ZodConfig;\n types?: TypesConfig;\n mcp?: McpConfig;\n}\n\n// ─── Caching constants ─────────────────────────────────────────────────────\n\n/** Bumped when the codegen output shape changes in a way that should bust every per-file fingerprint. */\nexport const TYPESCRIPT_CODEGEN_VERSION = '2';\n\n// The taint set is `DEFAULT_REVIVABLE_SCALARS` rather than decimal alone, which is what makes a\n// temporal field a real Luxon object in an SDK client rather than a string wearing a `DateTime`\n// type. It also feeds every `hashFingerprint` that already slices this set, so a model gaining a\n// `datetime` in another `.ck` file invalidates this file's cached output with no extra plumbing.\n\n/** Filename for the persisted TypeScript manifest under the CLI cache directory. */\nconst CACHE_MANIFEST_FILENAME = 'typescript-manifest.json';\n\n// ─── Plugin entry points ──────────────────────────────────────────────────\n\nconst plugin: ContractKitPlugin = {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n const config = ctx.options as TypescriptPluginConfig;\n await runTypescriptCodegen(inputs, ctx, config, ctx.rootDir);\n },\n};\n\nexport default plugin;\n\n/** Build a `@contractkit/plugin-typescript` instance with explicit configuration, for programmatic use. */\nexport function createTypescriptPlugin(config: TypescriptPluginConfig, rootDir: string): ContractKitPlugin {\n return {\n name: 'typescript',\n async generateTargets(inputs, ctx) {\n await runTypescriptCodegen(inputs, ctx, config, rootDir);\n },\n };\n}\n\n/** Reject config combinations that would generate code that cannot compile or cannot run. */\nfunction assertValidConfig(config: TypescriptPluginConfig): void {\n // Runtime check, not just a type: config arrives as JSON, so `ServerFrameworkName` constrains\n // programmatic callers only. Checked before the rest so a typo'd framework is the error reported.\n const framework = config.server?.framework;\n if (framework !== undefined && !(SERVER_FRAMEWORK_NAMES as readonly string[]).includes(framework)) {\n throw new Error(\n `plugin-typescript: server.framework '${String(framework)}' is not supported — expected one of: ${SERVER_FRAMEWORK_NAMES.join(', ')}.`,\n );\n }\n if (config.server?.validateResponses && !config.server.zod) {\n throw new Error(\n 'plugin-typescript: server.validateResponses requires server.zod: true — without it output.types emits plain TypeScript interfaces, which are types with no runtime schema value for the router to validate against.',\n );\n }\n}\n\n/**\n * Shared orchestration. Each sub-generator (server / sdk / zod / types) contributes a\n * set of cacheable units (per-file fingerprints) plus a set of always-regenerated global\n * files (aggregators, barrels, sdk-options). Units share a single manifest so the cache\n * survives cross-cutting reads — the manifest lives at `<rootDir>/.contractkit-typescript-manifest.json`.\n *\n * Honors `ctx.cacheEnabled` — `--force` bypasses the manifest entirely.\n */\nasync function runTypescriptCodegen(\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n ctx: PluginContext,\n config: TypescriptPluginConfig,\n rootDir: string,\n): Promise<void> {\n assertValidConfig(config);\n const manifestPath = resolve(ctx.cacheDir, CACHE_MANIFEST_FILENAME);\n const prevManifest: IncrementalManifest = ctx.cacheEnabled ? readManifest(manifestPath) : emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n\n const units: IncrementalUnit[] = [];\n const globalFiles: IncrementalOutputFile[] = [];\n\n if (config.server) collectServerOutput(config.server, rootDir, inputs, units);\n if (config.sdk) collectSdkOutput(config.sdk, rootDir, inputs, units, globalFiles);\n if (config.zod) collectZodOutput(config.zod, rootDir, inputs, units);\n if (config.types) collectTypesOutput(config.types, rootDir, inputs, units);\n if (config.mcp) collectMcpOutput(config.mcp, config, rootDir, inputs, units, globalFiles);\n\n const result = runIncrementalCodegen({\n codegenVersion: TYPESCRIPT_CODEGEN_VERSION,\n prevManifest,\n globalFiles,\n units,\n // Paths are absolute, so existsSync works directly.\n fileExists: existsSync,\n });\n\n deleteStalePaths(result.deletedPaths);\n\n const unresolved = new Set<string>();\n for (const { relativePath, content, ifAbsent } of result.filesToWrite) {\n for (const [, key] of relativePath.matchAll(TEMPLATE_VAR_RE_G)) unresolved.add(`${key}::${relativePath}`);\n ctx.emitFile(relativePath, content, ifAbsent ? { ifAbsent: true } : undefined);\n }\n // `resolveTemplate` leaves an unknown `{key}` in place, which then joins straight into the\n // output path — producing a literal `{area}` directory rather than an error. `assertWithinBase`\n // does not catch it, since the path is inside the base, just wrong. Checked here rather than\n // threaded down through five path helpers: every output path passes through this one funnel,\n // whichever helper built it.\n for (const entry of [...unresolved].sort()) {\n const [key, outPath] = entry.split('::');\n ctx.warn?.(\n `Output path template variable {${key}} has no value, so '${outPath}' contains it literally. ` +\n `Declare it in the source file's 'options { keys { ${key}: ... } }' block, or remove it from the path template.`,\n );\n }\n\n writeManifest(manifestPath, result.manifest);\n}\n\n// ─── Cross-file dependency analysis ────────────────────────────────────────\n\n/** Build a quick lookup from model name → its definition. */\nfunction buildModelMap(contractRoots: readonly ContractRootNode[]): Map<string, ModelNode> {\n const map = new Map<string, ModelNode>();\n for (const root of contractRoots) {\n for (const model of root.models) map.set(model.name, model);\n }\n return map;\n}\n\n/** Collect every model referenced by this contract root (own models' fields + bases). Used to slice cross-file fingerprint inputs to just what this file actually depends on. */\nfunction collectContractRootRefs(root: ContractRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const m of root.models) {\n if (m.type) seeds.push(m.type);\n for (const f of m.fields) seeds.push(f.type);\n if (m.bases) {\n for (const b of m.bases) seeds.push({ kind: 'ref', name: b } as Parameters<typeof collectTypeRefs>[0]);\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\n/** Collect every model referenced by an op root's routes/operations (transitive). */\nfunction collectOpRootRefs(root: OpRootNode, modelMap: Map<string, ModelNode>): Set<string> {\n const seeds: Parameters<typeof collectTypeRefs>[0][] = [];\n for (const route of root.routes) {\n if (route.params) seeds.push(...paramSourceTypes(route.params));\n for (const op of route.operations) {\n if (op.query) seeds.push(...paramSourceTypes(op.query));\n if (op.headers) seeds.push(...paramSourceTypes(op.headers));\n if (op.request) {\n for (const body of op.request.bodies) seeds.push(body.bodyType);\n }\n for (const resp of op.responses) {\n for (const body of resp.bodies) seeds.push(body.bodyType);\n if (resp.headers) {\n for (const h of resp.headers) seeds.push(h.type);\n }\n }\n }\n }\n return collectTransitiveModelRefs(seeds, modelMap);\n}\n\nfunction paramSourceTypes(src: NonNullable<OpRootNode['routes'][number]['params']>): Parameters<typeof collectTypeRefs>[0][] {\n const out: Parameters<typeof collectTypeRefs>[0][] = [];\n if (src.kind === 'params') {\n for (const n of src.nodes) out.push(n.type);\n } else if (src.kind === 'ref') {\n out.push({ kind: 'ref', name: src.name } as Parameters<typeof collectTypeRefs>[0]);\n } else if (src.kind === 'type') {\n out.push(src.node);\n }\n return out;\n}\n\n/** Build a sorted, JSON-stable record of (modelName -> outPath) for refs this unit depends on. */\nfunction sliceOutPathMap(refs: Set<string>, modelOutPaths: Map<string, string>, modelsWithInput: Set<string>, modelsWithOutput: Set<string>): Record<string, string> {\n const slice: Record<string, string> = {};\n for (const ref of [...refs].sort()) {\n const p = modelOutPaths.get(ref);\n if (p) slice[ref] = p;\n if (modelsWithInput.has(ref)) {\n const ip = modelOutPaths.get(`${ref}Input`);\n if (ip) slice[`${ref}Input`] = ip;\n }\n if (modelsWithOutput.has(ref)) {\n const op = modelOutPaths.get(`${ref}Output`);\n if (op) slice[`${ref}Output`] = op;\n }\n }\n return slice;\n}\n\n/** Slice modelsWithInput/Output to only the names relevant to this unit. */\nfunction sliceModelSet(refs: Set<string>, ownNames: Set<string>, set: Set<string>): string[] {\n const result: string[] = [];\n for (const name of set) {\n if (refs.has(name) || ownNames.has(name)) result.push(name);\n }\n return result.sort();\n}\n\n// ─── Server sub-generator ──────────────────────────────────────────────────\n\nfunction collectServerOutput(\n config: ServerConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const serverBase = resolve(rootDir, config.baseDir ?? '.');\n const framework = resolveServerFramework(config.framework);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n // Not `modelsWithOutput`: that set seeds only from `format(output=...)`, because only that case\n // needs an `Output` type alias. A `format(input=...)`-only model is just as untouchable for\n // response validation — its schema's input casing is not what the service hands back.\n const modelsWithTransform = computeModelsWithCaseTransform(inputs.contractRoots.flatMap(r => r.models));\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const subConfigKey = stableSubConfig(config);\n\n // Pre-pass: register all model → outPath. Cross-file refs need to resolve correctly,\n // which means we need the COMPLETE map (not a slice) — even though each unit's fingerprint\n // only includes its own slice.\n const serverModelOutPaths = new Map<string, string>();\n const typeEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeContractOutPath(ast.file, serverBase, config.output.types, '.ts', commonRoot, ast.meta);\n typeEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n serverModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) serverModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) serverModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── Per-contract-root types unit ──\n for (const { ast, typeOutPath } of typeEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'server-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `server-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n const renderCtx = {\n modelOutPaths: serverModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n // These types are consumed by server handlers, so `binary` is a Buffer, not a Blob.\n target: 'server' as const,\n };\n const content = config.zod ? generateContract(ast, renderCtx) : generatePlainTypes(ast, renderCtx);\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Per-op-root router unit ──\n for (const ast of inputs.opRoots) {\n const outPath = computeOpOutPath(ast.file, serverBase, config.output?.routes, '.router.ts', commonRoot, ast.meta);\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'server-router',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n // The router imports types from each contract root's type file; the slice covers exactly that.\n outPathSlice: sliceOutPathMap(refs, serverModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n servicePathTemplate: config.servicePathTemplate ?? null,\n includeInternal: config.includeInternal ?? true,\n // Not covered by `sub`: adding `format(input=snake)` to a *different* .ck file changes\n // this router's output with no change to `root` or the config.\n modelsWithTransform: sliceModelSet(refs, new Set(), modelsWithTransform),\n validateResponses: config.validateResponses ?? false,\n // Covered by `sub` already, which is the whole sub-config; explicit for the same reason\n // `validateResponses` is — the inputs that change a router's text read at a glance.\n framework: framework.name,\n sub: subConfigKey,\n });\n units.push({\n key: `server-router::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateOp(ast, {\n servicePathTemplate: config.servicePathTemplate,\n outPath,\n modelOutPaths: serverModelOutPaths,\n modelsWithInput,\n modelsWithOutput,\n modelsWithTransform,\n includeInternal: config.includeInternal,\n validateResponses: config.validateResponses,\n framework,\n }),\n },\n ],\n });\n }\n}\n\n// ─── SDK sub-generator ─────────────────────────────────────────────────────\n\nfunction collectSdkOutput(\n config: SdkConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n globalFiles: IncrementalOutputFile[],\n): void {\n const sdkBase = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;\n const sdkName = config.name;\n const sdkOutput = config.output?.sdk;\n const sdkEntryPath = sdkOutput\n ? join(sdkBase, TEMPLATE_VAR_RE.test(sdkOutput) ? resolveTemplate(sdkOutput, { name: sdkName ?? 'sdk' }) : sdkOutput)\n : join(sdkBase, 'sdk.ts');\n const sdkOptionsPath = join(dirname(sdkEntryPath), 'sdk-options.ts');\n const subConfigKey = stableSubConfig(config);\n\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n // Computed across every contract root, not per file: one decimal below a model taints it, and\n // the reference that reaches it may live in another .ck file entirely.\n const modelsWithDecimal = computeModelsWithScalar(inputs.contractRoots.flatMap(r => r.models), DEFAULT_REVIVABLE_SCALARS);\n // Which response bodies need the `123n` reviver. Transitive, because a bigint reached through\n // a referenced model counts, and cross-file, because that model may live in another .ck file —\n // which is also why it is sliced into every fingerprint below, exactly as modelsWithDecimal is.\n const modelsWithBigInt = computeModelsWithScalar(inputs.contractRoots.flatMap(r => r.models), BIGINT_SCALARS);\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const ckCommonRoot = commonDir(allFiles, rootDir);\n\n const sdkModelOutPaths = new Map<string, string>();\n const sdkTypePaths: string[] = [];\n const sdkClientInfos: { outPath: string; className: string; propertyName: string }[] = [];\n\n // ── Pre-pass: SDK type files ──\n const sdkContractEntries: { ast: ContractRootNode; typeOutPath: string }[] = [];\n if (config.output?.types) {\n const publicTypes = computePubliclyReachableTypes(inputs.opRoots, inputs.contractRoots, modelsWithInput, modelsWithOutput);\n for (const ast of inputs.contractRoots) {\n const typeOutPath = computeSdkTypeOutPath(ast.file, sdkBase, config.output.types, ckCommonRoot, ast.meta);\n if (!typeOutPath) continue;\n if (publicTypes !== null && !ast.models.some(m => publicTypes.has(m.name))) continue;\n sdkTypePaths.push(typeOutPath);\n sdkContractEntries.push({ ast, typeOutPath });\n for (const model of ast.models) {\n sdkModelOutPaths.set(model.name, typeOutPath);\n if (modelsWithInput.has(model.name)) sdkModelOutPaths.set(`${model.name}Input`, typeOutPath);\n if (modelsWithOutput.has(model.name)) sdkModelOutPaths.set(`${model.name}Output`, typeOutPath);\n }\n }\n }\n\n // ── SDK type units ──\n for (const { ast, typeOutPath } of sdkContractEntries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'sdk-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: typeOutPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n // Not covered by `root`: adding a decimal to a model in a *different* .ck file changes\n // this file's revivers with no change to `root` or the config.\n modelsWithDecimal: sliceModelSet(refs, ownNames, modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(refs, ownNames, modelsWithBigInt),\n sdkOptionsPath,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-types::${typeOutPath}`,\n fingerprint,\n render: () => {\n let content: string;\n // `emitRevivers` is set for SDK type files only: a server handler receives decimals\n // already parsed by `_ZodDecimal`, so it has nothing to rehydrate.\n if (config.zod) {\n content = generateContract(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n emitRevivers: true,\n // An SDK client runs in a browser as readily as in Node, and its scaffold\n // declares no `@types/node`.\n target: 'client',\n });\n } else {\n let rel = relative(dirname(typeOutPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n content = generatePlainTypes(ast, {\n modelOutPaths: sdkModelOutPaths,\n currentOutPath: typeOutPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n emitRevivers: true,\n jsonValueImportPath: rel,\n });\n }\n return [{ relativePath: typeOutPath, content }];\n },\n });\n }\n\n // ── Bucket op roots by area/subarea ──\n interface AreaBucket {\n leaves: { ast: OpRootNode; outPath: string; subarea: string }[];\n inlineRoots: OpRootNode[];\n }\n const areaBuckets = new Map<string, AreaBucket>();\n const topLevelEntries: { ast: OpRootNode; outPath: string }[] = [];\n\n if (config.output?.clients) {\n for (const ast of inputs.opRoots) {\n const sdkOutPath = computeSdkOutPath(ast.file, sdkBase, config.output.clients, ckCommonRoot, ast.meta);\n if (!sdkOutPath || !hasPublicOperations(ast, config.includeInternal)) continue;\n const { area, subarea } = getAreaSubarea(ast);\n if (area && subarea) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.leaves.push({ ast, outPath: sdkOutPath, subarea });\n areaBuckets.set(area, bucket);\n } else if (area) {\n const bucket = areaBuckets.get(area) ?? { leaves: [], inlineRoots: [] };\n bucket.inlineRoots.push(ast);\n areaBuckets.set(area, bucket);\n } else {\n topLevelEntries.push({ ast, outPath: sdkOutPath });\n }\n }\n\n // ── Per-leaf-client (area+subarea) units ──\n for (const [area, bucket] of areaBuckets.entries()) {\n for (const leaf of bucket.leaves) {\n const className = deriveSubareaClientClassName(area, leaf.subarea);\n sdkClientInfos.push({ outPath: leaf.outPath, className, propertyName: deriveSubareaPropertyName(leaf.subarea) });\n const refs = collectOpRootRefs(leaf.ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-leaf-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: leaf.outPath,\n root: leaf.ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n modelsWithDecimal: sliceModelSet(refs, new Set(), modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(refs, new Set(), modelsWithBigInt),\n sdkOptionsPath,\n className,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-leaf-client::${leaf.outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: leaf.outPath,\n content: generateSdk(leaf.ast, {\n typeImportPathTemplate: undefined,\n outPath: leaf.outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n modelsWithBigInt,\n modelMap,\n includeInternal: config.includeInternal,\n clientClassName: className,\n }),\n },\n ],\n });\n }\n }\n\n // ── Top-level (no area) client units ──\n for (const { ast, outPath } of topLevelEntries) {\n const className = deriveClientClassName(ast.file);\n sdkClientInfos.push({ outPath, className, propertyName: deriveClientPropertyName(ast.file) });\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'sdk-top-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n modelsWithDecimal: sliceModelSet(refs, new Set(), modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(refs, new Set(), modelsWithBigInt),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n units.push({\n key: `sdk-top-client::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateSdk(ast, {\n typeImportPathTemplate: undefined,\n outPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n modelsWithBigInt,\n modelMap,\n includeInternal: config.includeInternal,\n }),\n },\n ],\n });\n }\n }\n\n // ── Global files: sdk-options, aggregator, barrels, root index ──\n // sdk-options.ts is a constant; the aggregator is small (just imports + a wrapper class)\n // and depends on the cross-cutting client list, so it's cheap to regenerate every run.\n // Per-area `<area>.client.ts` files are cached as their own units below.\n globalFiles.push({ relativePath: sdkOptionsPath, content: generateSdkOptions() });\n\n const hasAnything = sdkClientInfos.length > 0 || areaBuckets.size > 0;\n const areaClientOutPaths = new Map<string, string>(); // area → absolute outPath of <area>.client.ts\n if (hasAnything) {\n const sdkEntryDir = dirname(sdkEntryPath);\n const sdkOptionsRel = relative(sdkEntryDir, sdkOptionsPath).replace(/\\.ts$/, '.js');\n const sdkOptionsImportPath = sdkOptionsRel.startsWith('.') ? sdkOptionsRel : './' + sdkOptionsRel;\n const sdkClassName = sdkName\n ? sdkName\n .split(/[-._\\s]+/)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('') + 'Sdk'\n : 'Sdk';\n\n const toClientImport = (sourceDir: string, info: { outPath: string; className: string; propertyName: string }): SdkClientInfo => {\n let rel = relative(sourceDir, info.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n return { className: info.className, propertyName: info.propertyName, importPath: rel };\n };\n\n const topLevelClients: SdkClientInfo[] = topLevelEntries.map(e =>\n toClientImport(sdkEntryDir, {\n outPath: e.outPath,\n className: deriveClientClassName(e.ast.file),\n propertyName: deriveClientPropertyName(e.ast.file),\n }),\n );\n\n // ── Per-area `<area>.client.ts` units ──\n const areaInfos: SdkAreaInfo[] = [];\n const sortedAreas = [...areaBuckets.entries()].sort(([a], [b]) => a.localeCompare(b));\n for (const [area, bucket] of sortedAreas) {\n const areaClientOutPath = computeSdkAreaClientOutPath(area, sdkBase, config.output!.clients);\n areaClientOutPaths.set(area, areaClientOutPath);\n const areaClassName = deriveAreaClientClassName(area);\n const areaPropertyName = deriveAreaPropertyName(area);\n sdkClientInfos.push({ outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName });\n\n const subareaClients = bucket.leaves\n .sort((a, b) => a.subarea.localeCompare(b.subarea))\n .map(l => ({\n propertyName: deriveSubareaPropertyName(l.subarea),\n client: toClientImport(dirname(areaClientOutPath), {\n outPath: l.outPath,\n className: deriveSubareaClientClassName(area, l.subarea),\n propertyName: deriveSubareaPropertyName(l.subarea),\n }),\n }));\n\n // Fingerprint covers every input the area client depends on:\n // - all inline roots (full AST)\n // - subarea client metadata (className / propertyName / import path)\n // - the modelOutPaths slice for refs across all inline roots\n // - modelsWithInput/Output slices\n const allInlineRefs = new Set<string>();\n for (const r of bucket.inlineRoots) {\n for (const ref of collectOpRootRefs(r, modelMap)) allInlineRefs.add(ref);\n }\n const fingerprint = hashFingerprint({\n kind: 'sdk-area-client',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath: areaClientOutPath,\n area,\n inlineRoots: bucket.inlineRoots,\n subareaClients,\n outPathSlice: sliceOutPathMap(allInlineRefs, sdkModelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(allInlineRefs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(allInlineRefs, new Set(), modelsWithOutput),\n modelsWithDecimal: sliceModelSet(allInlineRefs, new Set(), modelsWithDecimal),\n modelsWithBigInt: sliceModelSet(allInlineRefs, new Set(), modelsWithBigInt),\n sdkOptionsPath,\n includeInternal: config.includeInternal ?? false,\n sub: subConfigKey,\n });\n\n const inlineFilesForGen = bucket.inlineRoots.map(root => ({\n root,\n codegenOptions: {\n typeImportPathTemplate: undefined,\n outPath: areaClientOutPath,\n modelOutPaths: sdkModelOutPaths,\n sdkOptionsPath,\n modelsWithInput,\n modelsWithOutput,\n modelsWithDecimal,\n modelsWithBigInt,\n modelMap,\n includeInternal: config.includeInternal,\n },\n }));\n\n units.push({\n key: `sdk-area-client::${areaClientOutPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: areaClientOutPath,\n content: generateAreaClient({\n area,\n outPath: areaClientOutPath,\n inlineFiles: inlineFilesForGen,\n subareaClients,\n sdkOptionsPath,\n }),\n },\n ],\n });\n\n areaInfos.push({\n area,\n client: toClientImport(sdkEntryDir, { outPath: areaClientOutPath, className: areaClassName, propertyName: areaPropertyName }),\n });\n }\n\n globalFiles.push({\n relativePath: sdkEntryPath,\n content: generateSdkAggregator({ topLevelClients, areas: areaInfos, sdkOptionsImportPath, sdkClassName }),\n });\n }\n\n const sdkSrcDir = dirname(sdkEntryPath);\n const sdkTypeBarrels = generateBarrelFiles(sdkTypePaths);\n for (const barrel of sdkTypeBarrels) globalFiles.push({ relativePath: barrel.outPath, content: barrel.content });\n\n const rootExports: string[] = [`export * from './${basename(sdkOptionsPath).replace(/\\.ts$/, '.js')}';`];\n if (hasAnything) rootExports.push(`export * from './${basename(sdkEntryPath).replace(/\\.ts$/, '.js')}';`);\n for (const c of sdkClientInfos) {\n let rel = relative(sdkSrcDir, c.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n for (const barrel of sdkTypeBarrels) {\n let rel = relative(sdkSrcDir, barrel.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n rootExports.push(`export * from '${rel}';`);\n }\n globalFiles.push({\n relativePath: join(sdkSrcDir, 'index.ts'),\n content: `// Auto-generated barrel file\\n${rootExports.sort().join('\\n')}\\n`,\n });\n\n // ── Scaffold files (opt-in, write-once) ──\n // Emitted at the SDK package root with `ifAbsent` so they're created once and\n // then owned by the user. Deps are derived from the contracts actually surfaced\n // into the SDK: zod when schema output is on, luxon when any covered model uses a\n // date/time/datetime/interval scalar.\n if (config.scaffold) {\n const coveredRoots = sdkContractEntries.map(e => e.ast);\n const deps: SdkScaffoldDeps = {\n zod: !!config.zod,\n // `duration` belongs here too: `generateContract` imports `Duration` from luxon for it,\n // so a contract whose only temporal scalar is a duration used to scaffold a package.json\n // with no luxon dependency and fail to compile.\n luxon: coveredRoots.some(r =>\n (['datetime', 'date', 'time', 'duration', 'interval'] as const).some(name => rootNeedsScalar(r, name)),\n ),\n decimal: coveredRoots.some(r => rootNeedsScalar(r, 'decimal')),\n };\n globalFiles.push({\n relativePath: join(sdkBase, 'package.json'),\n content: generateSdkPackageJson({ name: sdkName ?? 'sdk', deps }),\n ifAbsent: true,\n });\n globalFiles.push({\n relativePath: join(sdkBase, 'tsconfig.json'),\n content: generateSdkTsconfig(),\n ifAbsent: true,\n });\n }\n}\n\n// ─── Zod sub-generator ─────────────────────────────────────────────────────\n\nfunction collectZodOutput(\n config: ZodConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const zodBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, zodBase, config.output, '.schema.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'zod',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `zod::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n // Server-shaped, which is what this sub-generator has always emitted. The\n // standalone `zod:` output has no target option of its own; only the SDK's\n // schemas are client-shaped, and they pass their own target.\n content: generateContract(ast, { modelOutPaths, currentOutPath: outPath, modelsWithInput, modelsWithOutput, target: 'server' }),\n },\n ],\n });\n }\n}\n\n// ─── Plain types sub-generator ─────────────────────────────────────────────\n\nfunction collectTypesOutput(\n config: TypesConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n): void {\n const typesBase = resolve(rootDir, config.baseDir ?? '.');\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const subConfigKey = stableSubConfig(config);\n\n const modelOutPaths = new Map<string, string>();\n const entries: { ast: ContractRootNode; outPath: string }[] = [];\n for (const ast of inputs.contractRoots) {\n const outPath = computeContractOutPath(ast.file, typesBase, config.output, '.types.ts', commonRoot, ast.meta);\n entries.push({ ast, outPath });\n for (const model of ast.models) {\n modelOutPaths.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) modelOutPaths.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) modelOutPaths.set(`${model.name}Output`, outPath);\n }\n }\n\n for (const { ast, outPath } of entries) {\n const refs = collectContractRootRefs(ast, modelMap);\n const ownNames = new Set(ast.models.map(m => m.name));\n const fingerprint = hashFingerprint({\n kind: 'plain-types',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, ownNames, modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, ownNames, modelsWithOutput),\n sub: subConfigKey,\n });\n units.push({\n key: `plain-types::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generatePlainTypes(ast, {\n modelOutPaths,\n currentOutPath: outPath,\n modelsWithInput,\n modelsWithOutput,\n target: config.target,\n }),\n },\n ],\n });\n }\n}\n\n// ─── MCP sub-generator ─────────────────────────────────────────────────────\n\n/**\n * Resolve where the model **Zod schema** files live so the MCP tools can import them (for arg\n * validation + `z.toJSONSchema`). Precedence: explicit `mcp.output.types` → the `server` sub-config's\n * `output.types` (only when `server.zod`) → the `zod` sub-config's output. Returns an empty map when\n * none resolve (imports then fall back to a colocated `./<name>.js` guess).\n */\nfunction resolveMcpModelOutPaths(\n config: TypescriptPluginConfig,\n rootDir: string,\n contractRoots: readonly ContractRootNode[],\n commonRoot: string,\n modelsWithInput: Set<string>,\n modelsWithOutput: Set<string>,\n): Map<string, string> {\n const map = new Map<string, string>();\n let base: string;\n let template: string | undefined;\n let suffix: string;\n if (config.mcp?.output?.types) {\n base = resolve(rootDir, config.mcp.baseDir ?? '.');\n template = config.mcp.output.types;\n suffix = '.ts';\n } else if (config.server?.zod && config.server.output?.types) {\n base = resolve(rootDir, config.server.baseDir ?? '.');\n template = config.server.output.types;\n suffix = '.ts';\n } else if (config.zod) {\n base = resolve(rootDir, config.zod.baseDir ?? '.');\n template = config.zod.output;\n suffix = '.schema.ts';\n } else {\n return map;\n }\n\n for (const ast of contractRoots) {\n const outPath = computeContractOutPath(ast.file, base, template, suffix, commonRoot, ast.meta);\n for (const model of ast.models) {\n map.set(model.name, outPath);\n if (modelsWithInput.has(model.name)) map.set(`${model.name}Input`, outPath);\n if (modelsWithOutput.has(model.name)) map.set(`${model.name}Output`, outPath);\n }\n }\n return map;\n}\n\nfunction collectMcpOutput(\n config: McpConfig,\n fullConfig: TypescriptPluginConfig,\n rootDir: string,\n inputs: Parameters<NonNullable<ContractKitPlugin['generateTargets']>>[0],\n units: IncrementalUnit[],\n globalFiles: IncrementalOutputFile[],\n): void {\n const mcpBase = resolve(rootDir, config.baseDir ?? '.');\n const modelsWithInput = inputs.modelsWithInput as Set<string>;\n const modelsWithOutput = inputs.modelsWithOutput as Set<string>;\n const modelMap = buildModelMap(inputs.contractRoots);\n const allFiles = [...inputs.contractRoots.map(r => r.file), ...inputs.opRoots.map(r => r.file)];\n const commonRoot = commonDir(allFiles, rootDir);\n const subConfigKey = stableSubConfig(config);\n const includeInternal = config.includeInternal ?? false;\n\n const modelOutPaths = resolveMcpModelOutPaths(fullConfig, rootDir, inputs.contractRoots, commonRoot, modelsWithInput, modelsWithOutput);\n\n // ── Per-op-root tool-handler units (only files with MCP-exposed ops) ──\n const entries: { outPath: string; registerFn: string }[] = [];\n for (const ast of inputs.opRoots) {\n if (!hasMcpOperations(ast, includeInternal)) continue;\n const outPath = computeOpOutPath(ast.file, mcpBase, config.output?.tools, '.mcp.ts', commonRoot, ast.meta);\n const refs = collectOpRootRefs(ast, modelMap);\n const fingerprint = hashFingerprint({\n kind: 'mcp-tools',\n v: TYPESCRIPT_CODEGEN_VERSION,\n outPath,\n root: ast,\n outPathSlice: sliceOutPathMap(refs, modelOutPaths, modelsWithInput, modelsWithOutput),\n modelsWithInput: sliceModelSet(refs, new Set(), modelsWithInput),\n modelsWithOutput: sliceModelSet(refs, new Set(), modelsWithOutput),\n servicePathTemplate: config.servicePathTemplate ?? null,\n includeInternal,\n sub: subConfigKey,\n });\n units.push({\n key: `mcp-tools::${outPath}`,\n fingerprint,\n render: () => [\n {\n relativePath: outPath,\n content: generateMcpFile(ast, {\n outPath,\n modelOutPaths,\n modelsWithInput,\n modelsWithOutput,\n servicePathTemplate: config.servicePathTemplate,\n includeInternal,\n }),\n },\n ],\n });\n entries.push({ outPath, registerFn: deriveMcpRegisterFnName(ast.file) });\n }\n\n if (entries.length === 0) return;\n\n // ── Aggregator (global) ──\n const indexPath = join(mcpBase, config.output?.index ?? 'mcp.tools.ts');\n const aggregatorEntries = entries\n .map(e => {\n let rel = relative(dirname(indexPath), e.outPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n return { registerFn: e.registerFn, importPath: rel };\n })\n .sort((a, b) => a.registerFn.localeCompare(b.registerFn));\n globalFiles.push({ relativePath: indexPath, content: generateMcpAggregator(aggregatorEntries) });\n\n // ── Router (global, optional) ──\n if (config.emitRouter !== false) {\n const routerPath = join(mcpBase, config.output?.router ?? 'mcp.router.ts');\n // The mount is server-side wiring, so it follows the server sub-config's framework. Koa when\n // there is no `server` sub-config at all, which is the same default the router generator has.\n const framework = resolveServerFramework(fullConfig.server?.framework);\n globalFiles.push({ relativePath: routerPath, content: generateMcpRouter({ path: config.path, framework }) });\n }\n}\n\n// ─── Manifest IO + cleanup ─────────────────────────────────────────────────\n\nfunction readManifest(manifestPath: string): IncrementalManifest {\n if (!existsSync(manifestPath)) return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n try {\n return parseIncrementalManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return emptyIncrementalManifest(TYPESCRIPT_CODEGEN_VERSION);\n }\n}\n\n/** Write the manifest to `manifestPath`. Creates parent dirs as needed. Errors are swallowed so a broken cache never blocks the build. */\nfunction writeManifest(manifestPath: string, manifest: IncrementalManifest): void {\n try {\n mkdirSync(dirname(manifestPath), { recursive: true });\n writeFileSync(manifestPath, serializeIncrementalManifest(manifest), 'utf-8');\n } catch {\n // best-effort\n }\n}\n\nfunction deleteStalePaths(absPaths: string[]): void {\n if (absPaths.length === 0) return;\n const removedDirs = new Set<string>();\n for (const abs of absPaths) {\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(dirname(abs));\n }\n }\n // Walk up affected dirs and remove if empty. Bounded — stops at filesystem root or first non-empty dir.\n for (const dir of removedDirs) {\n let current = dir;\n while (current.length > 1) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = dirname(current);\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n\n/** Stringify a sub-config so it can participate in fingerprints. JSON.stringify gives stable output for typical config shapes. */\nfunction stableSubConfig(config: unknown): string {\n return JSON.stringify(config ?? null);\n}\n","import { relative, dirname } from 'node:path';\nimport type {\n ContractRootNode,\n ModelNode,\n FieldNode,\n ContractTypeNode,\n ScalarTypeNode,\n ArrayTypeNode,\n TupleTypeNode,\n RecordTypeNode,\n EnumTypeNode,\n LiteralTypeNode,\n UnionTypeNode,\n DiscriminatedUnionTypeNode,\n InlineObjectTypeNode,\n IntersectionTypeNode,\n ObjectMode,\n} from '@contractkit/core';\nimport {\n collectTypeRefs,\n computeModelsWithOutput as ckComputeModelsWithOutput,\n collectExternalOutputRefs as ckCollectExternalOutputRefs,\n} from '@contractkit/core';\nimport { escapeJsDocLines, sourceLink } from './ts-render.js';\nimport type { TsRenderTarget } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_PRELUDE_LINES } from './decimal-runtime.js';\nimport { renderReviveFunctions, reviveFnName, coerceDeclsFor } from './codegen-revive.js';\n\n/**\n * Maps a ContractKit object mode to its Zod constructor name.\n *\n * @returns `\"z.strictObject\"` | `\"z.object\"` | `\"z.looseObject\"`\n */\nexport function modeToWrapper(mode: ObjectMode): string {\n switch (mode) {\n case 'strict':\n return 'z.strictObject';\n case 'strip':\n return 'z.object';\n case 'loose':\n return 'z.looseObject';\n }\n}\n\n// ─── Cross-file import resolution ─────────────────────────────────────────\n\n/** Cross-file context passed to `generateContract` to wire up imports and Input/Output variant tracking. */\nexport interface ContractCodegenContext {\n /** Map from model name → absolute output file path */\n modelOutPaths: Map<string, string>;\n /** Absolute output file path for the current contract file */\n currentOutPath: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /** If set, import JsonValue from this path instead of re-declaring it (avoids barrel re-export conflicts) */\n jsonValueImportPath?: string;\n /**\n * Runtime the emitted types describe. Only affects scalars whose TypeScript type differs per\n * runtime: `binary` is a `Buffer` on a Node server and a `Blob` in a fetch client, and\n * `_ZodBinary` is generated to match. Default `'client'`.\n */\n target?: TsRenderTarget;\n /** Model names that carry a `decimal`, directly or transitively. */\n modelsWithDecimal?: Set<string>;\n /**\n * Emit `reviveX()` hydration functions alongside the schemas. Set only for SDK type files: a\n * server handler receives decimals already parsed by `_ZodDecimal`, so it has nothing to revive.\n */\n emitRevivers?: boolean;\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Compute which models need Input variants, including transitive dependencies.\n * A model needs an Input variant if it has visibility-modified fields, OR if\n * any of its field types (recursively) reference a model that has an Input variant.\n */\nexport function computeModelsWithInput(models: ModelNode[], externalModelsWithInput: Set<string> = new Set()): Set<string> {\n const result = new Set<string>();\n\n // Initial pass: direct visibility modifiers\n for (const model of models) {\n if (model.fields.some(f => f.visibility !== 'normal')) {\n result.add(model.name);\n }\n }\n\n // Transitive closure: add models that reference models with Input variants,\n // including through base model inheritance.\n let changed = true;\n while (changed) {\n changed = false;\n for (const model of models) {\n if (result.has(model.name)) continue;\n const refs = new Set<string>();\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // A model that extends a parent with Input variants also needs an Input variant,\n // so that the write schema can extend ParentInput instead of Parent.\n if (model.bases) for (const b of model.bases) refs.add(b);\n // A type alias (model.type set) that references a model with Input variants\n // also needs an Input variant.\n if (model.type) collectTypeRefs(model.type, refs);\n for (const ref of refs) {\n if (result.has(ref) || externalModelsWithInput.has(ref)) {\n result.add(model.name);\n changed = true;\n break;\n }\n }\n }\n }\n\n return result;\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n for (const l of escapeJsDocLines(model.description)) lines.push(` * ${l}`);\n }\n\n lines.push(` * generated from ${sourceLink(model.name, outPath, model.loc.file, model.loc.line)}`);\n lines.push('*/');\n return lines;\n}\n\n/**\n * Generate a TypeScript module containing Zod schemas for every model in `root`.\n *\n * Emits two schemas per model when visibility modifiers are present: `Model` (read — no\n * writeonly fields) and `ModelInput` (write — no readonly fields). Writeonly inheritance rides\n * on the Input chain, since a child's `Input` extends its parent's `Input`, which already carries\n * the parent's writeonly fields.\n *\n * @param root - The parsed contract root node.\n * @param context - Optional cross-file context for import resolution and Input/Output variant tracking.\n * @returns The full TypeScript source as a string.\n */\nexport function generateContract(root: ContractRootNode, context?: ContractCodegenContext): string {\n const needsDateTime = rootNeedsDateTime(root);\n const needsDuration = rootNeedsScalar(root, 'duration');\n const needsInterval = rootNeedsScalar(root, 'interval');\n const needsBinary = rootNeedsScalar(root, 'binary');\n const needsDatetime = rootNeedsScalar(root, 'datetime');\n const needsJson = rootNeedsScalar(root, 'json');\n const needsDecimal = rootNeedsScalar(root, 'decimal');\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = ckComputeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input refs needed for Input schema fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? ckCollectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n lines.push(`import { z } from 'zod';`);\n const luxonImports: string[] = [];\n if (needsDateTime) luxonImports.push('DateTime');\n if (needsDuration) luxonImports.push('Duration');\n if (needsInterval) luxonImports.push('Interval');\n if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n if (needsDecimal) lines.push(DECIMAL_IMPORT);\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n // A cross-file model that carries a decimal contributes its reviver too — the local\n // reviver calls it rather than re-deriving the other file's shape.\n const names =\n context?.emitRevivers && context.modelsWithDecimal?.has(ref) ? `${ref}, ${reviveFnName(ref)}` : ref;\n lines.push(`import { ${names} } from '${importPath}';`);\n }\n lines.push('');\n if (needsBinary) {\n // The one scalar with no single correct runtime type, so it follows `target` here exactly\n // as `renderTsScalar` does. An SDK type file reaching this through the shared\n // `generateContract` used to emit `Buffer.isBuffer` into a browser client, whose scaffold\n // declares no `@types/node` — the type did not resolve and the check could not run.\n lines.push(\n context?.target === 'server'\n ? `const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`\n : `const _ZodBinary = z.custom<Blob>((val) => val instanceof Blob, { error: 'Must be binary data' });`,\n );\n }\n if (needsDatetime) {\n lines.push(\n `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' }));`,\n );\n }\n if (needsInterval) {\n lines.push(\n `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()!);`,\n );\n }\n if (needsDecimal) {\n lines.push(...DECIMAL_PRELUDE_LINES);\n }\n if (needsJson) {\n lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n lines.push(\n `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)]));`,\n );\n }\n if (needsBinary || needsDatetime || needsInterval || needsDecimal || needsJson) lines.push('');\n\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n\n const reviveOpts =\n context?.emitRevivers && context.modelsWithDecimal\n ? { modelsWithDecimal: context.modelsWithDecimal, modelsWithOutput: allModelsWithOutput, modelMap }\n : undefined;\n\n const bodyLines: string[] = [];\n for (const model of topoSortModels(root.models)) {\n bodyLines.push(...generateModel(model, context?.currentOutPath, allModelsWithInput, modelMap, allModelsWithOutput));\n if (reviveOpts) {\n const revivers = renderReviveFunctions(model, reviveOpts);\n if (revivers.length > 0) {\n bodyLines.push('');\n bodyLines.push(...revivers);\n }\n }\n bodyLines.push('');\n }\n\n // Decided from the emitted revivers rather than from a predicate over the AST, so the\n // declarations and their uses cannot drift apart and leave an unused local behind.\n const coerceDecls = coerceDeclsFor(bodyLines);\n if (coerceDecls.length > 0) {\n lines.push(...coerceDecls);\n lines.push('');\n }\n lines.push(...bodyLines);\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\n/**\n * If any ancestor in the base chain has a format(input=)/format(output=) transform,\n * the parent schema compiles to a `ZodPipe` (object().transform()) which has no `.extend()`.\n * To keep extension working, inline the parent's fields into the child and inherit format/mode\n * so the child re-applies the transform on the merged shape. Returns the model unchanged when\n * no ancestor has format, preserving the existing `.extend()`-based output.\n */\nfunction flattenFormatChain(model: ModelNode, modelMap: Map<string, ModelNode>): ModelNode {\n if (!model.bases || model.bases.length === 0) return model;\n // TODO(multi-base): currently only the first base is followed for format inheritance.\n // Multi-base format flattening will need a topological merge across all bases.\n const firstBase = model.bases[0]!;\n const parent = modelMap.get(firstBase);\n if (!parent) return model;\n const flatParent = flattenFormatChain(parent, modelMap);\n const parentHasFormat =\n (flatParent.inputCase !== undefined && flatParent.inputCase !== 'camel') ||\n (flatParent.outputCase !== undefined && flatParent.outputCase !== 'camel');\n if (!parentHasFormat) return model;\n\n const merged = new Map<string, FieldNode>();\n for (const f of flatParent.fields) merged.set(f.name, f);\n for (const f of model.fields) merged.set(f.name, f);\n\n return {\n ...model,\n bases: undefined,\n fields: [...merged.values()],\n inputCase: model.inputCase ?? flatParent.inputCase,\n outputCase: model.outputCase ?? flatParent.outputCase,\n mode: model.mode ?? flatParent.mode,\n };\n}\n\nfunction generateModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n modelsWithOutput?: Set<string>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, outPath, modelsWithInput, modelsWithOutput);\n }\n\n const effective = modelMap ? flattenFormatChain(model, modelMap) : model;\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = effective.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(effective.name) ?? false);\n\n const lines = needsInputSplit\n ? generateThreeSchemaModel(effective, outPath, modelsWithInput, modelMap)\n : generateSimpleModel(effective, outPath);\n\n // Emit Output type alias when this model (transitively) has format(output=...)\n if (modelsWithOutput?.has(effective.name)) {\n lines.push(`export type ${effective.name}Output = z.output<typeof ${effective.name}>;`);\n }\n\n return lines;\n}\n\nfunction generateTypeAlias(model: ModelNode, outPath?: string, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export const ${model.name} = ${renderType(model.type!)};`);\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export const ${model.name}Input = ${renderInputType(model.type!, modelsWithInput)};`);\n lines.push(`export type ${model.name}Input = z.infer<typeof ${model.name}Input>;`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = z.output<typeof ${model.name}>;`);\n }\n return lines;\n}\n\nfunction generateSimpleModel(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const { inputCase, outputCase } = model;\n const hasInputTransform = !!inputCase && inputCase !== 'camel';\n const hasOutputTransform = !!outputCase && outputCase !== 'camel';\n\n if (hasInputTransform || hasOutputTransform) {\n const inputBody =\n inputCase === 'snake'\n ? renderFieldsAsSnakeCase(model.fields, model.mode)\n : inputCase === 'pascal'\n ? renderFieldsAsPascalCase(model.fields, model.mode)\n : renderFields(model.fields, model.mode);\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...inputBody.map(l => ` ${l}`));\n lines.push(`}).transform(data => ({`);\n for (const field of model.fields) {\n const inputKey = applyCase(field.name, inputCase);\n const outputKey = applyCase(field.name, outputCase);\n if (field.optional) {\n // Conditional spread keeps the field optional (`k?: T`) in the inferred\n // z.output / z.input type, instead of widening to required-nullable (`k: T | undefined`).\n // Consumer code built with `...(x ? { k: x } : {})` is only assignable to the optional form.\n // When inputCase is set, the input schema uses `.nullish()` so the guard must reject both\n // null and undefined; otherwise `.optional()` only allows undefined.\n const guard = hasInputTransform ? `data.${inputKey} != null` : `data.${inputKey} !== undefined`;\n lines.push(` ...(${guard} ? { ${quoteKey(outputKey)}: data.${inputKey} } : {}),`);\n } else {\n lines.push(` ${quoteKey(outputKey)}: data.${inputKey},`);\n }\n }\n lines.push(`}));`);\n // When only outputCase is set, the developer-facing type is the schema's\n // pre-transform shape (camelCase). With inputCase, the post-transform\n // shape is what consumers work with.\n const typeSource = hasOutputTransform && !hasInputTransform ? 'input' : 'output';\n lines.push(`export type ${model.name} = z.${typeSource}<typeof ${model.name}>;`);\n return lines;\n }\n\n const body = renderFields(model.fields, model.mode);\n const bases = model.bases ?? [];\n if (bases.length > 0) {\n const head = bases[0]!;\n const tail = bases\n .slice(1)\n .map(b => `.extend(${b}.shape)`)\n .join('');\n lines.push(`export const ${model.name} = ${head}${tail}.extend({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n } else {\n lines.push(`export const ${model.name} = ${wrapper}({`);\n lines.push(...body.map(l => ` ${l}`));\n lines.push(`});`);\n }\n\n lines.push(`export type ${model.name} = z.infer<typeof ${model.name}>;`);\n return lines;\n}\n\n/** Builds a Zod extension chain \"Head.extend(B.shape).extend(C.shape)...\" for a list of base names,\n * applying a per-base name resolver (e.g. choosing \"BaseInput\" for bases that have an Input variant). */\nfunction buildExtendChain(bases: string[], resolveName: (b: string) => string): { head: string; tail: string } {\n const head = resolveName(bases[0]!);\n const tail = bases\n .slice(1)\n .map(b => `.extend(${resolveName(b)}.shape)`)\n .join('');\n return { head, tail };\n}\n\nfunction collectEffectiveWritableFieldNames(modelName: string, modelMap: Map<string, ModelNode>): Set<string> {\n const model = modelMap.get(modelName);\n if (!model || model.type) return new Set();\n const result = new Set<string>();\n for (const base of model.bases ?? []) {\n for (const f of collectEffectiveWritableFieldNames(base, modelMap)) result.add(f);\n }\n for (const field of model.fields) {\n if (field.visibility === 'readonly') result.delete(field.name);\n else result.add(field.name);\n }\n return result;\n}\n\nfunction generateThreeSchemaModel(\n model: ModelNode,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n const lines: string[] = [];\n const name = model.name;\n\n lines.push(...generateComments(model, outPath));\n\n const wrapper = modeToWrapper(model.mode ?? 'strict');\n\n const allFields = model.fields;\n\n const bases = model.bases ?? [];\n\n // Read schema — omit writeonly fields; extends parent read schema\n const readFields = allFields.filter(f => f.visibility !== 'writeonly');\n const readBody = renderFields(readFields, model.mode);\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => b);\n lines.push(`export const ${name} = ${head}${tail}.extend({`);\n } else {\n lines.push(`export const ${name} = ${wrapper}({`);\n }\n lines.push(...readBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name} = z.infer<typeof ${name}>;`);\n lines.push('');\n\n // Write schema — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read schema\n const writeFields = allFields.filter(f => f.visibility !== 'readonly');\n const writeBody = modelsWithInput ? renderInputFields(writeFields, modelsWithInput, model.mode) : renderFields(writeFields, model.mode);\n // Fields that become readonly in this model but were writable in a base must be omitted from\n // the base Input schema — Zod's .extend() cannot remove inherited fields.\n const fieldsToOmit = new Set<string>();\n if (bases.length > 0 && modelMap) {\n for (const field of allFields) {\n if (field.visibility === 'readonly') {\n for (const base of bases) {\n if (collectEffectiveWritableFieldNames(base, modelMap).has(field.name)) {\n fieldsToOmit.add(field.name);\n break;\n }\n }\n }\n }\n }\n const omitClause =\n fieldsToOmit.size > 0\n ? `.omit({ ${[...fieldsToOmit].map(f => `${quoteKey(f)}: true`).join(', ')} })`\n : '';\n if (bases.length > 0) {\n const { head, tail } = buildExtendChain(bases, b => (modelsWithInput?.has(b) ? `${b}Input` : b));\n lines.push(`export const ${name}Input = ${head}${tail}${omitClause}.extend({`);\n } else {\n lines.push(`export const ${name}Input = ${wrapper}({`);\n }\n lines.push(...writeBody.map(l => ` ${l}`));\n lines.push(`});`);\n lines.push(`export type ${name}Input = z.infer<typeof ${name}Input>;`);\n\n return lines;\n}\n\n// ─── Fields ────────────────────────────────────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!caseTransform || caseTransform === 'camel') return name;\n if (caseTransform === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\nfunction renderFields(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderField(f, defaultMode));\n}\n\nfunction renderFieldsAsPascalCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const pascalKey = camelToPascal(f.name);\n let expr = renderType(f.type, 'pascal', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(pascalKey)}: ${expr},`;\n });\n}\n\nfunction renderFieldsAsSnakeCase(fields: FieldNode[], defaultMode?: ObjectMode): string[] {\n return fields.map(f => {\n const snakeKey = camelToSnake(f.name);\n let expr = renderType(f.type, 'snake', defaultMode);\n if (f.default !== undefined) {\n if (f.nullable) expr += '.nullable()';\n const dv = typeof f.default === 'string' ? `\"${escapeString(f.default)}\"` : String(f.default);\n expr += `.default(${dv})`;\n } else if (f.optional) {\n // .nullish() accepts null or undefined from the API; the transform coerces null → undefined\n expr += '.nullish()';\n } else if (f.nullable) {\n expr += '.nullable()';\n }\n if (f.description) expr += `.describe(\"${escapeString(f.description)}\")`;\n return `${quoteKey(snakeKey)}: ${expr},`;\n });\n}\n\n/**\n * Append the modifier chain a declared field carries: nullability, then a default or optionality,\n * then the description.\n *\n * Takes a structural subset of `FieldNode` rather than the node itself, so an `OpParamNode` — which\n * is a `FieldNode` minus `visibility`, `deprecated` and `override` — can be rendered through the\n * same path. That is what lets the router, the SDK and OpenAPI agree on what an inline `query:` or\n * `headers:` field means.\n *\n * A default and `optional` are mutually exclusive on purpose: `.default()` already makes the input\n * side optional, and adding `.optional()` on top would widen the *output* type to include\n * `undefined`, which is exactly what a default exists to prevent.\n */\nexport function applyFieldModifiers(expr: string, field: Pick<FieldNode, 'nullable' | 'default' | 'optional' | 'description'>): string {\n if (field.nullable) expr += '.nullable()';\n if (field.default !== undefined) {\n const dv = typeof field.default === 'string' ? `\"${escapeString(field.default)}\"` : String(field.default);\n expr += `.default(${dv})`;\n } else if (field.optional) {\n expr += '.optional()';\n }\n if (field.description) expr += `.describe(\"${escapeString(field.description)}\")`;\n return expr;\n}\n\nfunction renderField(field: FieldNode, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderType(field.type, undefined, defaultMode);\n\n expr = applyFieldModifiers(expr, field);\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\n// ─── Type rendering ────────────────────────────────────────────────────────\n\n/**\n * Render a ContractKit AST type node as a Zod schema expression string.\n *\n * @param parseCaseTransform - When set, generates a `.transform()` that remaps incoming keys from\n * the given casing (`'snake'` | `'pascal'`) to camelCase for `inlineObject` types.\n * @param defaultMode - Fallback object mode (`'strict'` | `'strip'` | `'loose'`) when the node\n * doesn't specify its own mode.\n */\nexport function renderType(type: ContractTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderScalar(type);\n case 'array':\n return renderArray(type, parseCaseTransform, defaultMode);\n case 'tuple':\n return renderTuple(type);\n case 'record':\n return renderRecord(type);\n case 'enum':\n return renderEnum(type);\n case 'literal':\n return renderLiteral(type);\n case 'union':\n return renderUnion(type, parseCaseTransform, defaultMode);\n case 'discriminatedUnion':\n return renderDiscriminatedUnion(type, parseCaseTransform, defaultMode);\n case 'intersection':\n return renderIntersection(type, parseCaseTransform, defaultMode);\n case 'ref':\n return type.name;\n case 'lazy':\n return `z.lazy(() => ${renderType(type.inner, parseCaseTransform, defaultMode)})`;\n case 'inlineObject':\n return renderInlineObject(type, parseCaseTransform, defaultMode);\n default:\n return 'z.unknown()';\n }\n}\n\n/**\n * Render a regex source as a JS regex literal for `.regex(...)`. If the source already has\n * anchors (`^` at the start and/or an unescaped `$` at the end) we trust the user's intent\n * and emit it as-is; otherwise we wrap with `^...$` so contracts default to full-match\n * semantics. Forward slashes are always escaped since `/` is the literal delimiter.\n */\nfunction renderRegexLiteral(source: string): string {\n const body = source.replace(/\\//g, '\\\\/');\n if (regexHasAnchor(source)) return `/${body}/`;\n return `/^${body}$/`;\n}\n\nfunction regexHasAnchor(source: string): boolean {\n if (source.startsWith('^')) return true;\n if (!source.endsWith('$')) return false;\n // The trailing `$` is an anchor only if it isn't escaped — count immediately preceding\n // backslashes; an even count (including zero) means `$` is unescaped.\n let i = source.length - 2;\n let backslashes = 0;\n while (i >= 0 && source[i] === '\\\\') {\n backslashes++;\n i--;\n }\n return backslashes % 2 === 0;\n}\n\n/**\n * Coercion for the numeric scalars: convert a non-empty string, pass everything else through for\n * `z.number()` to judge.\n *\n * `z.coerce.number()` is `Number(v)`, which accepts far more than a number. `[]` and `''` become\n * `0`, `null` becomes `0`, `true` becomes `1` — so `{\"quantity\": []}` validated as `0` and the\n * handler ran on a value the client never sent. Only the string case is a real coercion; it exists\n * because query strings and headers arrive as text, and it stays because a JSON body carrying\n * `\"42\"` is common enough that rejecting it would break working callers.\n *\n * The `boolean` scalar below already has this shape and needed no change: its preprocess maps only\n * the two literal strings and hands everything else to `z.boolean()`, which rejects it.\n */\nconst NUMERIC_PREPROCESS = `(v) => (typeof v === 'string' && v.trim() !== '' ? Number(v) : v)`;\n\nfunction renderScalar(s: ScalarTypeNode): string {\n switch (s.name) {\n case 'string': {\n let e = 'z.string()';\n if (s.min !== undefined && s.max !== undefined) e += `.min(${s.min}).max(${s.max})`;\n else if (s.min !== undefined) e += `.min(${s.min})`;\n else if (s.max !== undefined) e += `.max(${s.max})`;\n if (s.len !== undefined) e += `.length(${s.len})`;\n if (s.regex) e += `.regex(${renderRegexLiteral(s.regex)})`;\n return e;\n }\n case 'number':\n case 'int': {\n // Constraints go on the inner schema, not the outer expression: `z.preprocess` returns\n // a ZodPipe, which has no `.min()`. Same shape as the `bigint` case below.\n let inner = s.name === 'int' ? 'z.number().int()' : 'z.number()';\n if (s.min !== undefined) inner += `.min(${s.min})`;\n if (s.max !== undefined) inner += `.max(${s.max})`;\n return `z.preprocess(${NUMERIC_PREPROCESS}, ${inner})`;\n }\n case 'bigint': {\n let inner = 'z.bigint()';\n if (s.min !== undefined) inner += `.min(${s.min}n)`;\n if (s.max !== undefined) inner += `.max(${s.max}n)`;\n return `z.preprocess((val) => typeof val === 'string' ? BigInt(val.replace(/n$/, '')) : val, ${inner})`;\n }\n case 'decimal': {\n // Deliberately no output `.transform()`: `isRevalidatable` in codegen-operation treats\n // every scalar as idempotent under re-parse, which `server.validateResponses` relies on.\n // Preprocess passes an already-`Decimal` value straight through, so parse(parse(x)) is\n // stable. Modelling this on `_ZodInterval` — which does transform — would break that.\n const checks: string[] = [];\n if (s.scale !== undefined) checks.push(`v.decimalPlaces() <= ${s.scale}`);\n if (s.min !== undefined) checks.push(`v.gte('${escapeString(String(s.min))}')`);\n if (s.max !== undefined) checks.push(`v.lte('${escapeString(String(s.max))}')`);\n if (checks.length === 0) return '_ZodDecimal';\n const messageParts: string[] = [];\n if (s.scale !== undefined) messageParts.push(`at most ${s.scale} decimal place${s.scale === 1 ? '' : 's'}`);\n if (s.min !== undefined) messageParts.push(`at least ${s.min}`);\n if (s.max !== undefined) messageParts.push(`at most ${s.max}`);\n return `_ZodDecimal.refine((v) => ${checks.join(' && ')}, { message: 'Must be ${escapeString(messageParts.join(', '))}' })`;\n }\n case 'boolean':\n return `z.preprocess((v) => v === 'true' ? true : v === 'false' ? false : v, z.boolean())`;\n case 'date': {\n const fmt = s.format ?? 'yyyy-MM-dd';\n 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)}' }))`;\n }\n case 'time': {\n const fmt = s.format ?? 'HH:mm:ss';\n 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)}' }))`;\n }\n case 'datetime':\n return '_ZodDatetime';\n case 'interval':\n return '_ZodInterval';\n case 'duration': {\n const validParts = [`val instanceof Duration && val.isValid`];\n if (s.min !== undefined) validParts.push(`val.toMillis() >= Duration.fromISO('${s.min}').toMillis()`);\n if (s.max !== undefined) validParts.push(`val.toMillis() <= Duration.fromISO('${s.max}').toMillis()`);\n const validation = validParts.join(' && ');\n let message = 'Must be an ISO 8601 duration';\n if (s.min !== undefined && s.max !== undefined) message += ` between ${s.min} and ${s.max}`;\n else if (s.min !== undefined) message += ` of at least ${s.min}`;\n else if (s.max !== undefined) message += ` of at most ${s.max}`;\n return `z.preprocess((val) => typeof val === 'string' ? Duration.fromISO(val) : val, z.custom<Duration>((val) => ${validation}, { message: '${message}' }))`;\n }\n case 'email':\n return 'z.email()';\n case 'url':\n return 'z.url()';\n case 'uuid':\n return 'z.uuid()';\n case 'unknown':\n return 'z.unknown()';\n case 'null':\n return 'z.null()';\n case 'object':\n return 'z.record(z.string(), z.unknown())';\n case 'binary':\n return '_ZodBinary';\n case 'json':\n return '_ZodJson';\n default: {\n const _exhaustive: never = s.name;\n throw new Error(`plugin-typescript: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\nfunction renderArray(a: ArrayTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n let e = `z.array(${renderType(a.item, parseCaseTransform, defaultMode)})`;\n if (a.min !== undefined) e += `.min(${a.min})`;\n if (a.max !== undefined) e += `.max(${a.max})`;\n return e;\n}\n\nfunction renderTuple(t: TupleTypeNode): string {\n return `z.tuple([${t.items.map(i => renderType(i)).join(', ')}])`;\n}\n\nfunction renderRecord(r: RecordTypeNode): string {\n return `z.record(${renderType(r.key)}, ${renderType(r.value)})`;\n}\n\nfunction renderEnum(e: EnumTypeNode): string {\n const vals = e.values.map(v => `\"${escapeString(v)}\"`).join(', ');\n return `z.enum([${vals}])`;\n}\n\nfunction renderLiteral(l: LiteralTypeNode): string {\n if (typeof l.value === 'string') return `z.literal(\"${escapeString(l.value)}\")`;\n return `z.literal(${l.value})`;\n}\n\nfunction renderUnion(u: UnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.union([${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderDiscriminatedUnion(u: DiscriminatedUnionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n return `z.discriminatedUnion(\"${escapeString(u.discriminator)}\", [${u.members.map(m => renderType(m, parseCaseTransform, defaultMode)).join(', ')}])`;\n}\n\nfunction renderIntersection(i: IntersectionTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const [first, ...rest] = i.members;\n // When the pattern is ref & (ref | inlineObject)*, use .extend() chains to\n // produce a single ZodObject. .and() breaks strict objects — each strict side\n // rejects the other side's keys during intersection parsing, and ZodIntersection\n // has no .strict() method.\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n expr += `.extend(${member.name}.shape)`;\n } else {\n const m = member as InlineObjectTypeNode;\n const fieldLines =\n parseCaseTransform === 'snake'\n ? renderFieldsAsSnakeCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : parseCaseTransform === 'pascal'\n ? renderFieldsAsPascalCase(m.fields, defaultMode)\n .map(l => ` ${l}`)\n .join('\\n')\n : m.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderType(first!, parseCaseTransform, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderType(member, parseCaseTransform, defaultMode)})`;\n }\n return expr;\n}\n\nfunction renderInlineObject(o: InlineObjectTypeNode, parseCaseTransform?: 'snake' | 'pascal', defaultMode?: ObjectMode): string {\n const wrapper = modeToWrapper(o.mode ?? defaultMode ?? 'strict');\n if (parseCaseTransform === 'snake') {\n const snakeLines = renderFieldsAsSnakeCase(o.fields, defaultMode);\n const joined = snakeLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const snakeKey = camelToSnake(f.name);\n // Optional fields use .nullish() on input. Conditional spread (instead of `?? undefined`)\n // keeps the key optional in the inferred output type (`k?: T`) rather than widening to\n // required-nullable (`k: T | undefined`).\n if (f.optional) {\n return ` ...(data.${snakeKey} != null ? { ${quoteKey(f.name)}: data.${snakeKey} } : {}),`;\n }\n return ` ${quoteKey(f.name)}: data.${snakeKey},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n if (parseCaseTransform === 'pascal') {\n const pascalLines = renderFieldsAsPascalCase(o.fields, defaultMode);\n const joined = pascalLines.map(l => ` ${l}`).join('\\n');\n const transformEntries = o.fields\n .map(f => {\n const pascalKey = camelToPascal(f.name);\n if (f.optional) {\n return ` ...(data.${pascalKey} != null ? { ${quoteKey(f.name)}: data.${pascalKey} } : {}),`;\n }\n return ` ${quoteKey(f.name)}: data.${pascalKey},`;\n })\n .join('\\n');\n return `${wrapper}({\\n${joined}\\n}).transform(data => ({\\n${transformEntries}\\n}))`;\n }\n const fields = o.fields\n .flatMap(f => renderField(f, defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${wrapper}({\\n${fields}\\n})`;\n}\n\n// ─── Input type rendering ─────────────────────────────────────────────────\n\n/**\n * The request-side rendering of a scalar. A pure passthrough today, and the seam where a genuine\n * input/wire split would live.\n *\n * The docstring here used to claim it \"coerces from string input\", describing a distinction the\n * body does not make: `XInput` is a single exported `const`, and `generateParamValidation`'s ref\n * branch uses that same schema for `query: X` that the body path uses for\n * `request: { application/json: X }`. Making it strict would break query-by-model; leaving it\n * coercing leaves a JSON body accepting string-shaped numbers. A real split needs a second emitted\n * variant (`XInputWire`) plus the import plumbing to reach it, which is separate work — the\n * narrowed coercion in `renderScalar` closes the soundness hole in the meantime.\n */\nfunction renderInputScalar(s: ScalarTypeNode): string {\n return renderScalar(s);\n}\n\n/**\n * Like renderType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers, and coerces scalars from strings.\n * Used for Input (write) schema fields so that sub-type references also\n * point to their Input variants.\n */\nexport function renderInputType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'scalar':\n return renderInputScalar(type);\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n let e = `z.array(${renderInputType(type.item, modelsWithInput, defaultMode)})`;\n if (type.min !== undefined) e += `.min(${type.min})`;\n if (type.max !== undefined) e += `.max(${type.max})`;\n return e;\n }\n case 'tuple':\n return `z.tuple([${type.items.map(i => renderInputType(i, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'record':\n return `z.record(${renderInputType(type.key, modelsWithInput, defaultMode)}, ${renderInputType(type.value, modelsWithInput, defaultMode)})`;\n case 'union':\n return `z.union([${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'discriminatedUnion':\n return `z.discriminatedUnion(\"${escapeString(type.discriminator)}\", [${type.members.map(m => renderInputType(m, modelsWithInput, defaultMode)).join(', ')}])`;\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderInputField(f, modelsWithInput ?? new Set(), defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderInputType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderInputType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'lazy':\n return `z.lazy(() => ${renderInputType(type.inner, modelsWithInput, defaultMode)})`;\n case 'inlineObject': {\n const fields = type.fields\n .flatMap(f => renderInputField(f, modelsWithInput ?? new Set(), defaultMode))\n .map(l => ` ${l}`)\n .join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n default:\n return renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n const lines: string[] = [];\n if (field.deprecated) lines.push('/** @deprecated */');\n\n let expr = renderInputType(field.type, modelsWithInput, defaultMode);\n\n expr = applyFieldModifiers(expr, field);\n\n lines.push(`${quoteKey(field.name)}: ${expr},`);\n return lines;\n}\n\nfunction renderInputFields(fields: FieldNode[], modelsWithInput: Set<string>, defaultMode?: ObjectMode): string[] {\n return fields.flatMap(f => renderInputField(f, modelsWithInput, defaultMode));\n}\n\n// ─── Query type rendering ─────────────────────────────────────────────────\n\n/**\n * Like renderType, but wraps array types with z.preprocess to handle\n * query strings where a single value arrives as a string instead of a string[].\n * Also uses Input variants for model refs when modelsWithInput is provided.\n */\nexport function renderQueryType(type: ContractTypeNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n switch (type.kind) {\n case 'array': {\n const inner = modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n return `z.preprocess((v) => typeof v === 'string' ? v.split(',') : v, ${inner})`;\n }\n case 'inlineObject': {\n const fields = type.fields.map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`).join('\\n');\n return `${modeToWrapper(type.mode ?? defaultMode ?? 'strict')}({\\n${fields}\\n})`;\n }\n case 'intersection': {\n const [first, ...rest] = type.members;\n if (first && first.kind === 'ref' && rest.length > 0 && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject')) {\n let expr = modelsWithInput?.has(first.name) ? `${first.name}Input` : first.name;\n for (const member of rest) {\n if (member.kind === 'ref') {\n const name = modelsWithInput?.has(member.name) ? `${member.name}Input` : member.name;\n expr += `.extend(${name}.shape)`;\n } else {\n const fieldLines = (member as InlineObjectTypeNode).fields\n .map(f => ` ${renderQueryField(f, modelsWithInput, defaultMode)}`)\n .join('\\n');\n expr += `.extend({\\n${fieldLines}\\n})`;\n }\n }\n return expr;\n }\n let expr = renderQueryType(first!, modelsWithInput, defaultMode);\n for (const member of rest) {\n expr += `.and(${renderQueryType(member, modelsWithInput, defaultMode)})`;\n }\n return expr;\n }\n case 'ref':\n return modelsWithInput?.has(type.name) ? `${type.name}Input` : type.name;\n default:\n return modelsWithInput ? renderInputType(type, modelsWithInput, defaultMode) : renderType(type, undefined, defaultMode);\n }\n}\n\nfunction renderQueryField(field: FieldNode, modelsWithInput?: Set<string>, defaultMode?: ObjectMode): string {\n let expr =\n field.type.kind === 'array'\n ? renderQueryType(field.type, modelsWithInput, defaultMode)\n : modelsWithInput\n ? renderInputType(field.type, modelsWithInput, defaultMode)\n : renderType(field.type, undefined, defaultMode);\n\n expr = applyFieldModifiers(expr, field);\n\n return `${quoteKey(field.name)}: ${expr},`;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\nfunction quoteKey(name: string): string {\n return isValidIdentifier(name) ? name : `'${name}'`;\n}\n\n// ─── String escaping ──────────────────────────────────────────────────────\n\nfunction escapeString(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r');\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction rootNeedsDateTime(root: ContractRootNode): boolean {\n return root.models.some(m => (m.type && typeNeedsDateTime(m.type)) || m.fields.some(f => typeNeedsDateTime(f.type)));\n}\n\n/** Returns true if `type` (recursively) contains a scalar with the given `name`. */\nexport function typeNeedsScalar(type: ContractTypeNode, name: string): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === name;\n case 'array':\n return typeNeedsScalar(type.item, name);\n case 'tuple':\n return type.items.some(i => typeNeedsScalar(i, name));\n case 'record':\n return typeNeedsScalar(type.key, name) || typeNeedsScalar(type.value, name);\n case 'union':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'discriminatedUnion':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'intersection':\n return type.members.some(m => typeNeedsScalar(m, name));\n case 'lazy':\n return typeNeedsScalar(type.inner, name);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsScalar(f.type, name));\n default:\n return false;\n }\n}\n\n/** Returns true if any model in `root` uses a scalar with the given `name`. */\nexport function rootNeedsScalar(root: ContractRootNode, name: string): boolean {\n return root.models.some(m => (m.type && typeNeedsScalar(m.type, name)) || m.fields.some(f => typeNeedsScalar(f.type, name)));\n}\n\n/** Returns true if `type` (recursively) contains a `date`, `time`, or `datetime` scalar. */\nexport function typeNeedsDateTime(type: ContractTypeNode): boolean {\n switch (type.kind) {\n case 'scalar':\n return type.name === 'date' || type.name === 'time' || type.name === 'datetime';\n case 'array':\n return typeNeedsDateTime(type.item);\n case 'union':\n return type.members.some(typeNeedsDateTime);\n case 'discriminatedUnion':\n return type.members.some(typeNeedsDateTime);\n case 'intersection':\n return type.members.some(typeNeedsDateTime);\n case 'inlineObject':\n return type.fields.some(f => typeNeedsDateTime(f.type));\n default:\n return false;\n }\n}\n\n/** Collect model names referenced in `root` that are not defined locally (need to be imported). */\nexport function collectExternalRefs(root: ContractRootNode): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (model.bases?.[0] && !localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n }\n\n for (const name of localNames) refs.delete(name);\n return [...refs].sort();\n}\n\n/** Collect external Input variant refs needed for Input schema fields. */\nexport function collectExternalInputRefs(root: ContractRootNode, modelsWithInput: Set<string>): string[] {\n const localNames = new Set(root.models.map(m => m.name));\n const refs = new Set<string>();\n\n for (const model of root.models) {\n if (!modelsWithInput.has(model.name)) continue;\n // Type alias: collect Input refs from the aliased type expression.\n if (model.type) {\n collectInputTypeRefs(model.type, refs, modelsWithInput);\n continue;\n }\n // When a model extends an external parent that has an Input variant,\n // the write schema extends ParentInput — so we need to import it.\n if (model.bases?.[0] && modelsWithInput.has(model.bases?.[0]) && !localNames.has(model.bases?.[0])) {\n refs.add(`${model.bases?.[0]}Input`);\n }\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n for (const field of writeFields) {\n collectInputTypeRefs(field.type, refs, modelsWithInput);\n }\n }\n\n // Remove locally defined Input variants (generated in this file)\n for (const name of localNames) {\n refs.delete(`${name}Input`);\n }\n\n return [...refs].sort();\n}\n\nfunction collectInputTypeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(i => collectInputTypeRefs(i, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeRefs(type.key, out, modelsWithInput);\n collectInputTypeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(m => collectInputTypeRefs(m, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\n/**\n * Topologically sort models so dependencies are emitted before dependents.\n * Falls back to source order for cycles (which would need z.lazy at runtime).\n */\nexport function topoSortModels(models: ModelNode[]): ModelNode[] {\n const localNames = new Set(models.map(m => m.name));\n const modelMap = new Map(models.map(m => [m.name, m]));\n\n // Build adjacency: model name → set of local model names it depends on\n const deps = new Map<string, Set<string>>();\n for (const model of models) {\n const refs = new Set<string>();\n if (model.bases?.[0] && localNames.has(model.bases?.[0])) refs.add(model.bases?.[0]);\n if (model.type) collectTypeRefs(model.type, refs);\n for (const field of model.fields) {\n collectTypeRefs(field.type, refs);\n }\n // Keep only local dependencies\n const localDeps = new Set<string>();\n for (const r of refs) {\n if (localNames.has(r) && r !== model.name) localDeps.add(r);\n }\n deps.set(model.name, localDeps);\n }\n\n // Kahn's algorithm\n const inDegree = new Map<string, number>();\n for (const name of localNames) inDegree.set(name, 0);\n for (const [, d] of deps) {\n for (const dep of d) {\n inDegree.set(dep, (inDegree.get(dep) ?? 0) + 1);\n }\n }\n\n // Note: inDegree counts how many models *depend on* this model,\n // but for Kahn's we need how many dependencies each model has.\n // Re-do: inDegree = number of unresolved deps for each model.\n const remaining = new Map<string, Set<string>>();\n for (const [name, d] of deps) {\n remaining.set(name, new Set(d));\n }\n\n const queue: string[] = [];\n for (const name of localNames) {\n if (remaining.get(name)!.size === 0) queue.push(name);\n }\n\n const sorted: ModelNode[] = [];\n while (queue.length > 0) {\n const name = queue.shift()!;\n sorted.push(modelMap.get(name)!);\n // Remove this model from all dependents' remaining sets\n for (const [other, rem] of remaining) {\n if (rem.delete(name) && rem.size === 0) {\n queue.push(other);\n }\n }\n }\n\n // Append any models not yet emitted (cycles)\n for (const model of models) {\n if (!sorted.includes(model)) sorted.push(model);\n }\n\n return sorted;\n}\n\n/**\n * Resolve the import path for an external model reference.\n * When a codegen context is available, computes the correct relative path\n * from the current file to the referenced model's output file.\n * Falls back to same-directory PascalCase → dot.case convention.\n */\nexport function resolveImportPath(refName: string, context?: ContractCodegenContext): string {\n if (context) {\n const refOutPath = context.modelOutPaths.get(refName);\n if (refOutPath) {\n const fromDir = dirname(context.currentOutPath);\n let rel = relative(fromDir, refOutPath);\n // Replace .ts extension with .js for ESM imports\n rel = rel.replace(/\\.ts$/, '.js');\n // Ensure relative path starts with ./ or ../\n if (!rel.startsWith('.')) rel = './' + rel;\n return rel;\n }\n }\n // Fallback: assume same directory, use PascalCase → dot.case convention\n const moduleName = pascalToDotCase(refName);\n return `./${moduleName}.js`;\n}\n\n/** Convert PascalCase to dot-separated lowercase: CounterpartyAccount → counterparty.account */\nexport function pascalToDotCase(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/g, '$1.$2').toLowerCase();\n}\n","import { dirname, relative } from 'node:path';\nimport type { ContractTypeNode, FieldNode, ScalarTypeNode } from '@contractkit/core';\n\n/** Declaration emitted into generated files that reference the `json` scalar. */\nexport const JSON_VALUE_TYPE_DECL = 'export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };';\n\n/** Quote a property name unless it is already a valid bare TypeScript identifier. */\nexport function quoteKey(name: string): string {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? name : `'${name}'`;\n}\n\n/** Escape text for safe inclusion inside a JSDoc block comment: neutralize the\n * block-comment terminator sequence and split embedded newlines into separate\n * ` * ` continuation lines. Returns the content lines (WITHOUT a leading prefix). */\nexport function escapeJsDocLines(text: string): string[] {\n return text.replace(/\\*\\//g, '*\\\\/').split('\\n');\n}\n\n/** Escape a string for inclusion inside a single-quoted TypeScript string literal. */\nexport function escapeSingleQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r');\n}\n\n/**\n * Render the markdown link back to the `.ck` declaration a generated construct came from, as\n * `[label](./path/to/file.ck#L12)`. Returns the link only; callers supply the surrounding prose\n * and comment prefix, since some sites emit it inside a JSDoc block and others inside a `//` line.\n *\n * The path is relative to the emitted file's own directory, so it resolves when the reader clicks\n * it from wherever the file was written. `outPath` is optional because codegen can run without a\n * destination (the prettier plugin, and several tests), in which case the source path is used\n * as-is.\n *\n * Not `file://./path`: `file://` opens an authority component, so the `.` parses as the host and\n * the link resolves to nothing. A plain relative path is the correct form.\n */\nexport function sourceLink(label: string, outPath: string | undefined, sourceFile: string, line?: number): string {\n const rel = outPath ? relative(dirname(outPath), sourceFile) : sourceFile;\n const href = rel.startsWith('.') ? rel : `./${rel}`;\n return `[${label}](${href}${line === undefined ? '' : `#L${line}`})`;\n}\n\n/** Convert an HTTP header name (e.g. `preference-applied`, `X-Request-ID`, `ETag`) to camelCase for use as a JS property. */\nexport function headerNameToProperty(name: string): string {\n const parts = name.split(/[-_]/).filter(Boolean);\n return parts\n .map((p, i) => {\n const lower = p.toLowerCase();\n return i === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);\n })\n .join('');\n}\n\n// ─── TypeScript type rendering ────────────────────────────────────────────\n\n/**\n * Which runtime the emitted types describe. A few scalars have no single correct TypeScript\n * type: `binary` is a `Blob` in a fetch-based client but a `Buffer` on a Node server. Everything\n * else renders identically for both targets. Defaults to `'client'`.\n */\nexport type TsRenderTarget = 'client' | 'server';\n\n/**\n * Render a contract type as a plain TypeScript type expression. Model refs render as their bare\n * name; use `renderInputTsType` / `renderOutputTsType` to substitute Input/Output variants.\n *\n * @param target Runtime the type describes; only `binary` differs (`Buffer` vs `Blob`).\n */\nexport function renderTsType(type: ContractTypeNode, target: TsRenderTarget = 'client'): string {\n switch (type.kind) {\n case 'scalar':\n return renderTsScalar(type.name, target);\n case 'array': {\n const inner = renderTsType(type.item, target);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'tuple':\n return `[${type.items.map(i => renderTsType(i, target)).join(', ')}]`;\n case 'record':\n return `Record<${renderTsType(type.key, target)}, ${renderTsType(type.value, target)}>`;\n case 'enum':\n return type.values.map(v => `'${escapeSingleQuoted(v)}'`).join(' | ');\n case 'literal':\n return typeof type.value === 'string' ? `'${escapeSingleQuoted(type.value)}'` : String(type.value);\n case 'union':\n return type.members.map(m => renderTsType(m, target)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderTsType(m, target)).join(' | ');\n case 'intersection':\n return type.members.map(m => renderTsType(m, target)).join(' & ');\n case 'ref':\n return type.name;\n case 'lazy':\n return renderTsType(type.inner, target);\n case 'inlineObject':\n return renderTsInlineObject(type.fields, target);\n default:\n return 'unknown';\n }\n}\n\nfunction renderTsScalar(name: ScalarTypeNode['name'], target: TsRenderTarget): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n return 'string';\n case 'number':\n case 'int':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'decimal':\n // The one scalar whose wire view and server view agree — see the note on this\n // function and on `serverTsScalar`. A `decimal` travels as a quoted string, and both\n // the router (via `_ZodDecimal`) and the SDK (via the generated `reviveX` functions)\n // hand the developer a real `Decimal`, so there is no `target` split to make.\n return 'Decimal';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'time':\n case 'datetime':\n // Luxon objects on both sides. The router parses them via `_ZodDatetime`, and the SDK\n // rehydrates them in its generated revivers, so `string` was a claim neither honoured.\n return 'DateTime';\n case 'duration':\n return 'Duration';\n case 'interval':\n // The exception: `_ZodInterval` transforms back to an ISO string on output, so a\n // string is genuinely what a consumer receives.\n return 'string';\n case 'null':\n return 'null';\n case 'unknown':\n return 'unknown';\n case 'object':\n return 'Record<string, unknown>';\n case 'binary':\n // Node servers hand the handler a Buffer (matching `_ZodBinary`); fetch clients get a Blob.\n return target === 'server' ? 'Buffer' : 'Blob';\n case 'json':\n return 'JsonValue';\n default: {\n const _exhaustive: never = name;\n throw new Error(`plugin-typescript: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\nfunction renderTsInlineObject(fields: FieldNode[], target: TsRenderTarget): string {\n const entries = fields.map(f => {\n const opt = f.optional ? '?' : '';\n return `${quoteKey(f.name)}${opt}: ${renderTsType(f.type, target)}`;\n });\n return `{ ${entries.join('; ')} }`;\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Input variant\n * when the model has visibility modifiers. Used for request-side types\n * (body, params, query, headers).\n *\n * @param target Runtime the type describes; only `binary` differs (`Buffer` vs `Blob`).\n */\nexport function renderInputTsType(type: ContractTypeNode, modelsWithInput?: Set<string>, target: TsRenderTarget = 'client'): string {\n if (!modelsWithInput || modelsWithInput.size === 0) return renderTsType(type, target);\n switch (type.kind) {\n case 'ref':\n return modelsWithInput.has(type.name) ? `${type.name}Input` : type.name;\n case 'array': {\n const inner = renderInputTsType(type.item, modelsWithInput, target);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderInputTsType(m, modelsWithInput, target)).join(' & ');\n case 'union':\n return type.members.map(m => renderInputTsType(m, modelsWithInput, target)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderInputTsType(m, modelsWithInput, target)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderInputTsType(f.type, modelsWithInput, target)}`).join('; ')} }`;\n case 'lazy':\n return renderInputTsType(type.inner, modelsWithInput, target);\n default:\n return renderTsType(type, target);\n }\n}\n\n/**\n * Like renderTsType, but substitutes model refs with their Output variant\n * (post-transform wire shape) when the model has format(output=...) or\n * transitively references one. Used for response-side types in routers\n * and SDK return types.\n *\n * @param target Runtime the type describes; only `binary` differs (`Buffer` vs `Blob`).\n */\nexport function renderOutputTsType(type: ContractTypeNode, modelsWithOutput?: Set<string>, target: TsRenderTarget = 'client'): string {\n if (!modelsWithOutput || modelsWithOutput.size === 0) return renderTsType(type, target);\n switch (type.kind) {\n case 'ref':\n return modelsWithOutput.has(type.name) ? `${type.name}Output` : type.name;\n case 'array': {\n const inner = renderOutputTsType(type.item, modelsWithOutput, target);\n const needsParens =\n type.item.kind === 'union' ||\n type.item.kind === 'discriminatedUnion' ||\n type.item.kind === 'intersection' ||\n type.item.kind === 'enum';\n return needsParens ? `(${inner})[]` : `${inner}[]`;\n }\n case 'intersection':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput, target)).join(' & ');\n case 'union':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput, target)).join(' | ');\n case 'discriminatedUnion':\n return type.members.map(m => renderOutputTsType(m, modelsWithOutput, target)).join(' | ');\n case 'inlineObject':\n return `{ ${type.fields.map(f => `${quoteKey(f.name)}${f.optional ? '?' : ''}: ${renderOutputTsType(f.type, modelsWithOutput, target)}`).join('; ')} }`;\n case 'lazy':\n return renderOutputTsType(type.inner, modelsWithOutput, target);\n default:\n return renderTsType(type, target);\n }\n}\n","/**\n * The emitted decimal.js runtime shared by every generator that renders a `decimal` scalar.\n *\n * `_ZodBinary`/`_ZodDatetime`/`_ZodInterval` are duplicated as literals across codegen-contract,\n * codegen-operation and codegen-mcp, and have already drifted once (the three files emit their\n * luxon import lists in two different orders). The decimal runtime is defined once here so the\n * three call sites cannot disagree about it; each still decides *whether* to emit it with its own\n * detection strategy, which is the part that legitimately differs between them.\n */\n\n/**\n * The decimal.js import — **named, not default**.\n *\n * `decimal.d.ts` declares `Decimal` three times over: a class, a namespace, and a function, with\n * `export default Decimal` alongside. Under the `NodeNext` resolution the scaffolded SDK uses\n * (`module: NodeNext` + `\"type\": \"module\"`), the default export resolves to the *namespace*\n * meaning, so `import Decimal from 'decimal.js'` fails to compile with \"Cannot use namespace\n * 'Decimal' as a type\" and \"Property 'set' does not exist\". The named import binds the merged\n * class and is the only form that typechecks.\n */\nexport const DECIMAL_IMPORT = `import { Decimal } from 'decimal.js';`;\n\n/**\n * Global decimal.js configuration, emitted in **every** file that imports `Decimal` — plain-types\n * mode included, where there is no Zod schema but `String(value)` and `JSON.stringify` still run.\n *\n * Load-bearing, not cosmetic. decimal.js switches to exponential\n * notation outside `toExpNeg`/`toExpPos` (defaults -7/21), so without it `new Decimal('0.00000001')`\n * serializes as `\"1e-8\"` and any peer validating `^-?\\d+(\\.\\d+)?$` rejects it. It is the only lever\n * that reaches the `JSON.stringify` Koa runs over `ctx.body`, which we do not otherwise control.\n *\n */\nexport const DECIMAL_CONFIG_LINE = `Decimal.set({ toExpNeg: -9e15, toExpPos: 9e15 });`;\n\n/**\n * The Zod schema for a `decimal`.\n *\n * Deliberately has no output `.transform()`. `isRevalidatable` in codegen-operation treats every\n * scalar as idempotent under re-parse — the assumption `server.validateResponses` rests on — and\n * preprocess passes an already-`Decimal` value through untouched, so it holds.\n *\n * A raw JSON number fails validation rather than being coerced: by the time one reaches us it has\n * already been through an IEEE-754 double, which is the loss this scalar exists to prevent. Bad\n * strings are returned unchanged from preprocess rather than throwing, so they surface as an\n * ordinary Zod issue instead of a `DecimalError` escaping the parse.\n */\nexport const DECIMAL_ZOD_SCHEMA_LINE = `const _ZodDecimal = z.preprocess((val) => { if (typeof val !== 'string') return val; try { return new Decimal(val); } catch { return val; } }, z.custom<Decimal>((val) => Decimal.isDecimal(val), { message: 'Must be an exact decimal sent as a quoted string, e.g. \"1250.00\"' }));`;\n\n/** The decimal runtime for a file that also holds Zod schemas, in emission order. */\nexport const DECIMAL_PRELUDE_LINES: readonly string[] = [DECIMAL_CONFIG_LINE, DECIMAL_ZOD_SCHEMA_LINE];\n","import type { ContractTypeNode, FieldNode, ModelNode, ScalarTypeNode } from '@contractkit/core';\n\n/**\n * Emitters for the `reviveX` functions that rehydrate `decimal` fields in an SDK response.\n *\n * A decimal arrives as a quoted JSON string, but the generated types say `Decimal`, so something\n * has to construct one. The SDK cannot do it the way `bigint` does — `bigIntReviver` works only\n * because bigint invented a tagged `\"123n\"` wire encoding, and `\"10.50\"` is indistinguishable from\n * an ordinary string without knowing the schema. Nor can it re-parse the response through the Zod\n * schema: `XOutput` is a `z.output<>` type alias with no runtime value behind it, and models\n * default to `z.strictObject`, so any field the server added would throw in every deployed client.\n *\n * So the knowledge lives in generated code instead: one function per model that walks to the field\n * positions a decimal can occupy and converts in place. Mutating rather than rebuilding keeps the\n * cost proportional to the number of decimal fields, and preserves unknown server-added keys —\n * the forward compatibility a strict re-parse would destroy.\n *\n * Emitted from the AST, so zod mode and plain-types mode produce identical runtime behaviour.\n */\n\nexport interface ReviveCodegenOptions {\n /** Models that carry a revivable scalar, directly or transitively. Only these get a reviver. */\n modelsWithDecimal: Set<string>;\n /**\n * Which scalars need rehydrating from their wire form. Defaults to `decimal`, the only scalar\n * whose runtime type currently differs from what `JSON.parse` produces.\n *\n * A set rather than a boolean because the question a reviver asks is not \"does this reach a\n * decimal\" but \"which conversion does this leaf need\" — and the answer becomes plural as soon\n * as a second scalar joins.\n */\n revivableScalars?: ReadonlySet<ScalarTypeNode['name']>;\n /** Models with an `Output` variant, which need a second reviver keyed by the output casing. */\n modelsWithOutput?: Set<string>;\n /** Every model in scope, for resolving discriminated-union members to their literal tag. */\n modelMap?: Map<string, ModelNode>;\n}\n\n/**\n * The per-file coercion helpers, keyed by the call prefix that identifies them in emitted text.\n *\n * A file gets only the helpers its revivers actually call, decided by scanning the emitted lines\n * — the same text-derived idiom the reviver and type imports use, and for the same reason: a\n * predicate computed separately can drift and leave an unused local behind.\n *\n * Each one takes the raw JSON value and throws a `TypeError` naming the path rather than\n * returning something invalid, because a silently wrong `DateTime` surfaces much further from\n * the cause than a throw at the boundary does.\n */\nexport const COERCE_DECLS: Record<string, string[]> = {\n '__dec(': [\n `const __dec = (v: unknown, path: string): Decimal => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected a decimal string at '\\${path}', received \\${typeof v} — decimals must be sent as quoted JSON strings.\\`);`,\n ` }`,\n ` try {`,\n ` return new Decimal(v);`,\n ` } catch {`,\n ` throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' is not a valid decimal.\\`);`,\n ` }`,\n `};`,\n ],\n '__dt(': [\n `const __dt = (v: unknown, path: string): DateTime => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected an ISO 8601 string at '\\${path}', received \\${typeof v}.\\`);`,\n ` }`,\n ` const d = DateTime.fromISO(v);`,\n ` if (!d.isValid) throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' is not a valid ISO 8601 datetime.\\`);`,\n ` return d;`,\n `};`,\n ],\n '__dtf(': [\n `const __dtf = (v: unknown, path: string, fmt: string): DateTime => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected a string at '\\${path}' in format \\${fmt}, received \\${typeof v}.\\`);`,\n ` }`,\n ` const d = DateTime.fromFormat(v, fmt);`,\n ` if (!d.isValid) throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' does not match format \\${fmt}.\\`);`,\n ` return d;`,\n `};`,\n ],\n '__dur(': [\n `const __dur = (v: unknown, path: string): Duration => {`,\n ` if (typeof v !== 'string') {`,\n ` throw new TypeError(\\`ContractKit: expected an ISO 8601 duration string at '\\${path}', received \\${typeof v}.\\`);`,\n ` }`,\n ` const d = Duration.fromISO(v);`,\n ` if (!d.isValid) throw new TypeError(\\`ContractKit: '\\${v}' at '\\${path}' is not a valid ISO 8601 duration.\\`);`,\n ` return d;`,\n `};`,\n ],\n};\n\n/** Back-compat alias: the decimal helper alone, which several call sites still name directly. */\nexport const DECIMAL_COERCE_DECL = COERCE_DECLS['__dec(']!;\n\n/** The helper declarations `lines` actually calls, in a stable order. */\nexport function coerceDeclsFor(lines: string[]): string[] {\n const haystack = lines.join('\\n');\n return Object.entries(COERCE_DECLS)\n .filter(([prefix]) => haystack.includes(prefix))\n .flatMap(([, decl]) => decl);\n}\n\n/** Luxon classes referenced by the helpers `lines` calls, for the importing file to bring in. */\nexport function coerceLuxonImports(lines: string[]): string[] {\n const haystack = lines.join('\\n');\n const needed = new Set<string>();\n if (haystack.includes('__dt(') || haystack.includes('__dtf(')) needed.add('DateTime');\n if (haystack.includes('__dur(')) needed.add('Duration');\n return [...needed].sort();\n}\n\n/** `reviveInvoice` / `reviveInvoiceOutput`. */\nexport function reviveFnName(model: string, variant: 'base' | 'output' = 'base'): string {\n return `revive${model}${variant === 'output' ? 'Output' : ''}`;\n}\n\nfunction applyCase(name: string, caseTransform: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!caseTransform || caseTransform === 'camel') return name;\n if (caseTransform === 'snake') return name.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\n/**\n * Scalars whose runtime type differs from what `JSON.parse` produces, and which a reviver\n * therefore has to rehydrate. The default of {@link ReviveCodegenOptions.revivableScalars}.\n *\n * `interval` is excluded: `_ZodInterval` ends in `.transform(v => v.toISO()!)`, so its inferred\n * output type is already `string` and there is nothing to revive it to. Covering it means making\n * that round-trip idempotent first, which the router's `isRevalidatable` also depends on.\n */\nexport const DEFAULT_REVIVABLE_SCALARS: ReadonlySet<ScalarTypeNode['name']> = new Set([\n 'decimal',\n 'date',\n 'time',\n 'datetime',\n 'duration',\n]);\n\n/** Whether a type reaches a revivable scalar, following refs through `modelsWithDecimal`. */\nexport function typeReachesDecimal(type: ContractTypeNode, opts: ReviveCodegenOptions): boolean {\n switch (type.kind) {\n case 'scalar':\n return (opts.revivableScalars ?? DEFAULT_REVIVABLE_SCALARS).has(type.name);\n case 'ref':\n return opts.modelsWithDecimal.has(type.name);\n case 'array':\n return typeReachesDecimal(type.item, opts);\n case 'lazy':\n return typeReachesDecimal(type.inner, opts);\n case 'tuple':\n return type.items.some(t => typeReachesDecimal(t, opts));\n case 'record':\n // Value only, deliberately unlike `typeHasScalar` in core, which also checks the key.\n // That one answers \"is this scalar mentioned\", which decides imports; this one answers\n // \"is there a value to rehydrate\", and a JSON object key is always a string — there is\n // nothing at a key position for a reviver to convert.\n return typeReachesDecimal(type.value, opts);\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n return type.members.some(t => typeReachesDecimal(t, opts));\n case 'inlineObject':\n return type.fields.some(f => typeReachesDecimal(f.type, opts));\n default:\n return false;\n }\n}\n\n/**\n * The statement that rehydrates one scalar leaf, or nothing when the scalar needs no conversion.\n *\n * `date` and `time` carry their format on the node, and the reviver has to parse with the same\n * format the schema validates against — which is why the helper takes it as an argument rather\n * than baking one in. Defaults match `renderTsScalar`'s.\n *\n * `interval` is deliberately absent. `_ZodInterval` ends in `.transform(v => v.toISO()!)`, so its\n * inferred output is a string and there is nothing to revive it to; covering it means making that\n * round-trip idempotent first, which `isRevalidatable` in the router also depends on.\n */\nfunction scalarCoercion(type: ScalarTypeNode, slot: string, path: string, opts: ReviveCodegenOptions): string[] {\n if (!(opts.revivableScalars ?? DEFAULT_REVIVABLE_SCALARS).has(type.name)) return [];\n switch (type.name) {\n case 'decimal':\n return [`${slot} = __dec(${slot}, '${path}');`];\n case 'datetime':\n return [`${slot} = __dt(${slot}, '${path}');`];\n case 'duration':\n return [`${slot} = __dur(${slot}, '${path}');`];\n case 'date':\n return [`${slot} = __dtf(${slot}, '${path}', '${type.format ?? 'yyyy-MM-dd'}');`];\n case 'time':\n return [`${slot} = __dtf(${slot}, '${path}', '${type.format ?? 'HH:mm:ss'}');`];\n default:\n return [];\n }\n}\n\n/** Fresh local names, so nested loops in one function body cannot collide. */\nclass Scope {\n private n = 0;\n next(prefix: string): string {\n return `__${prefix}${this.n++}`;\n }\n}\n\n/**\n * Statements that hydrate `slot` — an assignable expression — in place.\n *\n * `path` is threaded purely for the error message; it is what tells a consumer *which* field of a\n * large response was malformed.\n */\nfunction emit(slot: string, type: ContractTypeNode, path: string, opts: ReviveCodegenOptions, scope: Scope, variant: 'base' | 'output'): string[] {\n switch (type.kind) {\n case 'scalar':\n return scalarCoercion(type, slot, path, opts);\n\n case 'ref':\n return opts.modelsWithDecimal.has(type.name) ? [`${reviveRefName(type.name, opts, variant)}(${slot} as never);`] : [];\n\n case 'lazy':\n return emit(slot, type.inner, path, opts, scope, variant);\n\n case 'array': {\n if (!typeReachesDecimal(type.item, opts)) return [];\n const arr = scope.next('a');\n const i = scope.next('i');\n const inner = emit(`${arr}[${i}]`, type.item, `${path}[]`, opts, scope, variant);\n return [\n `{`,\n ` const ${arr} = ${slot} as unknown[];`,\n ` for (let ${i} = 0; ${i} < ${arr}.length; ${i}++) {`,\n ...inner.map(l => ` ${l}`),\n ` }`,\n `}`,\n ];\n }\n\n case 'tuple': {\n const items = type.items.flatMap((t, idx) =>\n typeReachesDecimal(t, opts) ? emit(`(${slot} as unknown[])[${idx}]`, t, `${path}[${idx}]`, opts, scope, variant) : [],\n );\n return items;\n }\n\n case 'record': {\n if (!typeReachesDecimal(type.value, opts)) return [];\n const rec = scope.next('r');\n const k = scope.next('k');\n const inner = emit(`${rec}[${k}]`, type.value, `${path}{}`, opts, scope, variant);\n return [\n `{`,\n ` const ${rec} = ${slot} as Record<string, unknown>;`,\n ` for (const ${k} of Object.keys(${rec})) {`,\n ...inner.map(l => ` ${l}`),\n ` }`,\n `}`,\n ];\n }\n\n case 'inlineObject': {\n const relevant = type.fields.filter(f => typeReachesDecimal(f.type, opts));\n if (relevant.length === 0) return [];\n const obj = scope.next('o');\n const body = relevant.flatMap(f => fieldStatements(obj, f, path, opts, scope, variant, undefined));\n return [`{`, ` const ${obj} = ${slot} as Record<string, unknown>;`, ...body.map(l => ` ${l}`), `}`];\n }\n\n case 'intersection':\n return type.members.flatMap(m => emit(slot, m, path, opts, scope, variant));\n\n case 'union': {\n // `validateDecimal` rejects a decimal in a union with more than one non-null member, so\n // anything reaching here is `T | null`: hydrate the single real member behind a guard.\n const real = type.members.filter(m => !(m.kind === 'scalar' && m.name === 'null'));\n const target = real.find(m => typeReachesDecimal(m, opts));\n if (!target) return [];\n const inner = emit(slot, target, path, opts, scope, variant);\n return [`if (${slot} != null) {`, ...inner.map(l => ` ${l}`), `}`];\n }\n\n case 'discriminatedUnion': {\n const branches: string[] = [];\n const disc = scope.next('d');\n for (const member of type.members) {\n if (!typeReachesDecimal(member, opts)) continue;\n const tag = discriminatorTag(member, type.discriminator, opts);\n const inner = emit(slot, member, path, opts, scope, variant);\n if (inner.length === 0) continue;\n if (tag === undefined) {\n // No resolvable literal: hydrating unconditionally could apply the wrong arm's\n // shape, so skip it rather than risk corrupting a sibling member's field.\n continue;\n }\n branches.push(` if (${disc} === ${JSON.stringify(tag)}) {`, ...inner.map(l => ` ${l}`), ` }`);\n }\n if (branches.length === 0) return [];\n return [`{`, ` const ${disc} = (${slot} as Record<string, unknown>)[${JSON.stringify(type.discriminator)}];`, ...branches, `}`];\n }\n\n default:\n return [];\n }\n}\n\n/** The literal value that selects `member` in a discriminated union, when it can be resolved. */\nfunction discriminatorTag(member: ContractTypeNode, discriminator: string, opts: ReviveCodegenOptions): string | number | boolean | undefined {\n const fields: FieldNode[] | undefined =\n member.kind === 'inlineObject' ? member.fields : member.kind === 'ref' ? opts.modelMap?.get(member.name)?.fields : undefined;\n const field = fields?.find(f => f.name === discriminator);\n if (field?.type.kind === 'literal') return field.type.value;\n // A single-valued enum is the other way a discriminator gets written.\n if (field?.type.kind === 'enum' && field.type.values.length === 1) return field.type.values[0];\n return undefined;\n}\n\n/** Statements for one field of an object held in `objVar`. */\nfunction fieldStatements(\n objVar: string,\n field: FieldNode,\n path: string,\n opts: ReviveCodegenOptions,\n scope: Scope,\n variant: 'base' | 'output',\n outputCase: 'camel' | 'snake' | 'pascal' | undefined,\n): string[] {\n const key = variant === 'output' ? applyCase(field.name, outputCase) : field.name;\n const slot = `${objVar}[${JSON.stringify(key)}]`;\n const inner = emit(slot, field.type, `${path}.${key}`, opts, scope, variant);\n if (inner.length === 0) return [];\n // A union already emits its own null guard; adding a second would just nest.\n if (field.type.kind === 'union') return inner;\n if (field.optional || field.nullable) {\n return [`if (${slot} != null) {`, ...inner.map(l => ` ${l}`), `}`];\n }\n return inner;\n}\n\n/**\n * Pick the reviver for a referenced model.\n *\n * Mirrors `renderOutputTsType`: inside an output reviver, a referenced model uses its *own* output\n * reviver only if it has one. `computeModelsWithOutput` propagates referrer→referenced, so a child\n * of a transformed parent is not itself transformed and keeps camelCase keys.\n */\nfunction reviveRefName(name: string, opts: ReviveCodegenOptions, variant: 'base' | 'output'): string {\n if (variant === 'output' && opts.modelsWithOutput?.has(name)) return reviveFnName(name, 'output');\n return reviveFnName(name, 'base');\n}\n\n/**\n * A standalone reviver for an arbitrary type node — used for a response body that is not a plain\n * model reference (an inline object, a record, a tuple), where there is no `reviveX` to call.\n *\n * Returns `null` when the type holds no decimal, so the caller emits nothing at all.\n */\nexport function renderInlineReviver(\n fnName: string,\n tsType: string,\n type: ContractTypeNode,\n opts: ReviveCodegenOptions,\n variant: 'base' | 'output' = 'output',\n): string[] | null {\n if (!typeReachesDecimal(type, opts)) return null;\n const scope = new Scope();\n const body = emit('__v[0]', type, fnName.replace(/^__revive/, ''), opts, scope, variant);\n if (body.length === 0) return null;\n return [\n `/** Rehydrates the \\`decimal\\` fields of one response body. Mutates and returns \\`raw\\`. */`,\n `function ${fnName}(raw: ${tsType}): ${tsType} {`,\n ` const __v = [raw] as unknown[];`,\n ...body.map(l => ` ${l}`),\n ` return __v[0] as ${tsType};`,\n `}`,\n ];\n}\n\n/** The `reviveX` (and `reviveXOutput`) declarations for one model, or `[]` if it holds no decimal. */\nexport function renderReviveFunctions(model: ModelNode, opts: ReviveCodegenOptions): string[] {\n if (!opts.modelsWithDecimal.has(model.name)) return [];\n const lines = renderOne(model, opts, 'base');\n if (opts.modelsWithOutput?.has(model.name)) {\n lines.push('');\n lines.push(...renderOne(model, opts, 'output'));\n }\n return lines;\n}\n\nfunction renderOne(model: ModelNode, opts: ReviveCodegenOptions, variant: 'base' | 'output'): string[] {\n const scope = new Scope();\n const typeName = `${model.name}${variant === 'output' ? 'Output' : ''}`;\n const fnName = reviveFnName(model.name, variant);\n\n // A type-alias model has no fields — hydrate the aliased type as a whole.\n if (model.type) {\n const body = emit('__v[0]', model.type, model.name, opts, scope, variant);\n if (body.length === 0) return [];\n return [\n `/** Rehydrates every wire-encoded scalar in a ${typeName} into its runtime type. Mutates and returns \\`raw\\`. */`,\n `export function ${fnName}(raw: ${typeName}): ${typeName} {`,\n ` const __v = [raw] as unknown[];`,\n ...body.map(l => ` ${l}`),\n ` return __v[0] as ${typeName};`,\n `}`,\n ];\n }\n\n const obj = scope.next('o');\n const body = model.fields.flatMap(f =>\n typeReachesDecimal(f.type, opts) ? fieldStatements(obj, f, model.name, opts, scope, variant, model.outputCase) : [],\n );\n if (body.length === 0) return [];\n\n return [\n `/** Rehydrates every wire-encoded scalar in a ${typeName} into its runtime type. Mutates and returns \\`raw\\`. */`,\n `export function ${fnName}(raw: ${typeName}): ${typeName} {`,\n ` const ${obj} = raw as unknown as Record<string, unknown>;`,\n ...body.map(l => ` ${l}`),\n ` return raw;`,\n `}`,\n ];\n}\n","import type {\n OpRootNode,\n OpRouteNode,\n OpOperationNode,\n OpResponseNode,\n OpResponseHeaderNode,\n ContractTypeNode,\n ScalarTypeNode,\n ParamSource,\n ObjectMode,\n} from '@contractkit/core';\nimport { resolveModifiers, resolveSecurity, SECURITY_NONE, classifyContentType, emittedResponses, PATH_PARAM_RE_G, toIdentifier } from '@contractkit/core';\nimport {\n renderType,\n renderInputType,\n renderQueryType,\n applyFieldModifiers,\n pascalToDotCase,\n modeToWrapper,\n} from './codegen-contract.js';\nimport { renderOutputTsType, quoteKey, headerNameToProperty, escapeJsDocLines, escapeSingleQuoted, sourceLink } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_PRELUDE_LINES } from './decimal-runtime.js';\nimport { basename, dirname, relative } from 'path';\nimport type { ServerFramework } from './server-framework.js';\nimport { KOA_SERVER_FRAMEWORK } from './server-framework-koa.js';\n\n/** Which request-side object a validation block reads from. Names the variable the block declares. */\nexport type ParamKind = 'params' | 'query' | 'headers';\n\n/**\n * Identifiers the generated handler body binds for itself. A path parameter destructured under one\n * of these names would redeclare it, so those bindings are renamed the same way a collision with a\n * handler parameter is.\n */\nconst GENERATOR_HANDLER_LOCALS = ['service', 'result', 'body', 'multipartBody', 'params', 'query', 'headers'] as const;\n\n/**\n * Local identifier for each inline path parameter, keyed by its declared name.\n *\n * The declared name is what the framework keys its params object by, so it stays the schema key and\n * the route placeholder; only the local binding moves, and a `_` is appended until it collides with\n * neither a reserved identifier nor another parameter's binding. Path parameters are spread\n * positionally into the service call, so a rename is invisible to the service.\n */\nfunction bindPathParams(nodes: readonly { name: string }[], handlerLocals: readonly string[]): Map<string, string> {\n const reserved = new Set<string>([...handlerLocals, ...GENERATOR_HANDLER_LOCALS]);\n const taken = new Set<string>();\n const bindings = new Map<string, string>();\n for (const node of nodes) {\n let local = toIdentifier(node.name);\n while (reserved.has(local) || taken.has(local)) local += '_';\n taken.add(local);\n bindings.set(node.name, local);\n }\n return bindings;\n}\n\n// ─── Content-type helpers ──────────────────────────────────────────────────\n\n/**\n * Map a request MIME type to the ServerKit parser token used in middleware. The tokens are the keys\n * of the parser map in `@maroonedsoftware/servercore`, so they are the same whichever HTTP framework\n * the router targets.\n */\nfunction bodyParserToken(contentType: string): string {\n switch (classifyContentType(contentType)) {\n case 'urlencoded':\n return 'urlencoded';\n case 'multipart':\n return 'multipart';\n case 'text':\n return 'text';\n case 'binary':\n // There is no native binary token; fall back to text so the body is still readable as a\n // string. Services handling binary uploads should switch to multipart/form-data.\n return 'text';\n default:\n return 'json';\n }\n}\n\n/**\n * Deep structural equality on ContractTypeNode, ignoring source locations on inline fields.\n * Used to decide whether multiple declared request MIMEs can share a single validate path.\n */\nexport function bodyTypesStructurallyEqual(a: ContractTypeNode, b: ContractTypeNode): boolean {\n if (a.kind !== b.kind) return false;\n switch (a.kind) {\n case 'scalar': {\n const bb = b as typeof a;\n return (\n a.name === bb.name &&\n a.min === bb.min &&\n a.max === bb.max &&\n a.len === bb.len &&\n a.scale === bb.scale &&\n a.regex === bb.regex &&\n a.format === bb.format\n );\n }\n case 'array': {\n const bb = b as typeof a;\n return a.min === bb.min && a.max === bb.max && bodyTypesStructurallyEqual(a.item, bb.item);\n }\n case 'tuple': {\n const bb = b as typeof a;\n return a.items.length === bb.items.length && a.items.every((x, i) => bodyTypesStructurallyEqual(x, bb.items[i]!));\n }\n case 'record': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.key, bb.key) && bodyTypesStructurallyEqual(a.value, bb.value);\n }\n case 'enum': {\n const bb = b as typeof a;\n return a.values.length === bb.values.length && a.values.every((v, i) => v === bb.values[i]);\n }\n case 'literal': {\n const bb = b as typeof a;\n return a.value === bb.value;\n }\n case 'union':\n case 'intersection': {\n const bb = b as typeof a;\n return a.members.length === bb.members.length && a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!));\n }\n case 'discriminatedUnion': {\n const bb = b as typeof a;\n return (\n a.discriminator === bb.discriminator &&\n a.members.length === bb.members.length &&\n a.members.every((m, i) => bodyTypesStructurallyEqual(m, bb.members[i]!))\n );\n }\n case 'ref': {\n const bb = b as typeof a;\n return a.name === bb.name && !!a.lazy === !!bb.lazy;\n }\n case 'lazy': {\n const bb = b as typeof a;\n return bodyTypesStructurallyEqual(a.inner, bb.inner);\n }\n case 'inlineObject': {\n const bb = b as typeof a;\n if (a.mode !== bb.mode) return false;\n if (a.fields.length !== bb.fields.length) return false;\n return a.fields.every((f, i) => {\n const g = bb.fields[i]!;\n return (\n f.name === g.name &&\n f.optional === g.optional &&\n f.nullable === g.nullable &&\n f.visibility === g.visibility &&\n f.default === g.default &&\n !!f.deprecated === !!g.deprecated &&\n bodyTypesStructurallyEqual(f.type, g.type)\n );\n });\n }\n }\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/** Options controlling how {@link generateOp} renders a server router module. */\nexport interface OpCodegenOptions {\n servicePathTemplate?: string;\n typeImportPathTemplate?: string;\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /**\n * Whether to emit handlers for operations marked `internal`. Defaults to `true` because\n * the server still needs routes for internal endpoints; set to `false` to omit them\n * from the generated router entirely.\n */\n includeInternal?: boolean;\n /**\n * Re-parse the service result through its declared response schema before writing the response\n * body, and write the parsed value. Requires the type file to hold Zod schemas (`server.zod`) —\n * plain interfaces are types, with no runtime schema value to validate against. Default false.\n */\n validateResponses?: boolean;\n /**\n * Set of model names whose schema applies a `format(...)` key transform, directly or through a\n * referenced model. Response bodies touching one are left unvalidated: the service returns the\n * post-transform shape, which the schema itself cannot re-parse.\n */\n modelsWithTransform?: Set<string>;\n /**\n * Which HTTP framework the emitted router targets. Every framework-specific string in the output\n * comes from here. Defaults to Koa, the only framework shipped today.\n */\n framework?: ServerFramework;\n}\n\n/** {@link OpCodegenOptions} after {@link generateOp} has filled in the framework default. */\ntype ResolvedOpCodegenOptions = OpCodegenOptions & { framework: ServerFramework };\n\n/**\n * Generate a server router module for every operation in `root`, including the imports, type\n * aliases, and handler list.\n *\n * Imports are derived from the generated body — each candidate symbol is emitted only if it\n * actually appears in the output. Deciding them from predicates over the AST instead means any\n * drift between predicate and codegen leaves an unused import in every generated file, which\n * trips `noUnusedLocals` and lint downstream.\n */\nexport function generateOp(root: OpRootNode, options: OpCodegenOptions = {}): string {\n // Resolved once here rather than defaulted at each use, so every helper below reads a framework\n // that is definitely present and no branch can quietly fall back to a different one.\n const resolved: ResolvedOpCodegenOptions = { ...options, framework: options.framework ?? KOA_SERVER_FRAMEWORK };\n const framework = resolved.framework;\n // Collect all referenced types across all routes\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput);\n const services = collectServices(root);\n const routerName = deriveRouterName(root.file);\n\n const lines: string[] = [];\n\n lines.push('');\n lines.push('/**');\n lines.push(` * generated from ${sourceLink(basename(root.file), options.outPath, root.file)}`);\n lines.push('*/');\n lines.push(framework.routerDeclaration(routerName));\n lines.push('');\n\n const includeInternal = options.includeInternal ?? true;\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n lines.push(...generateHandler(route, op, root, resolved));\n lines.push('');\n }\n }\n\n // Helpers and imports are both decided from the code we just generated, not from predicates\n // over the AST that have to be kept in step with it by hand. A predicate that drifts leaves an\n // unused declaration in every generated file, which trips `noUnusedLocals` and lint in\n // consuming projects — `opNeedsScalar(root, 'binary')` over-approximates exactly that way,\n // since a binary *response* body is a plain `Buffer` annotation with no schema behind it.\n const handlerBody = lines.join('\\n');\n const references = (symbol: string) => new RegExp(`\\\\b${symbol}\\\\b`).test(handlerBody);\n\n const helpers: string[] = [];\n if (references('_ZodBinary')) {\n helpers.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (references('_ZodDatetime')) {\n helpers.push(\n `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' }));`,\n );\n }\n if (references('_ZodDecimal')) {\n helpers.push(...DECIMAL_PRELUDE_LINES);\n }\n if (references('_ZodInterval')) {\n helpers.push(\n `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()!);`,\n );\n }\n // `_ZodJson`'s own declaration is annotated with `_JsonValue`, so the type alias comes along\n // with it; the alias is also needed on its own for a `json` body's server-side annotation.\n const needsZodJson = references('_ZodJson');\n if (needsZodJson || references('_JsonValue')) {\n helpers.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n }\n if (needsZodJson) {\n helpers.push(\n `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)]));`,\n );\n }\n\n const generated = [...(helpers.length ? ['', ...helpers] : []), ...lines].join('\\n');\n const uses = (symbol: string) => new RegExp(`\\\\b${symbol}\\\\b`).test(generated);\n\n const body: string[] = [];\n\n body.push(...framework.imports(uses));\n\n // Services and model names come from the AST, which over-approximates two ways: a model with an\n // Input/Output variant contributes its base name even when only the variant is ever annotated,\n // and `collectServices`/`collectTypes` walk every operation including the `internal` ones\n // `includeInternal: false` drops. Filtering through `uses` — the same gate every symbol above\n // goes through — keeps the import list to what the handlers actually reference, so generated\n // code does not trip `noUnusedLocals` in the consuming project.\n for (const svc of services.filter(uses)) {\n const modulePath = root.services?.[svc] ?? root.meta[svc] ?? deriveModulePath(svc, options.servicePathTemplate);\n body.push(`import { ${svc} } from '${modulePath}';`);\n }\n\n const usedTypes = types.filter(uses);\n if (usedTypes.length > 0) {\n body.push(...generateTypeImports(usedTypes, root.file, options));\n }\n\n // luxon is needed for date/time/datetime (DateTime), duration (Duration) and interval (Interval);\n // the rendered Zod schemas and the service-result annotations both reference these classes.\n const luxonImports = ['DateTime', 'Duration', 'Interval'].filter(uses);\n if (luxonImports.length > 0) {\n body.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n }\n\n // Same `uses` gate: `Decimal` appears in the `_ZodDecimal` helper and in service-result\n // annotations via `serverTsScalar`, and the helper text is folded into `generated` above.\n if (uses('Decimal')) {\n body.push(DECIMAL_IMPORT);\n }\n\n if (uses('parseAndValidate')) {\n body.push(`import { parseAndValidate } from '@maroonedsoftware/zod';`);\n }\n\n if (uses('MultipartBody')) {\n body.push(`import { MultipartBody } from '@maroonedsoftware/multipart';`);\n }\n\n const allContent = [...body, ...(helpers.length ? ['', ...helpers] : []), ...lines].join('\\n');\n const needsZod = /\\bz\\./.test(allContent);\n return (needsZod ? `import { z } from 'zod';\\n` : '') + allContent;\n}\n\n// ─── Handler generation ────────────────────────────────────────────────────\n\nfunction generateHandler(route: OpRouteNode, op: OpOperationNode, root: OpRootNode, options: ResolvedOpCodegenOptions): string[] {\n const lines: string[] = [];\n const file = root.file;\n const outPath = options.outPath;\n const modelsWithInput = options.modelsWithInput;\n const framework = options.framework;\n\n lines.push('/**');\n\n // JSDoc from description\n const desc = op.description ?? route.description;\n if (desc) {\n for (const l of escapeJsDocLines(desc)) lines.push(` * ${l}`);\n }\n // Source location comment\n lines.push(` * from ${sourceLink(basename(file), outPath, file, op.loc.line)}`);\n\n // Security annotation (operation-level wins; falls back to route → file level)\n const effectiveSecurity = resolveSecurity(route, op, root);\n if (effectiveSecurity === SECURITY_NONE) {\n lines.push(` * anonymous access, no security required`);\n }\n\n // Modifier annotations\n const mods = resolveModifiers(route, op);\n if (mods.includes('internal')) lines.push(` * @internal`);\n if (mods.includes('deprecated')) lines.push(` * @deprecated`);\n\n lines.push('*/');\n\n const method = op.method;\n // The framework's placeholder syntax, from `{name}`, mapped to a valid identifier. Unlike a query\n // parameter or a header, a path placeholder's name never reaches the wire — the framework matches\n // by position — so renaming it is free, and it is what lets the params object be destructured.\n const path = route.path.replace(PATH_PARAM_RE_G, (_m, name: string) => framework.pathParam(toIdentifier(name)));\n const bodies = op.request?.bodies ?? [];\n const hasBody = bodies.length > 0;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n\n // Middleware list\n const middlewares: string[] = [];\n if (effectiveSecurity !== SECURITY_NONE) {\n const policy = effectiveSecurity?.policy;\n const args =\n policy === undefined\n ? ''\n : policy === false\n ? '{ policy: false }'\n : `{ policy: '${policy}' }`;\n middlewares.push(framework.middleware.policy(args));\n }\n if (hasBody) {\n const parserTokens = Array.from(new Set(bodies.map(b => bodyParserToken(b.contentType))));\n const tokensExpr = parserTokens.map(t => `'${t}'`).join(', ');\n middlewares.push(framework.middleware.bodyParser(tokensExpr));\n }\n if (op.signature) {\n const sigArgs = op.signaturePolicy\n ? `'${escapeSingleQuoted(op.signature)}', { policy: '${escapeSingleQuoted(op.signaturePolicy)}' }`\n : `'${escapeSingleQuoted(op.signature)}'`;\n middlewares.push(framework.middleware.signature(sigArgs));\n }\n lines.push(framework.routeOpen(deriveRouterName(file), method, path, middlewares));\n\n // Params / query / headers validation (request-side — use Input variants)\n const pathBindings =\n route.params?.kind === 'params' ? bindPathParams(route.params.nodes, framework.handlerLocals) : undefined;\n\n lines.push(...generateParamValidation(route.params, 'params', framework.request.params, route.paramsMode ?? 'strict', '', modelsWithInput, pathBindings));\n lines.push(...generateParamValidation(op.query, 'query', framework.request.query, op.queryMode ?? 'strict', '', modelsWithInput));\n lines.push(...generateParamValidation(op.headers, 'headers', framework.request.headers, op.headersMode ?? 'strip', '', modelsWithInput));\n\n // Body validation (request-side — use Input variants)\n if (hasBody && op.request) {\n if (isSingleMultipart) {\n lines.push(` const multipartBody = ${framework.request.parsedBody} as MultipartBody;`);\n lines.push('');\n } else if (bodies.length === 1) {\n lines.push(` const body = await parseAndValidate(${framework.request.parsedBody}, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n // All declared MIMEs share the same body shape — single validation suffices\n lines.push(` const body = await parseAndValidate(${framework.request.parsedBody}, ${renderInputType(bodies[0]!.bodyType, modelsWithInput)});`);\n lines.push('');\n } else {\n // Different body types per MIME — dispatch on Content-Type\n const annotation = bodies\n .map(b =>\n b.contentType === 'multipart/form-data' ? 'MultipartBody' : `z.infer<typeof ${renderInputType(b.bodyType, modelsWithInput)}>`,\n )\n .join(' | ');\n lines.push(` let body!: ${annotation};`);\n lines.push(` switch (${framework.request.contentType}) {`);\n for (const b of bodies) {\n lines.push(` case '${b.contentType}':`);\n if (b.contentType === 'multipart/form-data') {\n lines.push(` body = ${framework.request.parsedBody} as MultipartBody;`);\n } else {\n lines.push(` body = await parseAndValidate(${framework.request.parsedBody}, ${renderInputType(b.bodyType, modelsWithInput)});`);\n }\n lines.push(` break;`);\n }\n lines.push(` }`);\n lines.push('');\n }\n }\n\n // Service call. `emittedResponses` decides which of the declared statuses the service is\n // responsible for producing; the rest are documentation, or the thrown-error path.\n const emitted = emittedResponses(op);\n const serviceParts = inferService(op, route, file);\n const call = `await service.${serviceParts.methodName}(${buildArgs(route, op, pathBindings)})`;\n\n if (emitted.length > 1) {\n lines.push(...generateMultiStatusResult(emitted, serviceParts.className, call, options));\n } else {\n lines.push(...generateSingleStatusResult(emitted[0], op, serviceParts.className, call, options));\n }\n\n lines.push(...framework.routeClose());\n\n return lines;\n}\n\n/**\n * The service produces exactly one status (or none): the result is the body itself, or\n * `{ body, headers }` when the status declares headers, and the status code is a constant.\n *\n * A status declaring several mimes also gains a `contentType` the service picks, which is the\n * only thing here that can turn the response content type from a literal into an expression.\n */\nfunction generateSingleStatusResult(\n resp: OpResponseNode | undefined,\n op: OpOperationNode,\n className: string,\n call: string,\n options: ResolvedOpCodegenOptions,\n): string[] {\n const framework = options.framework;\n const lines: string[] = [];\n const bodies = resp ? resp.bodies : [];\n const respHeaders = resp?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersAnnotation = hasRespHeaders ? renderHeadersAnnotation(respHeaders, options.modelsWithOutput) : '';\n\n let bodySchema: string | undefined;\n\n if (bodies.length === 1) {\n const { annotation, prelude } = formatTypeAnnotation(bodies[0]!.bodyType, options.modelsWithOutput);\n if (prelude) lines.push(` ${prelude}`);\n bodySchema = responseBodySchema(bodies[0]!.bodyType, options, prelude ? 'resultType' : undefined);\n lines.push(` const service = ${framework.resolveService(className)};`);\n if (hasRespHeaders) {\n lines.push(` const result: { body: ${annotation}; headers: ${headersAnnotation} } = ${call};`);\n } else {\n lines.push(` const result: ${annotation} = ${call};`);\n }\n } else if (bodies.length > 1) {\n const rendered = renderResponseMembers(resp!, options, { includeStatus: false, varPrefix: 'result' });\n const { members, preludes } = rendered;\n bodySchema = rendered.bodySchema;\n for (const prelude of preludes) lines.push(` ${prelude}`);\n lines.push(` const service = ${framework.resolveService(className)};`);\n lines.push(` const result: ${members.join(' | ')} = ${call};`);\n } else {\n lines.push(` const service = ${framework.resolveService(className)};`);\n if (hasRespHeaders) {\n lines.push(` const result: { headers: ${headersAnnotation} } = ${call};`);\n } else {\n lines.push(` ${call};`);\n }\n }\n\n lines.push('');\n // 204 when the operation emits nothing. Falling back to the first *declared* status wrote an\n // error code on the success path, since a documentation-only block starts at a 4xx. 204 is\n // also what aligns the three generators: `observableResponses` excludes a bare `400:` too, so\n // the SDK already types such a method `Promise<void>` and `thrownResponses` puts the 400 in\n // `@throws`. A bodyless 204 success is exactly what `Promise<void>` means.\n lines.push(` ${framework.response.status(String(resp?.statusCode ?? 204))}`);\n lines.push(...headerSetLines(respHeaders, ' ', framework));\n\n if (bodies.length === 1) {\n lines.push(` ${framework.response.type(`'${bodies[0]!.contentType}'`)}`);\n lines.push(...indent(framework.response.send(responseBodyExpr(hasRespHeaders ? 'result.body' : 'result', bodySchema)), ' '));\n } else if (bodies.length > 1) {\n lines.push(` ${framework.response.type('result.contentType')}`);\n lines.push(...indent(framework.response.send(responseBodyExpr('result.body', bodySchema)), ' '));\n } else {\n // Nothing to write, but a framework that ends a response by returning still needs a statement.\n lines.push(...indent(framework.response.send(undefined), ' '));\n }\n\n return lines;\n}\n\n/**\n * The service chooses between several statuses: the result is a union discriminated on\n * `status`, and the handler switches on it so each status writes only its own headers, mime\n * and body.\n */\nfunction generateMultiStatusResult(emitted: OpResponseNode[], className: string, call: string, options: ResolvedOpCodegenOptions): string[] {\n const framework = options.framework;\n const lines: string[] = [];\n const members: string[] = [];\n const preludes: string[] = [];\n\n const bodySchemas = new Map<number, string | undefined>();\n\n for (const resp of emitted) {\n const rendered = renderResponseMembers(resp, options, { includeStatus: true, varPrefix: `result${resp.statusCode}` });\n members.push(...rendered.members);\n preludes.push(...rendered.preludes);\n bodySchemas.set(resp.statusCode, rendered.bodySchema);\n }\n\n for (const prelude of preludes) lines.push(` ${prelude}`);\n lines.push(` const service = ${framework.resolveService(className)};`);\n lines.push(` const result:`);\n for (const member of members) lines.push(` | ${member}`);\n lines.push(` = ${call};`);\n lines.push('');\n lines.push(` ${framework.response.status('result.status')}`);\n lines.push(` switch (result.status) {`);\n for (const resp of emitted) {\n lines.push(` case ${resp.statusCode}:`);\n lines.push(...headerSetLines(resp.headers ?? [], ' ', framework));\n if (resp.bodies.length > 0) {\n lines.push(` ${framework.response.type('result.contentType')}`);\n lines.push(...indent(framework.response.send(responseBodyExpr('result.body', bodySchemas.get(resp.statusCode))), ' '));\n } else {\n lines.push(...indent(framework.response.send(undefined), ' '));\n }\n lines.push(...indent(framework.response.caseEnd(), ' '));\n }\n lines.push(` }`);\n\n return lines;\n}\n\n/**\n * Render one status as the members of the service-result union — its `contentType`, `body` and\n * `headers`, plus `status` when the operation emits more than one.\n *\n * A status declaring several mimes collapses to a single member with a union of mime literals\n * when the bodies are structurally identical (`image/png` and `image/jpeg` both `binary`).\n * When they differ, it produces one member per mime so `contentType` and `body` stay correlated.\n */\nfunction renderResponseMembers(\n resp: OpResponseNode,\n options: OpCodegenOptions,\n opts: { includeStatus: boolean; varPrefix: string },\n): { members: string[]; preludes: string[]; bodySchema?: string } {\n const bodies = resp.bodies;\n const headers = resp.headers ?? [];\n const leading = opts.includeStatus ? [`status: ${resp.statusCode}`] : [];\n const trailing = headers.length > 0 ? [`headers: ${renderHeadersAnnotation(headers, options.modelsWithOutput)}`] : [];\n const preludes: string[] = [];\n\n if (bodies.length === 0) {\n return { members: [`{ ${[...leading, ...trailing].join('; ')} }`], preludes };\n }\n\n const uniform = bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType));\n if (uniform) {\n const { annotation, prelude } = formatTypeAnnotation(bodies[0]!.bodyType, options.modelsWithOutput, `${opts.varPrefix}Type`);\n if (prelude) preludes.push(prelude);\n const bodySchema = responseBodySchema(bodies[0]!.bodyType, options, prelude ? `${opts.varPrefix}Type` : undefined);\n const contentType = bodies.map(b => `'${b.contentType}'`).join(' | ');\n return {\n members: [`{ ${[...leading, `contentType: ${contentType}`, `body: ${annotation}`, ...trailing].join('; ')} }`],\n preludes,\n bodySchema,\n };\n }\n\n // One member per mime: `contentType` and `body` stay correlated, so validating would need a\n // second switch on `result.contentType` nested inside the status switch. Left unvalidated —\n // note the absent `bodySchema` in the return below.\n const members = bodies.map((b, i) => {\n const { annotation, prelude } = formatTypeAnnotation(b.bodyType, options.modelsWithOutput, `${opts.varPrefix}Type${i}`);\n if (prelude) preludes.push(prelude);\n return `{ ${[...leading, `contentType: '${b.contentType}'`, `body: ${annotation}`, ...trailing].join('; ')} }`;\n });\n return { members, preludes };\n}\n\nfunction renderHeadersAnnotation(headers: OpResponseHeaderNode[], modelsWithOutput?: Set<string>): string {\n const fields = headers.map(\n h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput, 'server')}`,\n );\n return `{ ${fields.join('; ')} }`;\n}\n\n/** Response-header writes for a status's declared headers, guarding the optional ones. */\nfunction headerSetLines(headers: OpResponseHeaderNode[], pad: string, framework: ServerFramework): string[] {\n return headers.map(h => {\n const accessor = `result.headers[${JSON.stringify(headerNameToProperty(h.name))}]`;\n const write = framework.response.header(h.name, `String(${accessor})`);\n return h.optional ? `${pad}if (${accessor} !== undefined) ${write}` : `${pad}${write}`;\n });\n}\n\n/** Prefix each of a framework's statements with the handler indentation the caller is writing at. */\nfunction indent(lines: string[], pad: string): string[] {\n return lines.map(line => `${pad}${line}`);\n}\n\n// ─── Inference helpers ─────────────────────────────────────────────────────\n\n/**\n * Resolve the service class and method a handler should delegate to.\n *\n * Uses the operation's explicit `service: Class.method` declaration when present; otherwise derives\n * the class from the contract file name (`ledger.categories.ck` → `LedgerCategoriesService`) and the\n * method from the HTTP verb and whether the path carries a parameter (`get` → `list` / `getById`).\n *\n * @param file Path of the `.ck` file the operation came from.\n */\nexport function inferService(op: OpOperationNode, route: OpRouteNode, file: string): { className: string; methodName: string } {\n // If explicitly declared: service: ServiceClass.methodName\n if (op.service) {\n const [cls = '', method] = op.service.split('.');\n return { className: cls, methodName: method ?? 'handle' };\n }\n\n // Infer from file name + method + path\n const baseName = deriveBaseName(file); // e.g. \"ledger.categories\" -> \"LedgerCategories\"\n const className = `${baseName}Service`;\n const methodName = inferMethodName(op.method, route.path);\n return { className, methodName };\n}\n\nfunction inferMethodName(method: string, path: string): string {\n const hasParam = path.includes('{');\n switch (method) {\n case 'get':\n return hasParam ? 'getById' : 'list';\n case 'post':\n return 'create';\n case 'put':\n return 'replace';\n case 'patch':\n return 'update';\n case 'delete':\n return 'delete';\n default:\n return 'handle';\n }\n}\n\n/**\n * Build the comma-separated argument list passed to the service method in a generated handler.\n *\n * Order is params, body, query, headers. Inline path params are spread as individual identifiers;\n * a referenced/compound params type is passed as a single `params` object. A lone\n * `multipart/form-data` request body is passed as `multipartBody` rather than `body`.\n *\n * @returns The rendered argument list, or an empty string when the method takes no arguments.\n */\nexport function buildArgs(route: OpRouteNode, op: OpOperationNode, bindings?: Map<string, string>): string {\n const args: string[] = [];\n // Path params: spread individually (inline) or pass 'params' object (type-ref/ContractTypeNode)\n if (route.params) {\n if (route.params.kind === 'params') {\n // `bindings` carries any rename the handler needed; the MCP generator passes none, since\n // its handlers bind different locals than a router's.\n args.push(...route.params.nodes.map(p => bindings?.get(p.name) ?? toIdentifier(p.name)));\n } else {\n args.push('params');\n }\n }\n // Body\n if (op.request && op.request.bodies.length > 0) {\n const bodies = op.request.bodies;\n const isSingleMultipart = bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data';\n args.push(isSingleMultipart ? 'multipartBody' : 'body');\n }\n // Query\n if (op.query) args.push('query');\n // Headers\n if (op.headers) args.push('headers');\n return args.join(', ');\n}\n\n/**\n * Map a `.ck` scalar to the TypeScript type a server handler sees, i.e. `z.infer` of the schema\n * `renderType` emits for that scalar. This is deliberately NOT `renderTsScalar` from ts-render:\n * that one describes the wire/SDK view (`binary` → `Blob`, dates → `string`), while the router\n * runs on Node against the parsed Zod output (`binary` → `Buffer`, dates → luxon `DateTime`).\n */\nfunction serverTsScalar(name: ScalarTypeNode['name']): string {\n switch (name) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n return 'string';\n case 'number':\n case 'int':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'decimal':\n // Unlike the date scalars, this matches `renderTsScalar`'s wire view — `_ZodDecimal`\n // has no output transform, so `z.infer` is a `Decimal` on both sides.\n return 'Decimal';\n case 'boolean':\n return 'boolean';\n case 'date':\n case 'time':\n case 'datetime':\n return 'DateTime';\n case 'duration':\n return 'Duration';\n case 'interval':\n // _ZodInterval transforms to an ISO string, so the inferred output type is string.\n return 'string';\n case 'binary':\n return 'Buffer';\n case 'json':\n return '_JsonValue';\n case 'object':\n return 'Record<string, unknown>';\n case 'null':\n return 'null';\n case 'unknown':\n return 'unknown';\n default: {\n const _exhaustive: never = name;\n throw new Error(`plugin-typescript: unmapped scalar '${String(_exhaustive)}' — add a case`);\n }\n }\n}\n\n/**\n * @param varName Name for the extracted schema variable. Distinct per status and per mime when\n * an operation emits several, so two complex bodies in one handler cannot collide.\n */\nfunction formatTypeAnnotation(bodyType: ContractTypeNode, modelsWithOutput?: Set<string>, varName = 'resultType'): { annotation: string; prelude?: string } {\n if (bodyType.kind === 'array') {\n const inner = formatTypeAnnotation(bodyType.item, modelsWithOutput, varName);\n return { annotation: `${inner.annotation}[]`, prelude: inner.prelude };\n }\n if (bodyType.kind === 'ref') {\n const name = modelsWithOutput?.has(bodyType.name) ? `${bodyType.name}Output` : bodyType.name;\n return { annotation: name };\n }\n if (bodyType.kind === 'scalar') return { annotation: serverTsScalar(bodyType.name) };\n // For complex types, extract schema into a variable so the result line stays readable\n const schema = renderType(bodyType);\n return {\n annotation: `z.infer<typeof ${varName}>`,\n prelude: `const ${varName} = ${schema};`,\n };\n}\n\n/**\n * Whether a response body can be soundly re-parsed through the schema `renderType` emits for it.\n *\n * False for anything transitively touching a model with a `format(...)` key transform — the service\n * returns the post-transform value while the schema expects the pre-transform one — and for an\n * intersection outside `renderIntersection`'s `.extend()` fast path, where `.and()` of two strict\n * objects rejects every value because each side sees the other's keys as unrecognized.\n */\nfunction isRevalidatable(type: ContractTypeNode, modelsWithOutput?: Set<string>, modelsWithTransform?: Set<string>): boolean {\n const rec = (t: ContractTypeNode): boolean => isRevalidatable(t, modelsWithOutput, modelsWithTransform);\n switch (type.kind) {\n case 'ref':\n return !modelsWithOutput?.has(type.name) && !modelsWithTransform?.has(type.name);\n case 'array':\n return rec(type.item);\n case 'tuple':\n return type.items.every(rec);\n case 'record':\n return rec(type.key) && rec(type.value);\n case 'intersection': {\n // Mirrors renderIntersection: a lone member renders as itself, `ref & (ref|object)*`\n // renders as an `.extend()` chain, and anything else falls back to `.and()`.\n const [first, ...rest] = type.members;\n if (!first) return true;\n if (rest.length === 0) return rec(first);\n const usesExtendChain = first.kind === 'ref' && rest.every(m => m.kind === 'ref' || m.kind === 'inlineObject');\n return usesExtendChain && type.members.every(rec);\n }\n case 'union':\n case 'discriminatedUnion':\n return type.members.every(rec);\n case 'inlineObject':\n return type.fields.every(f => rec(f.type));\n case 'lazy':\n return rec(type.inner);\n default:\n // scalar, enum, literal — identity or idempotent under re-parse\n return true;\n }\n}\n\n/**\n * The runtime schema a handler validates a response body against, or `undefined` when the body\n * cannot be soundly re-parsed and validation must be skipped.\n *\n * @param preludeVar The schema const {@link formatTypeAnnotation} already emitted for this body\n * (complex types only — `undefined` when it returned no prelude). Reusing it keeps a large object\n * literal from appearing twice in the same handler.\n */\nfunction responseBodySchema(bodyType: ContractTypeNode, options: OpCodegenOptions, preludeVar: string | undefined): string | undefined {\n if (!options.validateResponses) return undefined;\n if (!isRevalidatable(bodyType, options.modelsWithOutput, options.modelsWithTransform)) return undefined;\n return preludeVar ?? renderType(bodyType);\n}\n\n/**\n * The right-hand side of a response body write: the raw result expression, or a\n * `parseAndValidate` of it. The `500` is deliberate — a service returning a shape its own contract\n * rejects is a server fault, not a client one, and `@maroonedsoftware/zod` routes the field-level\n * detail to `internalDetails` (log-only) rather than the response body at 5xx.\n */\nfunction responseBodyExpr(value: string, schema: string | undefined): string {\n return schema ? `await parseAndValidate(${value}, ${schema}, 500)` : value;\n}\n\nfunction generateParamValidation(\n source: ParamSource | undefined,\n kind: ParamKind,\n sourceExpr: string,\n mode: ObjectMode,\n suffix = '',\n modelsWithInput?: Set<string>,\n bindings?: Map<string, string>,\n): string[] {\n if (!source) return [];\n const lines: string[] = [];\n const isQuery = kind === 'query';\n // Path params are destructured and spread into the service call; query and headers pass as\n // whole objects. The variable the block declares is named after the kind either way.\n const isPathParams = kind === 'params';\n if (source.kind === 'ref') {\n // Type reference — apply mode as a method call on the schema\n const typeName = modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;\n lines.push(` const ${kind} = await parseAndValidate(${sourceExpr}, ${typeName}.${mode}());`);\n lines.push('');\n } else if (source.kind === 'params') {\n // Inline param declarations — wrap with the appropriate z.*Object constructor\n if (source.nodes.length > 0) {\n const bind = (name: string) => (isPathParams ? toIdentifier(name) : name);\n // A path param whose binding was renamed is destructured under an alias, so the key the\n // framework supplies stays the declared one while the local is collision-free.\n const lhs = isPathParams\n ? `{ ${source.nodes\n .map(p => {\n const wire = bind(p.name);\n const local = bindings?.get(p.name) ?? wire;\n return wire === local ? wire : `${wire}: ${local}`;\n })\n .join(', ')} }`\n : kind;\n lines.push(` const ${lhs} = await parseAndValidate(`);\n lines.push(` ${sourceExpr},`);\n lines.push(` ${modeToWrapper(mode)}({`);\n for (const param of source.nodes) {\n // For path params the key must match the name in the route pattern above, which\n // is what the framework keys its params object by. For query and headers it is the\n // wire name, quoted when that is not an identifier — those the client actually sends.\n const bound = bind(param.name);\n const key = isValidIdentifier(bound) ? bound : `'${bound}'`;\n // Delegating to renderQueryType rather than hand-rolling the array preprocess here:\n // it is the same rule, and a second copy is a second thing to keep in sync. The\n // modifier chain then comes from the shared helper, so an inline param means the\n // same thing to the router as a model field does.\n const base = isQuery ? renderQueryType(param.type, modelsWithInput) : renderInputType(param.type, modelsWithInput);\n lines.push(` ${key}: ${applyFieldModifiers(base, param)},`);\n }\n lines.push(` })${suffix},`);\n lines.push(` );`);\n lines.push('');\n }\n } else {\n // ContractTypeNode — use query-aware rendering for query params (coerces single string → array),\n // otherwise use Input variant rendering; apply mode as a method call\n const schema = isQuery ? renderQueryType(source.node, modelsWithInput) : renderInputType(source.node, modelsWithInput);\n lines.push(` const ${kind} = await parseAndValidate(${sourceExpr}, (${schema}).${mode}());`);\n lines.push('');\n }\n return lines;\n}\n\n// ─── Type import resolution ────────────────────────────────────────────────\n\n/**\n * Generate per-file type import statements.\n * When modelOutPaths is available, groups types by their actual output file\n * and computes correct relative paths. Falls back to the template-based\n * single-import approach for types not found in the map.\n */\nfunction generateTypeImports(types: string[], opFile: string, options: OpCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n // Group types by their output file\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n // Emit one import per source file with a relative path\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import { ${names.sort().join(', ')} } from '${rel}';`);\n }\n\n // Fallback for types not in the map\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import { ${type} } from './${moduleName}.js';`);\n }\n } else {\n // No resolution context — fall back to template-based single import\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\n// ─── Collection helpers ────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of route.operations) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n for (const body of resp.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectOutputTypeNodeRefs(body.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'tuple':\n type.items.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'record':\n collectOutputTypeNodeRefs(type.key, out, modelsWithOutput);\n collectOutputTypeNodeRefs(type.value, out, modelsWithOutput);\n break;\n case 'union':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'intersection':\n type.members.forEach(t => collectOutputTypeNodeRefs(t, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'type') {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'record':\n collectInputTypeNodeRefs(type.key, out, modelsWithInput);\n collectInputTypeNodeRefs(type.value, out, modelsWithInput);\n break;\n case 'union':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'intersection':\n type.members.forEach(t => collectInputTypeNodeRefs(t, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n }\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\nfunction collectServices(root: OpRootNode): string[] {\n const services = new Set<string>();\n const inferredService = `${deriveBaseName(root.file)}Service`;\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (op.service) {\n services.add(op.service.split('.')[0] ?? op.service);\n } else {\n services.add(inferredService);\n }\n }\n }\n return [...services].sort();\n}\n\n\n\n\n\n\nfunction isValidIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\n/**\n * Derive the PascalCase base name used for router, service, and type names from a contract file path.\n *\n * Strips directories and the `.op`/`.ck` extension, then PascalCases each dot-separated segment\n * (`contracts/ledger.categories.ck` → `LedgerCategories`). Falls back to `Resource` for an empty path.\n */\nexport function deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n // ledger.categories -> LedgerCategories\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction deriveRouterName(file: string): string {\n return `${deriveBaseName(file)}Router`;\n}\n\n/**\n * Resolve the import specifier for a service class.\n *\n * Drops the trailing `Service` suffix and kebab-cases the remainder, then applies `template` if given\n * (`{name}` → `Ledger`, `{kebab}` → `ledger`). Without a template, defaults to\n * `#modules/<kebab>/<kebab>.service.js`.\n *\n * @param template Optional `servicePathTemplate` from the plugin config.\n */\nexport function deriveModulePath(serviceName: string, template?: string): string {\n // LedgerService -> #modules/ledger/ledger.service.js\n const base = serviceName.replace(/Service$/, '');\n const kebab = base.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`).replace(/^-/, '');\n if (template) {\n return template.replace(/\\{name\\}/g, base).replace(/\\{kebab\\}/g, kebab);\n }\n return `#modules/${kebab}/${kebab}.service.js`;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n","import type { ServerFramework } from './server-framework.js';\n\n/** Module the Koa flavour of ServerKit publishes its router and route middleware from. */\nconst KOA_RUNTIME_MODULE = '@maroonedsoftware/koa';\n\n/**\n * Symbols importable from {@link KOA_RUNTIME_MODULE}. Every one is a name the adapter itself emits,\n * so none can collide with a service class or router name derived from a contract.\n */\nconst KOA_RUNTIME_SYMBOLS = ['ServerKitRouter', 'bodyParserMiddleware', 'requirePolicy', 'requireSignature'] as const;\n\n/**\n * ServerKit on Koa: the router is a `@koa/router` instance, handlers take a single `ctx`, and a\n * response is written by assigning to `ctx.status` / `ctx.type` / `ctx.body` rather than returned.\n */\nexport const KOA_SERVER_FRAMEWORK: ServerFramework = {\n name: 'koa',\n\n imports(uses) {\n const symbols = KOA_RUNTIME_SYMBOLS.filter(uses);\n return symbols.length > 0 ? [`import { ${symbols.join(', ')} } from '${KOA_RUNTIME_MODULE}';`] : [];\n },\n\n routerDeclaration(routerName) {\n return `export const ${routerName} = ServerKitRouter();`;\n },\n\n pathParam(identifier) {\n return `:${identifier}`;\n },\n\n handlerLocals: ['ctx'],\n\n routeOpen(routerName, method, path, middlewares) {\n const middlewareStr = middlewares.length > 0 ? `, ${middlewares.join(', ')},` : ',';\n return `${routerName}.${method}('${path}'${middlewareStr} async ctx => {`;\n },\n\n routeClose() {\n return ['});'];\n },\n\n middleware: {\n policy(args) {\n return `requirePolicy(${args})`;\n },\n bodyParser(tokensExpr) {\n return `bodyParserMiddleware([${tokensExpr}])`;\n },\n signature(args) {\n return `requireSignature(${args})`;\n },\n },\n\n request: {\n params: 'ctx.params',\n query: 'ctx.query',\n headers: 'ctx.headers',\n // Not `ctx.request.body`: the ServerKit body parser drains the stream and writes its result\n // here, and in Koa `ctx.body` is the *response* body.\n parsedBody: 'ctx.parsedBody',\n // Koa strips the parameters off `Content-Type` for this accessor already.\n contentType: 'ctx.request.type',\n },\n\n resolveService(className) {\n return `ctx.container.get(${className})`;\n },\n\n response: {\n status(expr) {\n return `ctx.status = ${expr};`;\n },\n header(name, valueExpr) {\n return `ctx.set('${name}', ${valueExpr});`;\n },\n type(expr) {\n return `ctx.type = ${expr};`;\n },\n send(bodyExpr) {\n // A bodyless response needs no statement at all: Koa sends whatever `ctx.status` and the\n // headers say once the handler resolves.\n return bodyExpr === undefined ? [] : [`ctx.body = ${bodyExpr};`];\n },\n caseEnd() {\n return ['break;'];\n },\n },\n\n mcpRouter({ path }) {\n return `import { ServerKitRouter, bodyParserMiddleware, requireSignature } from '${KOA_RUNTIME_MODULE}';\nimport { McpDispatcher, createMcpRequestContext, MCP_AUTH_POLICY } from '@maroonedsoftware/mcp';\n\n/** Mount the MCP endpoint onto a ServerKit router. Bind \\`registerMcpTools\\` to the \\`McpToolHandlerMap\\` token. */\nexport function mountMcp(router: ReturnType<typeof ServerKitRouter>): void {\n router.post('${path}', bodyParserMiddleware(['json']), requireSignature('mcp', { policy: MCP_AUTH_POLICY }), async (ctx) => {\n const dispatcher = ctx.container.get(McpDispatcher);\n const context = createMcpRequestContext({ requestId: ctx.requestId, logger: ctx.logger });\n if (dispatcher.sessionMode === 'stateful') {\n ctx.respond = false;\n await dispatcher.dispatchStateful(\n { req: ctx.req, res: ctx.res, body: ctx.parsedBody, sessionId: ctx.get('mcp-session-id') },\n context,\n );\n } else {\n const response = await dispatcher.dispatch(JSON.parse(String(ctx.rawBody)), context);\n if (response) ctx.body = response;\n else ctx.status = 202; // a notification — nothing to return\n }\n });\n}\n`;\n },\n};\n","import type {\n OpRootNode,\n OpRouteNode,\n OpOperationNode,\n OpRequestBodyNode,\n OpResponseNode,\n OpResponseBodyNode,\n OpResponseHeaderNode,\n ContractTypeNode,\n ModelNode,\n OpParamNode,\n ParamSource,\n ScalarTypeNode,\n} from '@contractkit/core';\nimport { resolveModifiers, isJsonMime, classifyContentType, observableResponses, thrownResponses, PATH_PARAM_RE_G, toIdentifier } from '@contractkit/core';\nimport {\n renderInputTsType,\n renderOutputTsType,\n quoteKey,\n headerNameToProperty,\n escapeJsDocLines,\n sourceLink,\n JSON_VALUE_TYPE_DECL,\n} from './ts-render.js';\nimport { pascalToDotCase, typeNeedsScalar } from './codegen-contract.js';\nimport { bodyTypesStructurallyEqual } from './codegen-operation.js';\nimport { reviveFnName, renderInlineReviver, typeReachesDecimal, coerceDeclsFor, coerceLuxonImports } from './codegen-revive.js';\nimport { DECIMAL_IMPORT, DECIMAL_CONFIG_LINE } from './decimal-runtime.js';\nimport { basename, dirname, relative } from 'path';\n\n// ─── Body strategy ────────────────────────────────────────────────────────\n\ntype BodyStrategy =\n | { kind: 'none' }\n | { kind: 'single'; body: OpRequestBodyNode }\n | { kind: 'multi-equal'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-formdata-detect'; bodies: OpRequestBodyNode[] }\n | { kind: 'multi-required-arg'; bodies: OpRequestBodyNode[] };\n\n/** Serialize expression for a single MIME, given the source body var (e.g. 'body'). */\nfunction jsonOrFormSerialize(varName: string, contentType: string): string {\n if (contentType === 'application/x-www-form-urlencoded') {\n return `new URLSearchParams(${varName} as unknown as Record<string, string>).toString()`;\n }\n if (contentType === 'multipart/form-data') {\n return `(${varName} as FormData)`;\n }\n // application/json + any `+json` structured suffix — JSON.stringify with bigint support.\n return `JSON.stringify(${varName}, bigIntReplacer)`;\n}\n\n/**\n * Build a runtime expression that picks the right serialization based on a contentType variable.\n * Used by the SDK when the caller passes (or defaults to) a content-type at call time.\n */\nfunction renderSerializeExpr(varName: string, bodies: OpRequestBodyNode[], ctVar: string): string {\n // Build a chained ternary, last MIME is the fallback\n const arms = bodies.slice(0, -1);\n const last = bodies[bodies.length - 1]!;\n let expr = jsonOrFormSerialize(varName, last.contentType);\n for (let i = arms.length - 1; i >= 0; i--) {\n const arm = arms[i]!;\n expr = `${ctVar} === '${arm.contentType}' ? ${jsonOrFormSerialize(varName, arm.contentType)} : ${expr}`;\n }\n return expr;\n}\n\nfunction classifyBodyStrategy(op: OpOperationNode): BodyStrategy {\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 0) return { kind: 'none' };\n if (bodies.length === 1) return { kind: 'single', body: bodies[0]! };\n if (bodies.every(b => bodyTypesStructurallyEqual(b.bodyType, bodies[0]!.bodyType))) {\n return { kind: 'multi-equal', bodies };\n }\n if (bodies.some(b => b.contentType === 'multipart/form-data')) {\n return { kind: 'multi-formdata-detect', bodies };\n }\n return { kind: 'multi-required-arg', bodies };\n}\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/** Options shared by every SDK code-generation entry point. */\nexport interface SdkCodegenOptions {\n /** Template for type import paths when `modelOutPaths` is not provided. Supports `{module}` and `{base}`. */\n typeImportPathTemplate?: string;\n /** Absolute path of the file currently being generated. Used to compute relative imports. */\n outPath?: string;\n /** Map from model name → absolute output file path (for cross-module type imports) */\n modelOutPaths?: Map<string, string>;\n /** Absolute path to the shared sdk-options.ts file (if set, imports SdkOptions instead of defining inline) */\n sdkOptionsPath?: string;\n /** Set of model names that have Input variants (models with visibility modifiers) */\n modelsWithInput?: Set<string>;\n /** Set of model names that have Output variants (models with format(output=...)) */\n modelsWithOutput?: Set<string>;\n /** Model names carrying a `decimal`, whose response bodies need rehydrating client-side. */\n modelsWithDecimal?: Set<string>;\n /** Model names carrying a `bigint`, directly or transitively. Selects the JSON reviver. */\n modelsWithBigInt?: Set<string>;\n /** Every model in scope, for resolving discriminated-union members inside an inline reviver. */\n modelMap?: Map<string, ModelNode>;\n /**\n * Whether to emit SDK methods for operations marked `internal`. Defaults to `false` —\n * internal ops are omitted from the SDK so consumers don't pick them up. Set to `true`\n * to include them (e.g. for an internal-use SDK).\n */\n includeInternal?: boolean;\n /**\n * Override the generated client class name. When omitted, falls back to\n * `deriveClientClassName(root.file)` (the legacy per-file name). The aggregator\n * uses this to emit `<Area><Subarea>Client` for area+subarea leaf files.\n */\n clientClassName?: string;\n}\n\n/**\n * Returns true if the root contains at least one operation eligible for SDK emission.\n * With `includeInternal: false` (default) that means at least one non-internal op; with\n * `includeInternal: true` any op qualifies.\n */\nexport function hasPublicOperations(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (includeInternal || !resolveModifiers(route, op).includes('internal')) return true;\n }\n }\n return false;\n}\n\n/**\n * Generate a complete `*.client.ts` file for one operation root: imports, the client class\n * declaration, and one method per public operation. Used for top-level (no-area) files and\n * for subarea-leaf files. Area-level files are NOT routed through this — their methods get\n * inlined into the SDK aggregator via {@link generateClientMethods} + {@link generateSdkAggregator}.\n */\nexport function generateSdk(root: OpRootNode, options: SdkCodegenOptions = {}): string {\n const lines: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n\n const types = collectTypes(root, options.modelsWithInput, options.modelsWithOutput, includeInternal);\n const clientClassName = options.clientClassName ?? deriveClientClassName(root.file);\n\n // The method bodies are generated first so the imports can be read off them, the same way\n // codegen-operation decides its imports from the code it just emitted. A reviver import that\n // came from a predicate instead could drift and leave an unused local behind.\n const inlineRevivers = new Map<string, string[]>();\n const classBody: string[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n classBody.push('');\n classBody.push(...generateMethod(route, op, root.file, options, inlineRevivers));\n }\n }\n\n const inlineReviverDecls = [...inlineRevivers.values()].flat();\n const decimalPrelude = decimalPreludeFor(inlineReviverDecls);\n // Computed here rather than at its splice point below, so the import filter can see the\n // aliases: an error-body alias is a genuine reference to a model type.\n const errorAliases = generateErrorBodyAliases(root, options);\n\n // Type-only imports, plus the model revivers the methods actually call.\n //\n // `collectTypes` walks the AST and so reports every model a request body names, including one\n // carried by a `multipart/form-data` body — which `buildMethodParams` types as `FormData`, so\n // the model is never mentioned in the emitted code and its import is unused. Rather than\n // special-casing multipart in `collectTypes`, which validating multipart bodies would later\n // have to undo, keep only the types the emitted text actually names. This is the same\n // text-derived idiom the reviver imports already use just below.\n const referenced = referencedTypes(types, [...classBody, ...errorAliases, ...inlineReviverDecls]);\n if (referenced.length > 0) {\n lines.push(...generateTypeImports(referenced, root.file, options, usedRevivers(classBody)));\n }\n lines.push(...decimalPrelude.imports);\n const headerLuxon = headerLuxonImport(classBody, decimalPrelude.imports);\n if (headerLuxon) lines.push(headerLuxon);\n\n // SdkOptions import (from shared file) or inline fallback\n if (options.sdkOptionsPath && options.outPath) {\n let rel = relative(dirname(options.outPath), options.sdkOptionsPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const jsonImport = sdkNeedsJson(root, includeInternal) ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${rel}';`);\n const valueImports: string[] = [];\n if (sdkNeedsBigIntReplacer(root, includeInternal)) valueImports.push('bigIntReplacer');\n // Aliased rather than emitted at each call site: the method bodies are identical either\n // way, and the import line is where the choice is legible.\n if (sdkParsesJsonResponse(root, includeInternal)) {\n valueImports.push(sdkResponsesUseBigInt(root, options, includeInternal) ? 'parseJsonWithBigInt as parseJson' : 'parseJson');\n }\n if (sdkNeedsQueryString(root, includeInternal)) valueImports.push('buildQueryString');\n if (sdkNeedsReadContentType(root, includeInternal)) valueImports.push('readContentType');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${rel}';`);\n }\n } else {\n lines.push('');\n lines.push('export class SdkError<TBody = unknown> extends Error {');\n lines.push(' constructor(');\n lines.push(' public readonly status: number,');\n lines.push(' public readonly statusText: string,');\n lines.push(' public readonly body: TBody,');\n lines.push(' public readonly headers: Headers,');\n lines.push(' ) {');\n lines.push(' super(`${status} ${statusText}`);');\n lines.push(\" this.name = 'SdkError';\");\n lines.push(' }');\n lines.push('}');\n lines.push('');\n lines.push('export interface SdkRequestInit extends RequestInit {');\n lines.push(' /**');\n lines.push(' * Statuses this operation declares as values rather than errors — a 304 from');\n lines.push(' * conditional-GET middleware, or an error status the service returns deliberately.');\n lines.push(' * Anything else at or above 400 still throws SdkError.');\n lines.push(' */');\n lines.push(' expectStatuses?: number[];');\n lines.push('}');\n lines.push('');\n lines.push('export type SdkFetch = (url: string, init: SdkRequestInit) => Promise<Response>;');\n lines.push('');\n lines.push('export interface SdkOptions {');\n lines.push(' baseUrl: string;');\n lines.push(' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);');\n lines.push(' fetch?: SdkFetch;');\n lines.push(' /** Called once per request to produce a unique X-Request-ID header value */');\n lines.push(' requestIdFactory?: () => string;');\n lines.push('}');\n lines.push('');\n lines.push('export function readContentType(res: Response): string {');\n lines.push(\" return res.headers.get('content-type')?.split(';')[0]?.trim() ?? '';\");\n lines.push('}');\n lines.push('');\n lines.push('export function createSdkFetch(options: SdkOptions): SdkFetch {');\n lines.push(' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());');\n lines.push(' return async (url: string, init: SdkRequestInit): Promise<Response> => {');\n lines.push(\" const baseHeaders = typeof options.headers === 'function'\");\n lines.push(' ? await options.headers()');\n lines.push(' : options.headers ?? {};');\n lines.push(' const res = await fetch(`${options.baseUrl}${url}`, {');\n lines.push(' ...init,');\n lines.push(\" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\");\n lines.push(' });');\n lines.push(' if (!res.ok && !(init.expectStatuses ?? []).includes(res.status)) {');\n lines.push(' const text = await res.text();');\n lines.push(' let body: unknown;');\n lines.push(' try { body = JSON.parse(text); } catch { body = text; }');\n lines.push(' throw new SdkError(res.status, res.statusText, body, res.headers);');\n lines.push(' }');\n lines.push(' return res;');\n lines.push(' };');\n lines.push('}');\n lines.push('');\n lines.push('export function buildQueryString(query: object | undefined): string {');\n lines.push(' const searchParams = new URLSearchParams();');\n lines.push(' if (query) {');\n lines.push(' for (const [k, v] of Object.entries(query)) {');\n lines.push(' if (v === undefined || v === null) continue;');\n lines.push(' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }');\n lines.push(' else searchParams.set(k, String(v));');\n lines.push(' }');\n lines.push(' }');\n lines.push(' const qs = searchParams.toString();');\n lines.push(\" return qs ? `?${qs}` : '';\");\n lines.push('}');\n lines.push('');\n lines.push('export async function parseJson<T>(res: Response): Promise<T> {');\n lines.push(\n sdkResponsesUseBigInt(root, options, includeInternal)\n ? ' return JSON.parse(await res.text(), bigIntReviver) as T;'\n : ' return JSON.parse(await res.text()) as T;',\n );\n lines.push('}');\n }\n\n if (sdkNeedsJson(root, includeInternal) && !(options.sdkOptionsPath && options.outPath)) {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n\n lines.push('');\n\n if (errorAliases.length > 0) {\n lines.push(...errorAliases);\n lines.push('');\n }\n\n if (decimalPrelude.decls.length > 0) {\n lines.push('');\n lines.push(...decimalPrelude.decls);\n }\n\n // Wrappers for bodies with no `reviveX` of their own — an inline object, a record, a tuple.\n for (const decl of inlineRevivers.values()) {\n lines.push('');\n lines.push(...decl);\n }\n\n // Client class\n lines.push('/**');\n lines.push(` * generated from ${sourceLink(basename(root.file), options.outPath, root.file)}`);\n lines.push(' */');\n lines.push(`export class ${clientClassName} {`);\n lines.push(' constructor(private fetch: SdkFetch) {}');\n lines.push(...classBody);\n\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Render the method-block lines for an operation file as if they were declared inside a\n * client class.\n *\n * Skips operations marked `internal` unless `options.includeInternal` is set.\n *\n * @returns `lines`, one consolidated array pre-indented for class-body level with leading blank\n * lines between methods; `methodNames`, used by the caller to detect cross-file collisions when\n * several files contribute to the same area-level client; `preludeLines`, module-level\n * declarations the methods reference (decimal revivers and their `__dec` helper) which the caller\n * must splice in above the class; and `needsDecimalImport`, true when those declarations require\n * `import { Decimal } from 'decimal.js'` in the emitting file.\n */\nexport function generateClientMethods(\n root: OpRootNode,\n options: SdkCodegenOptions,\n): { lines: string[]; methodNames: string[]; preludeLines: string[]; needsDecimalImport: boolean } {\n const lines: string[] = [];\n const methodNames: string[] = [];\n const includeInternal = options.includeInternal ?? false;\n const inlineRevivers = new Map<string, string[]>();\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n lines.push('');\n lines.push(...generateMethod(route, op, root.file, options, inlineRevivers));\n methodNames.push(deriveMethodName(op, route));\n }\n }\n // Module-level declarations the methods reference, spliced above the class by the caller —\n // the same shape `generateErrorBodyAliases` already uses.\n const declLines = [...inlineRevivers.values()].flat();\n const { decls } = decimalPreludeFor(declLines);\n const preludeLines = [...(decls.length > 0 ? ['', ...decls] : []), ...[...inlineRevivers.values()].flatMap(decl => ['', ...decl])];\n return { lines, methodNames, preludeLines, needsDecimalImport: decls.length > 0 };\n}\n\n/**\n * Declarations a client file needs for the inline revivers it carries.\n *\n * An inline wrapper calls `__dec`, which is file-local to the *types* module and not exported, so\n * a client file that has one needs its own copy — along with the decimal.js import and the global\n * config, since nothing else in the file necessarily pulls them in.\n */\nfunction decimalPreludeFor(declLines: string[]): { imports: string[]; decls: string[] } {\n const decls = coerceDeclsFor(declLines);\n if (decls.length === 0) return { imports: [], decls: [] };\n\n const imports: string[] = [];\n const preamble: string[] = [];\n if (declLines.some(l => l.includes('__dec('))) {\n imports.push(DECIMAL_IMPORT);\n // The global config keeps decimals out of exponential notation; only decimal.js needs it.\n preamble.push(DECIMAL_CONFIG_LINE, '');\n }\n const luxon = coerceLuxonImports(declLines);\n if (luxon.length > 0) imports.push(`import { ${luxon.join(', ')} } from 'luxon';`);\n\n return { imports, decls: [...preamble, ...decls] };\n}\n\n/**\n * The `luxon` import a client needs for its response-header coercions, or undefined.\n *\n * Header conversions call `DateTime.fromISO` and friends directly rather than through a reviver,\n * so they are invisible to `decimalPreludeFor`. Decided from the emitted method bodies, like every\n * other import in these files, and skipped when the reviver prelude already brought luxon in.\n */\nfunction headerLuxonImport(methodLines: string[], existingImports: string[]): string | undefined {\n if (existingImports.some(l => l.includes(\"from 'luxon'\"))) return undefined;\n const needed = ['DateTime', 'Duration'].filter(c => methodLines.some(l => l.includes(`${c}.from`)));\n return needed.length > 0 ? `import { ${needed.join(', ')} } from 'luxon';` : undefined;\n}\n\n/** Model reviver names referenced by generated method bodies. `__revive…` wrappers are local. */\n/**\n * Narrow a collected type list to the names the emitted code actually mentions.\n *\n * Boundaries are spelled out rather than using `\\b`, so a model name containing `-`, `.` or `$`\n * is matched correctly. A name appearing only inside a doc string counts as a reference and the\n * import is kept: an unnecessary import is untidy, a missing one does not compile.\n */\nfunction referencedTypes(types: string[], emitted: string[]): string[] {\n const haystack = emitted.join('\\n');\n return types.filter(t => {\n const escaped = t.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp(`(?<![A-Za-z0-9_$])${escaped}(?![A-Za-z0-9_$])`).test(haystack);\n });\n}\n\nfunction usedRevivers(lines: string[]): string[] {\n const found = new Set<string>();\n for (const m of lines.join('\\n').matchAll(/\\brevive[A-Z]\\w*/g)) found.add(m[0]);\n return [...found].sort();\n}\n\n// ─── Method generation ────────────────────────────────────────────────────\n\nfunction generateMethod(\n route: OpRouteNode,\n op: OpOperationNode,\n file: string,\n options: SdkCodegenOptions,\n inlineRevivers?: Map<string, string[]>,\n): string[] {\n const revive: ReviveContext | undefined =\n options.modelsWithDecimal && options.modelsWithDecimal.size > 0 && inlineRevivers\n ? {\n modelsWithDecimal: options.modelsWithDecimal,\n modelsWithOutput: options.modelsWithOutput,\n modelMap: options.modelMap,\n inlineRevivers,\n nameHint: '',\n }\n : undefined;\n const lines: string[] = [];\n const methodName = deriveMethodName(op, route);\n /** Identifies the operation in a codegen rejection, which the CLI scopes to this plugin. */\n const where = `${op.method.toUpperCase()} ${route.path}`;\n const mRevive = hint(revive, `${methodName.charAt(0).toUpperCase()}${methodName.slice(1)}`);\n const httpMethod = op.method.toUpperCase();\n const { modelsWithInput, modelsWithOutput } = options;\n\n // Build method parameters (request-side — use Input variants)\n const params = buildMethodParams(route, op, modelsWithInput);\n const paramStr = params.map(p => `${p.name}${p.optional ? '?' : ''}: ${p.type}`).join(', ');\n\n // Determine return type — response side uses Output variants (post-transform wire shape).\n // For non-JSON responses the schema is ignored: text/* is read as string, binary as Blob.\n //\n // `observableResponses` is the client-side mirror of the router's `emittedResponses`: it also\n // covers statuses the service never writes but a client can still receive, such as a 304 from\n // conditional-GET middleware. Anything left over reaches the caller as a thrown SdkError.\n const observable = observableResponses(op);\n const thrown = thrownResponses(op);\n const isMultiStatus = observable.length > 1;\n const primaryResponse = observable[0];\n const primaryBodies = primaryResponse ? primaryResponse.bodies : [];\n const isVoid = primaryBodies.length === 0;\n const respHeaders = primaryResponse?.headers ?? [];\n const hasRespHeaders = respHeaders.length > 0;\n const headersShape = hasRespHeaders ? renderSdkHeadersShape(respHeaders, modelsWithOutput) : '';\n\n // A union of more than one member is broken across lines — a four-status operation runs to\n // several hundred characters on one line otherwise.\n let returnMembers: string[] | undefined;\n let returnType = '';\n if (isMultiStatus) {\n returnMembers = observable.flatMap(r => sdkResponseMembers(r, modelsWithOutput, true));\n } else if (primaryBodies.length > 1) {\n returnMembers = sdkResponseMembers(primaryResponse!, modelsWithOutput, false);\n } else {\n const dataType = isVoid ? 'void' : sdkDataType(primaryBodies[0]!, modelsWithOutput);\n returnType = hasRespHeaders ? (isVoid ? `{ headers: ${headersShape} }` : `{ data: ${dataType}; headers: ${headersShape} }`) : dataType;\n }\n if (returnMembers?.length === 1) {\n returnType = returnMembers[0]!;\n returnMembers = undefined;\n }\n\n // Statuses the shared fetch would otherwise reject. All-2xx operations pass nothing, so the\n // overwhelmingly common case keeps its existing call shape.\n const expectStatuses = observable.filter(r => r.statusCode < 200 || r.statusCode >= 300).map(r => r.statusCode);\n\n // JSDoc\n const desc = op.description ?? route.description;\n const errorBodyName = thrown.some(r => r.bodies.length > 0) ? errorBodyTypeName(route, op) : undefined;\n // `@deprecated` belongs in this block rather than in one of its own: TypeScript honours only\n // the JSDoc comment adjacent to the declaration, so a separate `/** @deprecated */` above a\n // description block is dropped by editors entirely. Tag order mirrors the router's.\n const deprecated = resolveModifiers(route, op).includes('deprecated');\n if (op.name || desc || errorBodyName || deprecated) {\n const tags: string[] = [];\n if (op.name) tags.push(`@name ${op.name}`);\n if (desc) tags.push(`@description ${desc}`);\n if (errorBodyName) tags.push(`@throws {SdkError<${errorBodyName}>} on ${thrown.map(r => r.statusCode).join(', ')}`);\n if (deprecated) tags.push('@deprecated');\n const contentLines = tags.flatMap(t => escapeJsDocLines(t));\n if (contentLines.length === 1) {\n lines.push(` /** ${contentLines[0]} */`);\n } else {\n lines.push(` /**`);\n for (const l of contentLines) lines.push(` * ${l}`);\n lines.push(` */`);\n }\n }\n\n if (returnMembers) {\n lines.push(` async ${methodName}(${paramStr}): Promise<`);\n for (const member of returnMembers) lines.push(` | ${member}`);\n lines.push(` > {`);\n } else {\n lines.push(` async ${methodName}(${paramStr}): Promise<${returnType}> {`);\n }\n\n // Build URL with path params\n const urlExpr = buildUrlExpression(route.path, route.params);\n\n // Query string\n const hasQuery = !!op.query;\n let fetchUrl = urlExpr;\n if (hasQuery) {\n lines.push(` const qs = buildQueryString(query);`);\n fetchUrl = urlExpr;\n }\n\n // Build fetch options\n const strategy = classifyBodyStrategy(op);\n const hasBody = strategy.kind !== 'none';\n const hasOpHeaders = !!op.headers;\n\n // Pre-emit serialization preludes for multi-MIME strategies\n if (strategy.kind === 'multi-equal') {\n const defaultCt = strategy.bodies[0]!.contentType;\n lines.push(` const __contentType = options?.contentType ?? '${defaultCt}';`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n } else if (strategy.kind === 'multi-formdata-detect') {\n lines.push(` const __isFormData = body instanceof FormData;`);\n const nonMultipart = strategy.bodies.find(b => b.contentType !== 'multipart/form-data')!;\n lines.push(` const __contentType: string = __isFormData ? 'multipart/form-data' : '${nonMultipart.contentType}';`);\n lines.push(\n ` const __serialized: BodyInit = __isFormData ? (body as FormData) : ${jsonOrFormSerialize('body', nonMultipart.contentType)};`,\n );\n } else if (strategy.kind === 'multi-required-arg') {\n lines.push(` const __contentType = options.contentType;`);\n lines.push(` const __serialized = ${renderSerializeExpr('body', strategy.bodies, '__contentType')};`);\n }\n\n const fetchArgs: string[] = [];\n\n if (hasQuery) {\n fetchArgs.push(`url: \\`${fetchUrl}\\${qs}\\``);\n } else {\n fetchArgs.push(`url: \\`${fetchUrl}\\``);\n }\n\n fetchArgs.push(`method: '${httpMethod}'`);\n\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n // FormData supplies its own Content-Type with boundary; don't override it.\n fetchArgs.push('body: body');\n } else if (cat === 'urlencoded') {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: new URLSearchParams(body as unknown as Record<string, string>).toString()');\n } else if (cat === 'text' || cat === 'binary') {\n // text/* and binary mimes pass the body through to fetch as-is — no schema serialization.\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: body');\n } else {\n fetchArgs.push(`headers: { 'Content-Type': '${body.contentType}' }`);\n fetchArgs.push('body: JSON.stringify(body, bigIntReplacer)');\n }\n } else if (hasBody) {\n // multi-equal | multi-formdata-detect | multi-required-arg — share a __contentType / __serialized prelude\n fetchArgs.push(`headers: { 'Content-Type': __contentType }`);\n fetchArgs.push('body: __serialized');\n }\n\n if (hasOpHeaders) {\n const lastHeaderIdx = fetchArgs.findIndex(a => a.startsWith('headers:'));\n if (lastHeaderIdx !== -1) {\n const existing = fetchArgs[lastHeaderIdx]!;\n const inner = existing.slice('headers: '.length).replace(/^\\{\\s*|\\s*\\}$/g, '');\n fetchArgs[lastHeaderIdx] = `headers: { ${inner}, ...customHeaders }`;\n } else {\n fetchArgs.push('headers: customHeaders');\n }\n }\n\n if (expectStatuses.length > 0) fetchArgs.push(`expectStatuses: [${expectStatuses.join(', ')}]`);\n\n const needsResult = isMultiStatus || !isVoid || hasRespHeaders;\n const resultPrefix = needsResult ? 'const result = ' : '';\n if (fetchArgs.length === 2 && !hasBody && !hasOpHeaders && !hasQuery) {\n // Simple case — inline\n lines.push(` ${resultPrefix}await this.fetch(\\`${fetchUrl}\\`, { method: '${httpMethod}' });`);\n } else {\n lines.push(` ${resultPrefix}await this.fetch(${fetchArgs[0]!.split(': ').slice(1).join(': ')}, {`);\n for (let i = 1; i < fetchArgs.length; i++) {\n lines.push(` ${fetchArgs[i]},`);\n }\n lines.push(` });`);\n }\n\n if (isMultiStatus) {\n // The status is only known at runtime, so the caller gets a union to narrow. The lowest\n // status is the default branch, which keeps the function exhaustively returning.\n const [fallback, ...rest] = observable;\n lines.push(` switch (result.status) {`);\n for (const resp of rest) {\n lines.push(` case ${resp.statusCode}:`);\n lines.push(...sdkReturnLines(resp, modelsWithOutput, ' ', true, mRevive, where));\n }\n lines.push(` default:`);\n lines.push(...sdkReturnLines(fallback!, modelsWithOutput, ' ', true, mRevive, where));\n lines.push(` }`);\n } else if (primaryBodies.length > 1) {\n lines.push(...sdkReturnLines(primaryResponse!, modelsWithOutput, ' ', false, mRevive, where));\n } else if (hasRespHeaders) {\n const headerEntries = sdkHeaderEntries(respHeaders, where);\n if (isVoid) {\n lines.push(` return { headers: { ${headerEntries} } };`);\n } else {\n lines.push(` const data = ${sdkReadExpr(primaryBodies[0]!, modelsWithOutput, hint(mRevive, primaryResponse!.statusCode))};`);\n lines.push(` return { data, headers: { ${headerEntries} } };`);\n }\n } else if (!isVoid) {\n lines.push(` return ${sdkReadExpr(primaryBodies[0]!, modelsWithOutput, hint(mRevive, primaryResponse!.statusCode))};`);\n }\n\n lines.push(' }');\n\n return lines;\n}\n\n// ─── Response shapes ──────────────────────────────────────────────────────\n\n/** The TypeScript type a client sees for one response body. */\nfunction sdkDataType(body: OpResponseBodyNode, modelsWithOutput?: Set<string>): string {\n const category = classifyContentType(body.contentType);\n if (category === 'text') return 'string';\n if (category === 'binary') return 'Blob';\n return renderOutputTsType(body.bodyType, modelsWithOutput);\n}\n\n/**\n * How a client reads one response body off the `Response`.\n *\n * A decimal-bearing body is wrapped in its reviver: `parseJson` is a bare cast, so without this the\n * type would say `Decimal` while the runtime held a string. Bodies with no decimal are emitted\n * byte-identically to before.\n */\nfunction sdkReadExpr(body: OpResponseBodyNode, modelsWithOutput?: Set<string>, revive?: ReviveContext): string {\n const category = classifyContentType(body.contentType);\n if (category === 'text') return 'await result.text()';\n if (category === 'binary') return 'await result.blob()';\n const tsType = renderOutputTsType(body.bodyType, modelsWithOutput);\n const read = `await parseJson<${tsType}>(result)`;\n const reviver = reviveExprFor(body.bodyType, revive);\n if (!reviver) return read;\n // `.map` over an array of refs rather than a wrapper function: the reviver returns the same\n // object it mutated, so the mapped array holds the same elements.\n return reviver.kind === 'array' ? `(${read}).map(${reviver.name})` : `${reviver.name}(${read})`;\n}\n\n/**\n * Extend the inline-reviver name with one more path segment.\n *\n * Built up compositionally — method, then status, then mime index — because each of those lives in\n * a different function, and the resulting name has to be distinct per body: two operations with\n * different inline decimal bodies must not share one wrapper.\n */\nfunction hint(revive: ReviveContext | undefined, segment: string | number): ReviveContext | undefined {\n if (!revive) return undefined;\n return { ...revive, nameHint: `${revive.nameHint}${segment}` };\n}\n\n/** What `sdkReadExpr` needs to decide whether a body has to be revived, and with which function. */\ninterface ReviveContext {\n modelsWithDecimal: Set<string>;\n /** Which scalars need rehydrating; see `ReviveCodegenOptions.revivableScalars`. */\n revivableScalars?: ReadonlySet<ScalarTypeNode['name']>;\n modelsWithOutput?: Set<string>;\n /** Inline reviver declarations accumulated for the current file, keyed by function name. */\n inlineRevivers: Map<string, string[]>;\n modelMap?: Map<string, ModelNode>;\n /** Distinguishes the inline wrapper emitted for each body. */\n nameHint: string;\n}\n\n/** The reviver to apply to a response body, or `null` when the body holds nothing to rehydrate. */\nfunction reviveExprFor(bodyType: ContractTypeNode, ctx: ReviveContext | undefined): { name: string; kind: 'value' | 'array' } | null {\n if (!ctx || ctx.modelsWithDecimal.size === 0) return null;\n const opts = {\n modelsWithDecimal: ctx.modelsWithDecimal,\n revivableScalars: ctx.revivableScalars,\n modelsWithOutput: ctx.modelsWithOutput,\n modelMap: ctx.modelMap,\n };\n if (!typeReachesDecimal(bodyType, opts)) return null;\n\n const refName = (t: ContractTypeNode): string | null => (t.kind === 'ref' ? t.name : t.kind === 'lazy' ? refName(t.inner) : null);\n const pick = (name: string) => reviveFnName(name, ctx.modelsWithOutput?.has(name) ? 'output' : 'base');\n\n const direct = refName(bodyType);\n if (direct && ctx.modelsWithDecimal.has(direct)) return { name: pick(direct), kind: 'value' };\n\n if (bodyType.kind === 'array') {\n const item = refName(bodyType.item);\n if (item && ctx.modelsWithDecimal.has(item)) return { name: pick(item), kind: 'array' };\n }\n\n // Anything else — an inline object, a record, a tuple — has no `reviveX` to call, so the file\n // gets a wrapper of its own.\n const fnName = `__revive${ctx.nameHint}`;\n if (!ctx.inlineRevivers.has(fnName)) {\n const decl = renderInlineReviver(fnName, renderOutputTsType(bodyType, ctx.modelsWithOutput), bodyType, opts);\n if (!decl) return null;\n ctx.inlineRevivers.set(fnName, decl);\n }\n return { name: fnName, kind: 'value' };\n}\n\nfunction renderSdkHeadersShape(headers: OpResponseHeaderNode[], modelsWithOutput?: Set<string>): string {\n const fields = headers.map(\n h => `${quoteKey(headerNameToProperty(h.name))}${h.optional ? '?' : ''}: ${renderOutputTsType(h.type, modelsWithOutput)}`,\n );\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * The value expression for one response header, matching the type `renderSdkHeadersShape` gives it.\n *\n * Header values always arrive as strings, but the shape is typed from the contract — so a header\n * declared `int` was typed `number` and assigned `string | undefined`, and a required one was\n * typed `T` and assigned `T | undefined`. Both are `TS2322`, in opposite directions.\n *\n * `null` is what `Headers.get` returns for an absent header. A required header is asserted rather\n * than defaulted, because the contract says the service always sends it; an optional one maps the\n * absence onto `undefined`, which is what its `?` in the shape means.\n *\n * Anything that is not one of the scalars below cannot be read from a header at all, and is\n * rejected here rather than emitted as code that does not compile. The list is shared with the\n * Python SDK, except that temporals need coercion there — `renderPyType` maps them to `datetime`\n * objects, while `renderOutputTsType` maps them to `string`.\n */\nfunction sdkHeaderEntry(h: OpResponseHeaderNode, where: string): string {\n const raw = `result.headers.get('${h.name}')`;\n const key = quoteKey(headerNameToProperty(h.name));\n const scalar = h.type.kind === 'scalar' ? h.type.name : undefined;\n\n /**\n * Wrap a conversion so an optional header maps an absent value onto `undefined`.\n *\n * The value is asserted non-null in both branches. TypeScript does not carry a narrowing from\n * `get(x) === null` across a *second* `get(x)` call, and the conversions below take a `string`\n * — so without the assertion the optional form is a TS2345 even though the ternary has\n * already excluded null.\n */\n const convert = (expr: (v: string) => string) =>\n `${key}: ${h.optional ? `${raw} === null ? undefined : ${expr(`${raw}!`)}` : expr(`${raw}!`)}`;\n\n switch (scalar) {\n case 'string':\n case 'email':\n case 'url':\n case 'uuid':\n case 'interval':\n case 'unknown':\n return `${key}: ${raw}${h.optional ? ' ?? undefined' : '!'}`;\n // Temporals are Luxon objects since the SDK started reviving them, so the shape\n // `renderOutputTsType` produces says `DateTime` and the raw string no longer satisfies it.\n // The format for date and time comes from the contract, as it does in the reviver.\n case 'datetime':\n return convert(v => `DateTime.fromISO(${v})`);\n case 'duration':\n return convert(v => `Duration.fromISO(${v})`);\n case 'date':\n return convert(v => `DateTime.fromFormat(${v}, '${(h.type.kind === 'scalar' && h.type.format) || 'yyyy-MM-dd'}')`);\n case 'time':\n return convert(v => `DateTime.fromFormat(${v}, '${(h.type.kind === 'scalar' && h.type.format) || 'HH:mm:ss'}')`);\n case 'number':\n case 'int':\n return `${key}: ${h.optional ? `${raw} === null ? undefined : Number(${raw})` : `Number(${raw})`}`;\n case 'boolean':\n return `${key}: ${h.optional ? `${raw} === null ? undefined : ${raw} === 'true'` : `${raw} === 'true'`}`;\n case 'bigint':\n return convert(v => `BigInt(${v})`);\n default:\n throw new Error(\n `Response header '${h.name}' on ${where} is declared as ${describeHeaderType(h.type)}, which cannot be read from an HTTP header. ` +\n `Header values arrive as strings — declare it as string, email, url, uuid, a date/time type, int, number, boolean or bigint.`,\n );\n }\n}\n\n/** A short, contract-facing description of a header type, for the rejection message above. */\nfunction describeHeaderType(type: ContractTypeNode): string {\n return type.kind === 'scalar' ? `the '${type.name}' scalar` : type.kind === 'ref' ? `the model '${type.name}'` : `${type.kind === 'array' ? 'an' : 'a'} ${type.kind}`;\n}\n\nfunction sdkHeaderEntries(headers: OpResponseHeaderNode[], where: string): string {\n return headers.map(h => sdkHeaderEntry(h, where)).join(', ');\n}\n\n/**\n * Render one response as the members of the client's return union — the mirror of the router's\n * service-result members, with `data` in place of `body`.\n *\n * Collapses to a single member with a union of mime literals when every declared mime yields the\n * same data type; otherwise one member per mime, so `contentType` and `data` stay correlated.\n */\nfunction sdkResponseMembers(resp: OpResponseNode, modelsWithOutput: Set<string> | undefined, includeStatus: boolean): string[] {\n const bodies = resp.bodies;\n const headers = resp.headers ?? [];\n const leading = includeStatus ? [`status: ${resp.statusCode}`] : [];\n const trailing = headers.length > 0 ? [`headers: ${renderSdkHeadersShape(headers, modelsWithOutput)}`] : [];\n\n if (bodies.length === 0) {\n return [`{ ${[...leading, ...trailing].join('; ')} }`];\n }\n\n const dataTypes = bodies.map(b => sdkDataType(b, modelsWithOutput));\n if (dataTypes.every(t => t === dataTypes[0])) {\n const contentType = bodies.map(b => `'${b.contentType}'`).join(' | ');\n return [`{ ${[...leading, `contentType: ${contentType}`, `data: ${dataTypes[0]}`, ...trailing].join('; ')} }`];\n }\n return bodies.map((b, i) => `{ ${[...leading, `contentType: '${b.contentType}'`, `data: ${dataTypes[i]}`, ...trailing].join('; ')} }`);\n}\n\n/** The `return` statement(s) that build one response's member of the return union. */\nfunction sdkReturnLines(\n resp: OpResponseNode,\n modelsWithOutput: Set<string> | undefined,\n indent: string,\n includeStatus: boolean,\n revive: ReviveContext | undefined,\n where: string,\n): string[] {\n const bodies = resp.bodies;\n const headers = resp.headers ?? [];\n const leading = includeStatus ? [`status: ${resp.statusCode}`] : [];\n const trailing = headers.length > 0 ? [`headers: { ${sdkHeaderEntries(headers, where)} }`] : [];\n\n if (bodies.length === 0) {\n return [`${indent}return { ${[...leading, ...trailing].join(', ')} };`];\n }\n if (bodies.length === 1) {\n const fields = [\n ...leading,\n `contentType: '${bodies[0]!.contentType}'`,\n `data: ${sdkReadExpr(bodies[0]!, modelsWithOutput, hint(revive, resp.statusCode))}`,\n ...trailing,\n ];\n return [`${indent}return { ${fields.join(', ')} };`];\n }\n\n const dataTypes = bodies.map(b => sdkDataType(b, modelsWithOutput));\n if (dataTypes.every(t => t === dataTypes[0])) {\n // Every mime reads the same way, so only the label has to come off the wire.\n const cast = bodies.map(b => `'${b.contentType}'`).join(' | ');\n const fields = [\n ...leading,\n `contentType: readContentType(result) as ${cast}`,\n `data: ${sdkReadExpr(bodies[0]!, modelsWithOutput, hint(revive, resp.statusCode))}`,\n ...trailing,\n ];\n return [`${indent}return { ${fields.join(', ')} };`];\n }\n\n // The mimes read differently, so the client has to dispatch on what actually came back.\n const lines = [`${indent}switch (readContentType(result)) {`];\n for (const [i, body] of bodies.slice(1).entries()) {\n const fields = [\n ...leading,\n `contentType: '${body.contentType}'`,\n `data: ${sdkReadExpr(body, modelsWithOutput, hint(revive, `${resp.statusCode}_${i + 1}`))}`,\n ...trailing,\n ];\n lines.push(`${indent} case '${body.contentType}':`);\n lines.push(`${indent} return { ${fields.join(', ')} };`);\n }\n const first = bodies[0]!;\n const fallbackFields = [\n ...leading,\n `contentType: '${first.contentType}'`,\n `data: ${sdkReadExpr(first, modelsWithOutput, hint(revive, `${resp.statusCode}_0`))}`,\n ...trailing,\n ];\n lines.push(`${indent} default:`);\n lines.push(`${indent} return { ${fallbackFields.join(', ')} };`);\n lines.push(`${indent}}`);\n return lines;\n}\n\n// ─── Error body typing ────────────────────────────────────────────────────\n\nfunction errorBodyTypeName(route: OpRouteNode, op: OpOperationNode): string {\n const method = deriveMethodName(op, route);\n return `${method.charAt(0).toUpperCase()}${method.slice(1)}ErrorBody`;\n}\n\n/**\n * Module-level `…ErrorBody` aliases for every operation whose thrown statuses declare a body.\n *\n * TypeScript cannot type a `throw`, so the alias plus the method's `@throws` tag is as far as the\n * error contract can be carried: it gives callers something to narrow `SdkError.body` to instead\n * of leaving them with `unknown`.\n */\nexport function generateErrorBodyAliases(root: OpRootNode, options: SdkCodegenOptions): string[] {\n const includeInternal = options.includeInternal ?? false;\n const lines: string[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n const mods = resolveModifiers(route, op);\n if (!includeInternal && mods.includes('internal')) continue;\n const types = new Set<string>();\n for (const resp of thrownResponses(op)) {\n for (const body of resp.bodies) types.add(sdkDataType(body, options.modelsWithOutput));\n }\n if (types.size === 0) continue;\n lines.push(`export type ${errorBodyTypeName(route, op)} = ${[...types].join(' | ')};`);\n }\n }\n return lines;\n}\n\n// ─── URL building ─────────────────────────────────────────────────────────\n\n/**\n * Render a route path as the template-literal body that produces the request URL.\n *\n * `params` says where each value lives. `buildMethodParams` spreads a `params { … }` block across\n * the signature, so those interpolate by bare name; but for `params: SomeModel` it emits a single\n * argument called `params`, and interpolating the bare name then refers to nothing that exists.\n *\n * The placeholder pattern matches what the `.ck` grammar allows rather than just\n * `[a-zA-Z_]\\w*`, so a hyphenated `{payment-id}` is interpolated instead of being left in the URL\n * verbatim. Such a name is not a valid property accessor either, hence the bracket form.\n */\nfunction buildUrlExpression(path: string, params?: ParamSource): string {\n return path.replace(PATH_PARAM_RE_G, (_m, name: string) => {\n // Spread across the signature: interpolate the identifier `buildMethodParams` bound.\n if (!params || params.kind === 'params') return `\\${encodeURIComponent(${toIdentifier(name)})}`;\n // Behind one `params` argument: read the model's field, which keeps its declared spelling\n // and so may need bracket access. `String(...)` because that field may be typed something\n // `encodeURIComponent` does not accept.\n const access = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? `params.${name}` : `params[${JSON.stringify(name)}]`;\n return `\\${encodeURIComponent(String(${access}))}`;\n });\n}\n\n// ─── Method parameters ────────────────────────────────────────────────────\n\ninterface MethodParam {\n name: string;\n type: string;\n optional: boolean;\n}\n\nfunction buildMethodParams(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): MethodParam[] {\n const params: MethodParam[] = [];\n\n // Path params — always first, always required (request-side — use Input variants)\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const p of route.params.nodes) {\n params.push({ name: toIdentifier(p.name), type: renderInputTsType(p.type, modelsWithInput), optional: false });\n }\n } else if (route.params.kind === 'ref') {\n const typeName = modelsWithInput?.has(route.params.name) ? `${route.params.name}Input` : route.params.name;\n params.push({ name: 'params', type: typeName, optional: false });\n } else {\n params.push({ name: 'params', type: renderInputTsType(route.params.node, modelsWithInput), optional: false });\n }\n }\n\n // Body (request-side — use Input variants)\n const strategy = classifyBodyStrategy(op);\n if (strategy.kind === 'single') {\n const body = strategy.body;\n const cat = classifyContentType(body.contentType);\n if (cat === 'multipart') {\n params.push({ name: 'body', type: 'FormData', optional: false });\n } else if (cat === 'text') {\n params.push({ name: 'body', type: 'string', optional: false });\n } else if (cat === 'binary') {\n params.push({ name: 'body', type: 'Blob | ArrayBuffer | Uint8Array | string', optional: false });\n } else {\n params.push({ name: 'body', type: renderInputTsType(body.bodyType, modelsWithInput), optional: false });\n }\n } else if (strategy.kind === 'multi-equal') {\n const bodies = strategy.bodies;\n const bodyType = renderInputTsType(bodies[0]!.bodyType, modelsWithInput);\n params.push({ name: 'body', type: bodyType, optional: false });\n const ctUnion = bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType?: ${ctUnion} }`, optional: true });\n } else if (strategy.kind === 'multi-formdata-detect') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n } else if (strategy.kind === 'multi-required-arg') {\n const types = strategy.bodies\n .map(b => (b.contentType === 'multipart/form-data' ? 'FormData' : renderInputTsType(b.bodyType, modelsWithInput)))\n .join(' | ');\n params.push({ name: 'body', type: types, optional: false });\n const ctUnion = strategy.bodies.map(b => `'${b.contentType}'`).join(' | ');\n params.push({ name: 'options', type: `{ contentType: ${ctUnion} }`, optional: false });\n }\n\n // Query and custom headers (request-side — use Input variants)\n if (op.query) params.push(inlineArgParam('query', op.query, modelsWithInput));\n if (op.headers) params.push(inlineArgParam('customHeaders', op.headers, modelsWithInput));\n\n return normaliseOptionalOrder(params);\n}\n\n/**\n * One whole-object argument built from a `query:` or `headers:` source.\n *\n * A field is optional only when the contract says so — with `?`, or by carrying a default, which\n * the caller may equally omit. The argument itself is optional only when every field is, since a\n * caller cannot omit an object that must supply something. Both were previously hardcoded\n * optional, which was wrong in both directions at once: it let a caller omit a value the router\n * demanded, and typed a required field as one you could leave out.\n *\n * A `ref` or a whole type node stays optional. Deciding needs the model's own fields, which\n * `buildMethodParams` has no access to.\n */\nfunction inlineArgParam(name: string, source: ParamSource, modelsWithInput?: Set<string>): MethodParam {\n if (source.kind === 'params') {\n const isOptional = (p: OpParamNode) => Boolean(p.optional) || p.default !== undefined;\n const fields = source.nodes\n .map(p => `${quoteKey(p.name)}${isOptional(p) ? '?' : ''}: ${renderInputTsType(p.type, modelsWithInput)}`)\n .join('; ');\n return { name, type: `{ ${fields} }`, optional: source.nodes.every(isOptional) };\n }\n if (source.kind === 'ref') {\n const typeName = modelsWithInput?.has(source.name) ? `${source.name}Input` : source.name;\n return { name, type: typeName, optional: true };\n }\n return { name, type: renderInputTsType(source.node, modelsWithInput), optional: true };\n}\n\n/**\n * Clear `optional` on every parameter before the last required one.\n *\n * Parameter order is path, then body, then query, then customHeaders. An optional parameter\n * cannot precede a required one in TypeScript (`TS1016`), so an operation with an all-optional\n * `query:` and an all-required `headers:` would emit `async m(query?: Q, customHeaders: H)` and\n * fail to compile. Widening the earlier argument to required is the only option that keeps the\n * positional order the call sites depend on.\n *\n * This could not arise while every query and header argument was hardcoded optional; it becomes\n * reachable the moment optionality is read from the contract.\n */\nfunction normaliseOptionalOrder(params: MethodParam[]): MethodParam[] {\n const lastRequired = params.reduce((last, p, i) => (p.optional ? last : i), -1);\n return params.map((p, i) => (i < lastRequired ? { ...p, optional: false } : p));\n}\n\n// ─── Method name inference ────────────────────────────────────────────────\n\nfunction deriveMethodName(op: OpOperationNode, route: OpRouteNode): string {\n if (op.sdk) return op.sdk;\n if (op.name) return nameToMethodName(op.name);\n return inferMethodName(op.method, route.path);\n}\n\nfunction nameToMethodName(name: string): string {\n const parts = name.split(/[\\s\\-_]+/).filter(Boolean);\n return parts.map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join('');\n}\n\nfunction inferMethodName(method: string, path: string): string {\n // Build a name from the path segments + method\n // e.g. GET /users/:id → getUsersById\n // e.g. POST /users → postUsers\n // e.g. DELETE /users/:id → deleteUsersById\n const segments = path.split('/').filter(s => s.length > 0);\n const parts: string[] = [method.toLowerCase()];\n\n for (const seg of segments) {\n if (seg.startsWith('{')) {\n // {id} → ById, {accountId} → ByAccountId\n const paramName = seg.slice(1, -1);\n parts.push('By' + paramName.charAt(0).toUpperCase() + paramName.slice(1));\n } else {\n // Regular segment — camelCase it\n const segParts = seg.split(/[.-]/).filter(Boolean);\n for (const sp of segParts) {\n parts.push(sp.charAt(0).toUpperCase() + sp.slice(1));\n }\n }\n }\n\n return parts[0]! + parts.slice(1).join('');\n}\n\n// ─── Naming conventions ────────────────────────────────────────────────────\n\nfunction deriveBaseName(file: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'Resource';\n return base\n .split('.')\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\n/** Derive a client class name from a `.ck` file path, e.g. `users.ck` → `UsersClient`. Used for legacy flat (no-area) files. */\nexport function deriveClientClassName(file: string): string {\n return `${deriveBaseName(file)}Client`;\n}\n\n/** Camel-cased property name for a flat client on the SDK aggregator, e.g. `users.ck` → `users`. */\nexport function deriveClientPropertyName(file: string): string {\n const base = deriveBaseName(file);\n return base.charAt(0).toLowerCase() + base.slice(1);\n}\n\n/**\n * Pull `area` / `subarea` from a file's `root.meta` (set via `options { keys: { ... } }`).\n * Both are optional. `area` drives top-level SDK grouping; `subarea` drives nesting under\n * an area's client class.\n */\nexport function getAreaSubarea(root: OpRootNode): { area?: string; subarea?: string } {\n return { area: root.meta?.area, subarea: root.meta?.subarea };\n}\n\nfunction pascal(value: string): string {\n return value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map(s => s.charAt(0).toUpperCase() + s.slice(1))\n .join('');\n}\n\nfunction camel(value: string): string {\n const p = pascal(value);\n return p.charAt(0).toLowerCase() + p.slice(1);\n}\n\n/** Class name for the area-level client, e.g. `area=identity` → `IdentityClient`. */\nexport function deriveAreaClientClassName(area: string): string {\n return `${pascal(area)}Client`;\n}\n\n/** Property name on the SDK aggregator for an area, e.g. `area=identity` → `identity`. */\nexport function deriveAreaPropertyName(area: string): string {\n return camel(area);\n}\n\n/** Class name for a leaf subarea client, e.g. `(identity, invitations)` → `IdentityInvitationsClient`. */\nexport function deriveSubareaClientClassName(area: string, subarea: string): string {\n return `${pascal(area)}${pascal(subarea)}Client`;\n}\n\n/** Property name on the area client for a subarea, e.g. `subarea=invitations` → `invitations`. */\nexport function deriveSubareaPropertyName(subarea: string): string {\n return camel(subarea);\n}\n\n// ─── Type collection ──────────────────────────────────────────────────────\n\nfunction collectTypes(root: OpRootNode, modelsWithInput?: Set<string>, modelsWithOutput?: Set<string>, includeInternal = false): string[] {\n const types = new Set<string>();\n for (const route of root.routes) {\n const publicOps = route.operations.filter(op => includeInternal || !resolveModifiers(route, op).includes('internal'));\n if (publicOps.length === 0) continue;\n // Only collect path-param types if there are public ops on this route\n collectParamSourceRefs(route.params, types);\n collectParamSourceInputRefs(route.params, types, modelsWithInput);\n for (const op of publicOps) {\n if (op.request) {\n for (const body of op.request.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectInputTypeNodeRefs(body.bodyType, types, modelsWithInput);\n }\n }\n for (const resp of op.responses) {\n for (const body of resp.bodies) {\n collectTypeNodeRefs(body.bodyType, types);\n collectOutputTypeNodeRefs(body.bodyType, types, modelsWithOutput);\n }\n if (resp.headers) {\n for (const h of resp.headers) {\n collectTypeNodeRefs(h.type, types);\n collectOutputTypeNodeRefs(h.type, types, modelsWithOutput);\n }\n }\n }\n collectParamSourceRefs(op.query, types);\n collectParamSourceInputRefs(op.query, types, modelsWithInput);\n collectParamSourceRefs(op.headers, types);\n collectParamSourceInputRefs(op.headers, types, modelsWithInput);\n }\n }\n return [...types].sort();\n}\n\n/** Collect Output variant refs for response-side ContractTypeNode types. */\nfunction collectOutputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithOutput?: Set<string>): void {\n if (!modelsWithOutput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithOutput.has(type.name)) out.add(`${type.name}Output`);\n break;\n case 'array':\n collectOutputTypeNodeRefs(type.item, out, modelsWithOutput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectOutputTypeNodeRefs(m, out, modelsWithOutput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectOutputTypeNodeRefs(f.type, out, modelsWithOutput));\n break;\n case 'lazy':\n collectOutputTypeNodeRefs(type.inner, out, modelsWithOutput);\n break;\n }\n}\n\n/** Collect Input variant refs for request-side ParamSource types. */\nfunction collectParamSourceInputRefs(source: ParamSource | undefined, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!source || !modelsWithInput) return;\n if (source.kind === 'ref') {\n if (modelsWithInput.has(source.name)) out.add(`${source.name}Input`);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectInputTypeNodeRefs(param.type, out, modelsWithInput);\n }\n } else {\n collectInputTypeNodeRefs(source.node, out, modelsWithInput);\n }\n}\n\n/** Collect Input variant refs for request-side ContractTypeNode types. */\nfunction collectInputTypeNodeRefs(type: ContractTypeNode, out: Set<string>, modelsWithInput?: Set<string>): void {\n if (!modelsWithInput) return;\n switch (type.kind) {\n case 'ref':\n if (modelsWithInput.has(type.name)) out.add(`${type.name}Input`);\n break;\n case 'array':\n collectInputTypeNodeRefs(type.item, out, modelsWithInput);\n break;\n case 'intersection':\n case 'union':\n case 'discriminatedUnion':\n type.members.forEach(m => collectInputTypeNodeRefs(m, out, modelsWithInput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectInputTypeNodeRefs(f.type, out, modelsWithInput));\n break;\n case 'lazy':\n collectInputTypeNodeRefs(type.inner, out, modelsWithInput);\n break;\n }\n}\n\nfunction collectParamSourceRefs(source: ParamSource | undefined, out: Set<string>): void {\n if (!source) return;\n if (source.kind === 'ref') {\n if (/^[A-Z]/.test(source.name)) out.add(source.name);\n } else if (source.kind === 'params') {\n for (const param of source.nodes) {\n collectTypeNodeRefs(param.type, out);\n }\n } else {\n collectTypeNodeRefs(source.node, out);\n }\n}\n\n/** True if any emitted operation has query params (drives the `buildQueryString` import). */\nfunction sdkNeedsQueryString(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n if (op.query) return true;\n }\n }\n return false;\n}\n\n/**\n * True if any emitted operation has a status declaring several mimes, so the client has to read\n * the actual content type off the response to know which it got.\n */\nfunction sdkNeedsReadContentType(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n if (observableResponses(op).some(r => r.bodies.length > 1)) return true;\n }\n }\n return false;\n}\n\n/** True if any emitted operation serializes a JSON request body (uses bigIntReplacer). */\nfunction sdkNeedsBigIntReplacer(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n if (op.request && op.request.bodies.some(b => isJsonMime(b.contentType))) return true;\n }\n }\n return false;\n}\n\n/** True if any public operation parses a JSON response body, and so calls `parseJson`. */\nfunction sdkParsesJsonResponse(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n // Only JSON-shaped responses use parseJson — text/binary read raw.\n if (op.responses.some(r => r.bodies.some(b => classifyContentType(b.contentType) === 'json'))) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * True if a public operation's JSON *response* carries a `bigint`, so the client needs the\n * `123n` reviver when parsing one.\n *\n * Response bodies only: the request side is handled by `bigIntReplacer` on the way out. This is\n * the test the reviver always needed and never made — it was applied to every client that read\n * any JSON at all, so a contract with no bigint anywhere still had a legitimate string like\n * \"123n\" silently converted.\n */\nfunction sdkResponsesUseBigInt(root: OpRootNode, options: SdkCodegenOptions, includeInternal = false): boolean {\n const tainted = options.modelsWithBigInt;\n const reachesBigInt = (type: ContractTypeNode): boolean => {\n // `typeNeedsScalar` stops at a `ref` leaf, so the transitive answer has to come from the\n // precomputed set — a bigint two models down still arrives on the wire as `123n`.\n switch (type.kind) {\n case 'ref':\n return tainted?.has(type.name) ?? false;\n case 'array':\n return reachesBigInt(type.item);\n case 'lazy':\n return reachesBigInt(type.inner);\n case 'tuple':\n return type.items.some(reachesBigInt);\n case 'record':\n return reachesBigInt(type.value);\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n return type.members.some(reachesBigInt);\n case 'inlineObject':\n return type.fields.some(f => reachesBigInt(f.type));\n default:\n return typeNeedsScalar(type, 'bigint');\n }\n };\n\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n for (const resp of op.responses) {\n for (const body of resp.bodies) {\n if (classifyContentType(body.contentType) === 'json' && reachesBigInt(body.bodyType)) return true;\n }\n }\n }\n }\n return false;\n}\n\nfunction sdkNeedsJson(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n const check = (src: ParamSource | undefined) => {\n if (!src || src.kind === 'ref') return false;\n if (src.kind === 'params') return src.nodes.some(p => typeNeedsScalar(p.type, 'json'));\n return typeNeedsScalar(src.node, 'json');\n };\n if (\n !!op.request?.bodies.some(b => typeNeedsScalar(b.bodyType, 'json')) ||\n op.responses.some(r => r.bodies.some(b => typeNeedsScalar(b.bodyType, 'json'))) ||\n check(op.query) ||\n check(op.headers) ||\n check(route.params)\n )\n return true;\n }\n }\n return false;\n}\n\nfunction collectTypeNodeRefs(type: ContractTypeNode, out: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n if (/^[A-Z]/.test(type.name)) out.add(type.name);\n break;\n case 'array':\n collectTypeNodeRefs(type.item, out);\n break;\n case 'tuple':\n type.items.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'record':\n collectTypeNodeRefs(type.key, out);\n collectTypeNodeRefs(type.value, out);\n break;\n case 'union':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'discriminatedUnion':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'intersection':\n type.members.forEach(t => collectTypeNodeRefs(t, out));\n break;\n case 'lazy':\n collectTypeNodeRefs(type.inner, out);\n break;\n case 'inlineObject':\n type.fields.forEach(f => collectTypeNodeRefs(f.type, out));\n break;\n }\n}\n\n// ─── Type import resolution ───────────────────────────────────────────────\n\nfunction generateTypeImports(types: string[], opFile: string, options: SdkCodegenOptions, revivers: string[] = []): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n\n if (modelOutPaths && outPath) {\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n\n for (const type of types) {\n const typeOutPath = modelOutPaths.get(type);\n if (typeOutPath) {\n const group = byFile.get(typeOutPath) ?? [];\n group.push(type);\n byFile.set(typeOutPath, group);\n } else {\n unresolved.push(type);\n }\n }\n\n const fromDir = dirname(outPath);\n for (const [typeOutPath, names] of byFile) {\n let rel = relative(fromDir, typeOutPath);\n rel = rel.replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import type { ${names.sort().join(', ')} } from '${rel}';`);\n // Revivers are values, so they need a second, non-type import from the same module.\n const fromHere = revivers.filter(r => modelOutPaths.get(reviverModelName(r, names)) === typeOutPath);\n if (fromHere.length > 0) lines.push(`import { ${fromHere.sort().join(', ')} } from '${rel}';`);\n }\n\n for (const type of unresolved) {\n const moduleName = pascalToDotCase(type);\n lines.push(`import type { ${type} } from './${moduleName}.js';`);\n }\n } else {\n const typeImport = deriveTypeImportPath(opFile, options.typeImportPathTemplate);\n lines.push(`import type { ${types.join(', ')} } from '${typeImport}';`);\n }\n\n return lines;\n}\n\n/**\n * The model a reviver belongs to. `reviveInvoiceOutput` can come from either `Invoice` (with an\n * `Output` variant) or a model literally called `InvoiceOutput`, so the names actually imported\n * from the module decide it.\n */\nfunction reviverModelName(reviver: string, namesInModule: string[]): string {\n const stem = reviver.replace(/^revive/, '');\n if (namesInModule.includes(stem)) return stem;\n const base = stem.replace(/Output$/, '');\n return namesInModule.includes(base) ? base : stem;\n}\n\nfunction deriveTypeImportPath(file: string, template?: string): string {\n const base =\n file\n .split('/')\n .pop()\n ?.replace(/\\.(op|ck)$/, '') ?? 'resource';\n const module = base.split('.')[0] ?? base;\n if (template) {\n return template.replace(/\\{module\\}/g, module).replace(/\\{base\\}/g, base);\n }\n return `#modules/${module}/types/index.js`;\n}\n\n// ─── Shared SDK files ──────────────────────────────────────────────────────\n\n/** Generate the shared SdkOptions interface file. */\nexport function generateSdkOptions(): string {\n return [\n 'export class SdkError<TBody = unknown> extends Error {',\n ' constructor(',\n ' public readonly status: number,',\n ' public readonly statusText: string,',\n ' public readonly body: TBody,',\n ' public readonly headers: Headers,',\n ' ) {',\n ' super(`${status} ${statusText}`);',\n \" this.name = 'SdkError';\",\n ' }',\n '}',\n '',\n 'export interface SdkRequestInit extends RequestInit {',\n ' /**',\n ' * Statuses this operation declares as values rather than errors — a 304 from',\n ' * conditional-GET middleware, or an error status the service returns deliberately.',\n ' * Anything else at or above 400 still throws SdkError.',\n ' */',\n ' expectStatuses?: number[];',\n '}',\n '',\n 'export type SdkFetch = (url: string, init: SdkRequestInit) => Promise<Response>;',\n '',\n 'export interface SdkOptions {',\n ' baseUrl: string;',\n ' headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);',\n ' fetch?: SdkFetch;',\n ' /** Called once per request to produce a unique X-Request-ID header value */',\n ' requestIdFactory?: () => string;',\n '}',\n '',\n 'export const bigIntReplacer = (_: string, value: any): any => {',\n \" if (typeof value === 'bigint') {\",\n \" return value.toString() + 'n';\",\n ' }',\n ' return value;',\n '};',\n '',\n 'export const bigIntReviver = (_: string, value: any): any => {',\n \" if (typeof value === 'string' && /^-?\\\\d+n$/.test(value)) {\",\n ' return BigInt(value.slice(0, -1));',\n ' }',\n ' return value;',\n '};',\n '',\n JSON_VALUE_TYPE_DECL,\n '',\n 'export function readContentType(res: Response): string {',\n \" return res.headers.get('content-type')?.split(';')[0]?.trim() ?? '';\",\n '}',\n '',\n 'export function createSdkFetch(options: SdkOptions): SdkFetch {',\n ' const getRequestId = options.requestIdFactory ?? (() => crypto.randomUUID());',\n ' return async (url: string, init: SdkRequestInit): Promise<Response> => {',\n \" const baseHeaders = typeof options.headers === 'function'\",\n ' ? await options.headers()',\n ' : options.headers ?? {};',\n ' const res = await fetch(`${options.baseUrl}${url}`, {',\n ' ...init,',\n \" headers: { ...baseHeaders, 'X-Request-ID': getRequestId(), ...init.headers as Record<string, string> },\",\n ' });',\n ' if (!res.ok && !(init.expectStatuses ?? []).includes(res.status)) {',\n ' const text = await res.text();',\n ' let body: unknown;',\n ' try { body = JSON.parse(text); } catch { body = text; }',\n ' throw new SdkError(res.status, res.statusText, body, res.headers);',\n ' }',\n ' return res;',\n ' };',\n '}',\n '',\n 'export function buildQueryString(query: object | undefined): string {',\n ' const searchParams = new URLSearchParams();',\n ' if (query) {',\n ' for (const [k, v] of Object.entries(query)) {',\n ' if (v === undefined || v === null) continue;',\n ' if (Array.isArray(v)) { for (const item of v) searchParams.append(k, String(item)); }',\n ' else searchParams.set(k, String(v));',\n ' }',\n ' }',\n ' const qs = searchParams.toString();',\n \" return qs ? `?${qs}` : '';\",\n '}',\n '',\n '/**',\n ' * Read a JSON response body.',\n ' *',\n ' * No reviver: `bigIntReviver` matches any string of the form `123n` anywhere in the',\n ' * document, so a contract with no bigint field would still have a legitimate string like',\n ' * \"123n\" silently turned into a BigInt. Clients whose contracts do use bigint import',\n ' * `parseJsonWithBigInt` under this name instead.',\n ' */',\n 'export async function parseJson<T>(res: Response): Promise<T> {',\n ' return JSON.parse(await res.text()) as T;',\n '}',\n '',\n '/** `parseJson` for contracts that declare a bigint, applying the `123n` reviver. */',\n 'export async function parseJsonWithBigInt<T>(res: Response): Promise<T> {',\n ' return JSON.parse(await res.text(), bigIntReviver) as T;',\n '}',\n '',\n ].join('\\n');\n}\n\n// ─── Scaffold files (package.json / tsconfig.json) ─────────────────────────\n\n/** Pinned dependency ranges for scaffolded SDK packages. Kept in one place so they're easy to bump. */\nconst SCAFFOLD_DEP_VERSIONS = {\n zod: '^4.3.6',\n luxon: '^3.5.0',\n decimalJs: '^10.4.3',\n typesLuxon: '^3.4.2',\n typescript: '^6.0.3',\n} as const;\n\n/** Which optional runtime deps the generated SDK references, derived from the contracts it covers. */\nexport interface SdkScaffoldDeps {\n /** Zod schema files are emitted (`config.zod`) — the SDK imports `zod`. */\n zod: boolean;\n /** Any covered model uses a `date`/`time`/`datetime`/`duration`/`interval` scalar — the SDK imports `luxon`. */\n luxon: boolean;\n /** Any covered model uses a `decimal` scalar — the SDK imports `decimal.js`. */\n decimal: boolean;\n}\n\n/**\n * Generate a starter `package.json` for a generated SDK package. Emitted with\n * `ifAbsent` semantics — written once, then owned by the user — so the dependency\n * ranges here are only ever a starting point, never re-applied on later builds.\n */\nexport function generateSdkPackageJson(input: { name: string; deps: SdkScaffoldDeps }): string {\n const dependencies: Record<string, string> = {};\n if (input.deps.zod) dependencies.zod = SCAFFOLD_DEP_VERSIONS.zod;\n if (input.deps.luxon) dependencies.luxon = SCAFFOLD_DEP_VERSIONS.luxon;\n // No `@types/` half — decimal.js ships its own declarations.\n if (input.deps.decimal) dependencies['decimal.js'] = SCAFFOLD_DEP_VERSIONS.decimalJs;\n\n const devDependencies: Record<string, string> = { typescript: SCAFFOLD_DEP_VERSIONS.typescript };\n if (input.deps.luxon) devDependencies['@types/luxon'] = SCAFFOLD_DEP_VERSIONS.typesLuxon;\n\n const pkg = {\n name: input.name,\n version: '0.0.0',\n type: 'module',\n main: './dist/index.js',\n types: './dist/index.d.ts',\n exports: {\n '.': {\n types: './dist/index.d.ts',\n import: './dist/index.js',\n },\n },\n files: ['dist'],\n scripts: {\n build: 'tsc -p tsconfig.json',\n },\n ...(Object.keys(dependencies).length > 0 ? { dependencies } : {}),\n devDependencies,\n };\n return JSON.stringify(pkg, null, 4) + '\\n';\n}\n\n/**\n * Generate a standalone `tsconfig.json` for a generated SDK package. Deliberately\n * self-contained (no workspace `extends`) so the scaffold works in a freshly\n * `npm init`'d package outside this monorepo. Emitted with `ifAbsent` semantics.\n */\nexport function generateSdkTsconfig(): string {\n const tsconfig = {\n compilerOptions: {\n target: 'ES2022',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n declaration: true,\n outDir: './dist',\n rootDir: './src',\n strict: true,\n esModuleInterop: true,\n skipLibCheck: true,\n forceConsistentCasingInFileNames: true,\n },\n include: ['src'],\n exclude: ['dist', 'node_modules'],\n };\n return JSON.stringify(tsconfig, null, 4) + '\\n';\n}\n\n/**\n * Reference to a per-file leaf client emitted to its own `*.client.ts`. Used by the\n * aggregator to import the class and wire it as either a top-level `sdk.<prop>` or a\n * nested `sdk.<area>.<subarea>` property.\n */\nexport interface SdkClientInfo {\n /** Client class name (e.g. `UsersClient`, `IdentityInvitationsClient`). */\n className: string;\n /** Property name to expose this client under (e.g. `users`, `invitations`). */\n propertyName: string;\n /** Module specifier for the leaf file, relative to `sdk.ts` and `.js`-suffixed. */\n importPath: string;\n}\n\n/**\n * One area-level (no-subarea) `.ck` file whose methods are merged into the area's\n * `<Area>Client` (emitted to its own `<area>.client.ts`).\n */\nexport interface SdkAreaInlineFile {\n /** Parsed AST. */\n root: OpRootNode;\n /** Codegen options for this file (must have `outPath` pointing at the area client file so type-import paths resolve correctly). */\n codegenOptions: SdkCodegenOptions;\n}\n\n/** A grouping of files that share the same `keys.area`. */\nexport interface SdkAreaInfo {\n area: string;\n /**\n * Reference to the `<Area>Client` class — the file that holds it lives at\n * `client.importPath` (relative to `sdk.ts`) and is generated separately by\n * {@link generateAreaClient}. The aggregator just imports it.\n */\n client: SdkClientInfo;\n}\n\nexport interface SdkAggregatorInput {\n /** Files with no `keys.area` — kept as flat `Sdk.<filename>` properties (legacy behavior). */\n topLevelClients: SdkClientInfo[];\n /** One entry per `keys.area`. */\n areas: SdkAreaInfo[];\n /** Path to `sdk-options.ts` to import `SdkOptions`/`createSdkFetch`/etc. from. */\n sdkOptionsImportPath?: string;\n /** Name of the top-level aggregator class. Defaults to `Sdk`. */\n sdkClassName?: string;\n}\n\n/** Inputs to {@link generateAreaClient}. */\nexport interface AreaClientInput {\n /** Area name (e.g. `payments`). Drives the generated class name (`PaymentsClient`). */\n area: string;\n /** Output path of the generated `<area>.client.ts` file. Used to resolve relative type / leaf-client / sdk-options imports. */\n outPath: string;\n /** Files contributing inlined methods to the area client (typically area-level files with no subarea). */\n inlineFiles: SdkAreaInlineFile[];\n /** Subarea leaf clients exposed as named properties on the area client. */\n subareaClients: { propertyName: string; client: SdkClientInfo }[];\n /** Path to `sdk-options.ts`, used for `SdkFetch` and runtime helpers. */\n sdkOptionsPath: string;\n}\n\n/**\n * Generate a complete `<area>.client.ts` file: the `<Area>Client` class with\n * subarea property fields, a constructor that wires them, and inlined methods\n * merged from every area-level file in `inlineFiles`.\n *\n * Emitted by the plugin alongside the per-leaf `*.client.ts` files. The SDK\n * aggregator just imports the resulting class — see {@link generateSdkAggregator}.\n *\n * @throws if two area-level files contribute the same method name to the area —\n * disambiguate via `sdk:` on the operation, or move one into a subarea.\n */\nexport function generateAreaClient(input: AreaClientInput): string {\n const { area, outPath, inlineFiles, subareaClients, sdkOptionsPath } = input;\n const className = deriveAreaClientClassName(area);\n\n // ── Merge inputs across all inline files ────────────────────────────────\n const collectedMethodLines: string[] = [];\n const collectedRevivePrelude: string[] = [];\n let areaNeedsDecimalImport = false;\n /** Reviver value imports, grouped the same way `typesByImportPath` groups the type imports. */\n const reviversByImportPath = new Map<string, Set<string>>();\n // Aliases are keyed off method names, which already collide-check below, so a Set is enough.\n const collectedErrorAliases = new Set<string>();\n const seenMethods = new Set<string>();\n const typesByImportPath = new Map<string, Set<string>>();\n const unresolvedTypes = new Set<string>();\n let needsJson = false;\n let needsBigIntReplacer = false;\n let needsParseJson = false;\n let needsBigIntReviver = false;\n let needsQueryString = false;\n let needsReadContentType = false;\n\n for (const inline of inlineFiles) {\n const includeInternal = inline.codegenOptions.includeInternal ?? false;\n const { lines: methodLines, methodNames, preludeLines, needsDecimalImport } = generateClientMethods(inline.root, inline.codegenOptions);\n collectedRevivePrelude.push(...preludeLines);\n if (needsDecimalImport) areaNeedsDecimalImport = true;\n for (const name of methodNames) {\n if (seenMethods.has(name)) {\n throw new Error(\n `[sdk] duplicate method '${name}' in area '${area}': two area-level files contribute the same method. Disambiguate via 'sdk:' or move one into a subarea.`,\n );\n }\n seenMethods.add(name);\n }\n collectedMethodLines.push(...methodLines);\n for (const alias of generateErrorBodyAliases(inline.root, inline.codegenOptions)) collectedErrorAliases.add(alias);\n if (sdkNeedsJson(inline.root, includeInternal)) needsJson = true;\n if (sdkNeedsBigIntReplacer(inline.root, includeInternal)) needsBigIntReplacer = true;\n if (sdkParsesJsonResponse(inline.root, includeInternal)) needsParseJson = true;\n if (sdkResponsesUseBigInt(inline.root, inline.codegenOptions, includeInternal)) needsBigIntReviver = true;\n if (sdkNeedsQueryString(inline.root, includeInternal)) needsQueryString = true;\n if (sdkNeedsReadContentType(inline.root, includeInternal)) needsReadContentType = true;\n\n // Revivers this file's methods call, resolved against the same modelOutPaths. Derived from\n // the emitted lines, exactly as `generateSdk` does, so the two paths cannot disagree.\n for (const reviver of usedRevivers(methodLines)) {\n const stem = reviver.replace(/^revive/, '');\n const modelOut = inline.codegenOptions.modelOutPaths?.get(stem) ?? inline.codegenOptions.modelOutPaths?.get(stem.replace(/Output$/, ''));\n if (!modelOut) continue;\n let rel = relative(dirname(outPath), modelOut).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const set = reviversByImportPath.get(rel) ?? new Set<string>();\n set.add(reviver);\n reviversByImportPath.set(rel, set);\n }\n\n // Resolve each file's type refs against THIS file's modelOutPaths, but\n // produce import paths relative to the area client's outPath (not the\n // contributing file's outPath, which pointed at the now-defunct sdk.ts).\n // Filtered against this file's own emitted text for the same reason `generateSdk` filters\n // its own — a multipart body's model is collected but never named in the output.\n const typesForFile = referencedTypes(\n collectTypes(inline.root, inline.codegenOptions.modelsWithInput, inline.codegenOptions.modelsWithOutput, includeInternal),\n [...methodLines, ...generateErrorBodyAliases(inline.root, inline.codegenOptions), ...preludeLines],\n );\n const { modelOutPaths } = inline.codegenOptions;\n if (modelOutPaths) {\n const fromDir = dirname(outPath);\n for (const t of typesForFile) {\n const typeOutPath = modelOutPaths.get(t);\n if (typeOutPath) {\n let rel = relative(fromDir, typeOutPath).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n const set = typesByImportPath.get(rel) ?? new Set();\n set.add(t);\n typesByImportPath.set(rel, set);\n } else {\n unresolvedTypes.add(t);\n }\n }\n }\n }\n\n // ── Imports ─────────────────────────────────────────────────────────────\n let sdkOptionsRel = relative(dirname(outPath), sdkOptionsPath).replace(/\\.ts$/, '.js');\n if (!sdkOptionsRel.startsWith('.')) sdkOptionsRel = './' + sdkOptionsRel;\n\n const lines: string[] = [];\n const jsonImport = needsJson ? ', JsonValue' : '';\n lines.push(`import type { SdkFetch${jsonImport} } from '${sdkOptionsRel}';`);\n const valueImports: string[] = [];\n if (needsBigIntReplacer) valueImports.push('bigIntReplacer');\n if (needsParseJson) valueImports.push(needsBigIntReviver ? 'parseJsonWithBigInt as parseJson' : 'parseJson');\n if (needsQueryString) valueImports.push('buildQueryString');\n if (needsReadContentType) valueImports.push('readContentType');\n if (valueImports.length > 0) {\n lines.push(`import { ${valueImports.join(', ')} } from '${sdkOptionsRel}';`);\n }\n\n for (const path of [...typesByImportPath.keys()].sort()) {\n const names = [...typesByImportPath.get(path)!].sort();\n lines.push(`import type { ${names.join(', ')} } from '${path}';`);\n const revivers = reviversByImportPath.get(path);\n if (revivers && revivers.size > 0) lines.push(`import { ${[...revivers].sort().join(', ')} } from '${path}';`);\n }\n for (const t of [...unresolvedTypes].sort()) {\n lines.push(`import type { ${t} } from './${pascalToDotCase(t)}.js';`);\n }\n\n if (areaNeedsDecimalImport) lines.push(DECIMAL_IMPORT);\n const areaHeaderLuxon = headerLuxonImport(collectedMethodLines, collectedRevivePrelude);\n if (areaHeaderLuxon) lines.push(areaHeaderLuxon);\n\n // Leaf client imports (subareas only — top-level clients live next to sdk.ts).\n const importedClients = new Set<string>();\n for (const sc of subareaClients) {\n const key = `${sc.client.className}|${sc.client.importPath}`;\n if (importedClients.has(key)) continue;\n importedClients.add(key);\n lines.push(`import { ${sc.client.className} } from '${sc.client.importPath}';`);\n }\n lines.push('');\n\n if (collectedErrorAliases.size > 0) {\n lines.push(...collectedErrorAliases);\n lines.push('');\n }\n\n if (collectedRevivePrelude.length > 0) {\n lines.push(...collectedRevivePrelude);\n lines.push('');\n }\n\n // ── <Area>Client class ──────────────────────────────────────────────────\n lines.push(`export class ${className} {`);\n for (const sc of subareaClients) {\n lines.push(` readonly ${sc.propertyName}: ${sc.client.className};`);\n }\n if (subareaClients.length > 0) lines.push('');\n if (collectedMethodLines.length > 0 || subareaClients.length > 0) {\n const fetchModifier = collectedMethodLines.length > 0 ? 'private ' : '';\n lines.push(` constructor(${fetchModifier}fetch: SdkFetch) {`);\n for (const sc of subareaClients) {\n lines.push(` this.${sc.propertyName} = new ${sc.client.className}(fetch);`);\n }\n lines.push(' }');\n }\n for (const ln of collectedMethodLines) lines.push(ln);\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Generate the SDK aggregator (`sdk.ts`) — the entry-point file consumers import.\n *\n * Imports every `<Area>Client` (one per area, generated by {@link generateAreaClient}\n * to its own `<area>.client.ts`) and every leaf top-level client, then emits a\n * `class Sdk` that exposes them as properties.\n */\nexport function generateSdkAggregator(input: SdkAggregatorInput): string {\n const sdkOptionsImportPath = input.sdkOptionsImportPath ?? './sdk-options.js';\n const sdkClassName = input.sdkClassName ?? 'Sdk';\n\n const lines: string[] = [];\n lines.push(`import type { SdkOptions } from '${sdkOptionsImportPath}';`);\n lines.push(`import { createSdkFetch } from '${sdkOptionsImportPath}';`);\n\n const importedClients = new Set<string>();\n const pushClientImport = (c: SdkClientInfo): void => {\n const key = `${c.className}|${c.importPath}`;\n if (importedClients.has(key)) return;\n importedClients.add(key);\n lines.push(`import { ${c.className} } from '${c.importPath}';`);\n };\n // Areas first, then top-level — keeps the aggregator's import order stable.\n for (const area of input.areas) pushClientImport(area.client);\n for (const c of input.topLevelClients) pushClientImport(c);\n lines.push('');\n\n lines.push(`export class ${sdkClassName} {`);\n for (const area of input.areas) {\n lines.push(` readonly ${deriveAreaPropertyName(area.area)}: ${area.client.className};`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` readonly ${c.propertyName}: ${c.className};`);\n }\n lines.push('');\n lines.push(' constructor(options: SdkOptions) {');\n lines.push(' const sdkFetch = options.fetch ?? createSdkFetch(options);');\n for (const area of input.areas) {\n lines.push(` this.${deriveAreaPropertyName(area.area)} = new ${area.client.className}(sdkFetch);`);\n }\n for (const c of input.topLevelClients) {\n lines.push(` this.${c.propertyName} = new ${c.className}(sdkFetch);`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n","import type { ContractRootNode, ModelNode, FieldNode } from '@contractkit/core';\nimport { computeModelsWithOutput, collectExternalOutputRefs } from '@contractkit/core';\nimport type { ContractCodegenContext } from './codegen-contract.js';\nimport {\n collectExternalRefs,\n collectExternalInputRefs,\n computeModelsWithInput,\n topoSortModels,\n resolveImportPath,\n rootNeedsScalar,\n} from './codegen-contract.js';\nimport { renderTsType, renderInputTsType, renderOutputTsType, quoteKey, escapeJsDocLines, sourceLink, JSON_VALUE_TYPE_DECL } from './ts-render.js';\nimport type { TsRenderTarget } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_CONFIG_LINE } from './decimal-runtime.js';\nimport { renderReviveFunctions, reviveFnName, coerceDeclsFor } from './codegen-revive.js';\n\n// ─── Public entry point ────────────────────────────────────────────────────\n\n/**\n * Generate plain TypeScript interfaces/types from a contract AST.\n * Unlike `generateContract()` which produces Zod schemas, this emits\n * vanilla TypeScript `interface` and `type` declarations suitable\n * for SDK consumers that don't need runtime validation.\n *\n * @param context Import resolution and Input/Output variant sets. `context.target` selects the\n * runtime the types describe (`'server'` renders `binary` as `Buffer`, `'client'` as `Blob`).\n */\nexport function generatePlainTypes(root: ContractRootNode, context?: ContractCodegenContext): string {\n const target: TsRenderTarget = context?.target ?? 'client';\n const externalRefs = collectExternalRefs(root);\n const lines: string[] = [];\n\n // Compute which models have Input variants (local, incl. transitive deps + external)\n const externalModelsWithInput = context?.modelsWithInput ?? new Set<string>();\n const localModelsWithInput = computeModelsWithInput(root.models, externalModelsWithInput);\n const allModelsWithInput = new Set([...localModelsWithInput, ...externalModelsWithInput]);\n\n // Compute which models have Output variants (post-transform wire shape)\n const externalModelsWithOutput = context?.modelsWithOutput ?? new Set<string>();\n const localModelsWithOutput = computeModelsWithOutput(root.models, externalModelsWithOutput);\n const allModelsWithOutput = new Set([...localModelsWithOutput, ...externalModelsWithOutput]);\n\n // Collect additional external Input/Output refs needed for variant fields\n const externalInputRefs = allModelsWithInput.size > 0 ? collectExternalInputRefs(root, allModelsWithInput) : [];\n const externalOutputRefs = allModelsWithOutput.size > 0 ? collectExternalOutputRefs(root, allModelsWithOutput) : [];\n const allExternalRefs = [...new Set([...externalRefs, ...externalInputRefs, ...externalOutputRefs])].sort();\n\n // Not `import type`: `renderTsScalar` maps `decimal` to `Decimal` in this mode too, so the class\n // is a real runtime dependency of any consumer holding one — same position as in\n // `generateContract`, which emits it ahead of the external model refs.\n const needsDecimal = rootNeedsScalar(root, 'decimal') || (context?.emitRevivers && context.modelsWithDecimal ? root.models.some(m => context.modelsWithDecimal!.has(m.name)) : false);\n if (needsDecimal) lines.push(DECIMAL_IMPORT);\n\n // Likewise for the temporal scalars: `renderTsScalar` maps them to Luxon classes, which are a\n // real runtime dependency of anyone holding one. `interval` is not among them — it renders as\n // a string, since `_ZodInterval` transforms back to ISO on output.\n const luxonImports: string[] = [];\n if (rootNeedsScalar(root, 'date') || rootNeedsScalar(root, 'time') || rootNeedsScalar(root, 'datetime')) luxonImports.push('DateTime');\n if (rootNeedsScalar(root, 'duration')) luxonImports.push('Duration');\n if (luxonImports.length > 0) lines.push(`import { ${luxonImports.join(', ')} } from 'luxon';`);\n\n // Type-only imports for external references. A cross-file model carrying a decimal also\n // contributes its reviver, which is a value and so needs a second, non-type import.\n for (const ref of allExternalRefs) {\n const importPath = resolveImportPath(ref, context);\n lines.push(`import type { ${ref} } from '${importPath}';`);\n if (context?.emitRevivers && context.modelsWithDecimal?.has(ref)) {\n lines.push(`import { ${reviveFnName(ref)} } from '${importPath}';`);\n }\n }\n if (allExternalRefs.length > 0) lines.push('');\n\n if (rootNeedsScalar(root, 'json')) {\n if (context?.jsonValueImportPath) {\n lines.push(`import type { JsonValue } from '${context.jsonValueImportPath}';`);\n } else {\n lines.push(JSON_VALUE_TYPE_DECL);\n }\n lines.push('');\n }\n\n const modelMap = new Map(root.models.map(m => [m.name, m]));\n\n const reviveOpts =\n context?.emitRevivers && context.modelsWithDecimal\n ? { modelsWithDecimal: context.modelsWithDecimal, modelsWithOutput: allModelsWithOutput, modelMap }\n : undefined;\n\n const bodyLines: string[] = [];\n for (const model of topoSortModels(root.models)) {\n bodyLines.push(...generateModel(model, target, context?.currentOutPath, allModelsWithInput, allModelsWithOutput, modelMap));\n if (reviveOpts) {\n const revivers = renderReviveFunctions(model, reviveOpts);\n if (revivers.length > 0) {\n bodyLines.push('');\n bodyLines.push(...revivers);\n }\n }\n bodyLines.push('');\n }\n\n // Global decimal.js config belongs in any file holding a `Decimal`: there is no Zod schema in\n // this mode, but `String(value)` and `JSON.stringify` still have to stay out of exponential form.\n if (needsDecimal) {\n lines.push('');\n lines.push(DECIMAL_CONFIG_LINE);\n }\n\n // Same rule as in `generateContract`: a helper is emitted only if the revivers actually\n // reference it, so the two cannot drift and trip `noUnusedLocals`.\n const coerceDecls = coerceDeclsFor(bodyLines);\n if (coerceDecls.length > 0) {\n lines.push(...coerceDecls);\n lines.push('');\n }\n lines.push(...bodyLines);\n\n return lines.join('\\n');\n}\n\n// ─── Model ─────────────────────────────────────────────────────────────────\n\nfunction generateModel(\n model: ModelNode,\n target: TsRenderTarget,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithOutput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n // Type alias: Name : typeExpression\n if (model.type) {\n return generateTypeAlias(model, target, outPath, modelsWithInput, modelsWithOutput);\n }\n\n // A model needs Input/read split if it has visibility-modified fields OR if it\n // transitively references models that have Input variants (captured in modelsWithInput).\n const needsInputSplit = model.fields.some(f => f.visibility !== 'normal') || (modelsWithInput?.has(model.name) ?? false);\n\n const lines = needsInputSplit\n ? generateVisibilityModel(model, target, outPath, modelsWithInput, modelMap)\n : generateSimpleModel(model, target, outPath, modelMap);\n\n if (modelsWithOutput?.has(model.name)) {\n lines.push('');\n lines.push(...generateOutputModel(model, target, modelsWithOutput));\n }\n return lines;\n}\n\n/** Recursively collect every field name defined on `bases` and their ancestors. Used to detect\n * fields that the child re-declares without an explicit `override` keyword — those still need an\n * `Omit<Base, …>` wrap, otherwise the child's narrower/incompatible declaration collides with the\n * inherited one. */\nfunction collectInheritedFieldNames(bases: string[], modelMap: Map<string, ModelNode>): Set<string> {\n const result = new Set<string>();\n const visit = (name: string): void => {\n const m = modelMap.get(name);\n if (!m || m.type) return;\n for (const f of m.fields) result.add(f.name);\n for (const b of m.bases ?? []) visit(b);\n };\n for (const b of bases) visit(b);\n return result;\n}\n\n/** Names of fields the child declaration overrides — explicit `override` plus any field whose\n * name shadows an inherited one. The latter catches single-base redeclarations that omit the\n * `override` keyword (e.g. narrowing `kind: BusinessRoleKind` → `kind: 'employee'`). */\nfunction computeOverrideNames(model: ModelNode, modelMap?: Map<string, ModelNode>): string[] {\n const inherited = modelMap ? collectInheritedFieldNames(model.bases ?? [], modelMap) : new Set<string>();\n return model.fields.filter(f => f.override || inherited.has(f.name)).map(f => f.name);\n}\n\nfunction generateComments(model: ModelNode, outPath?: string): string[] {\n const lines: string[] = [];\n lines.push('/**');\n if (model.deprecated) {\n lines.push(` * @deprecated`);\n }\n if (model.description) {\n for (const l of escapeJsDocLines(model.description)) lines.push(` * ${l}`);\n }\n\n lines.push(` * generated from ${sourceLink(model.name, outPath, model.loc.file, model.loc.line)}`);\n lines.push(' */');\n return lines;\n}\n\nfunction generateTypeAlias(\n model: ModelNode,\n target: TsRenderTarget,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelsWithOutput?: Set<string>,\n): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n lines.push(`export type ${model.name} = ${renderTsType(model.type!, target)};`);\n if (modelsWithInput?.has(model.name)) {\n lines.push(`export type ${model.name}Input = ${renderInputTsType(model.type!, modelsWithInput, target)};`);\n }\n if (modelsWithOutput?.has(model.name)) {\n lines.push(`export type ${model.name}Output = ${renderOutputTsType(model.type!, modelsWithOutput, target)};`);\n }\n return lines;\n}\n\n/** Build the `extends` clause for a model.\n * Each entry in `overrideNames` is wrapped in `Omit<Base, 'name1' | 'name2'>` per base so the\n * subclass can legally redeclare those fields with new (possibly incompatible) types.\n * TypeScript's `Omit<T, K extends keyof any>` tolerates omit keys that don't appear on the base,\n * so we apply the same omit list to every base without per-base field-set lookup. */\nfunction buildExtendsClause(bases: string[], overrideNames: string[], baseNameResolver: (b: string) => string): string {\n if (bases.length === 0) return '';\n if (overrideNames.length === 0) return ` extends ${bases.map(baseNameResolver).join(', ')}`;\n const omitKeys = overrideNames.map(n => `'${n}'`).join(' | ');\n const wrapped = bases.map(b => `Omit<${baseNameResolver(b)}, ${omitKeys}>`);\n return ` extends ${wrapped.join(', ')}`;\n}\n\nfunction generateSimpleModel(model: ModelNode, target: TsRenderTarget, outPath?: string, modelMap?: Map<string, ModelNode>): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n\n for (const field of model.fields) {\n lines.push(` ${renderField(field, target)}`);\n }\n\n lines.push('}');\n return lines;\n}\n\nfunction generateVisibilityModel(\n model: ModelNode,\n target: TsRenderTarget,\n outPath?: string,\n modelsWithInput?: Set<string>,\n modelMap?: Map<string, ModelNode>,\n): string[] {\n const lines: string[] = [];\n lines.push(...generateComments(model, outPath));\n\n const bases = model.bases ?? [];\n const overrideNames = computeOverrideNames(model, modelMap);\n\n // Read type — omit writeonly fields\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n lines.push(`export interface ${model.name}${buildExtendsClause(bases, overrideNames, b => b)} {`);\n for (const field of readFields) {\n lines.push(` ${renderField(field, target)}`);\n }\n lines.push('}');\n lines.push('');\n\n // Write type — omit readonly fields (use Input variants for sub-type refs);\n // extends ParentInput if parent has an Input variant, else extends parent read type\n const writeFields = model.fields.filter(f => f.visibility !== 'readonly');\n const inputResolver = (b: string) => (modelsWithInput?.has(b) ? `${b}Input` : b);\n lines.push(`export interface ${model.name}Input${buildExtendsClause(bases, overrideNames, inputResolver)} {`);\n for (const field of writeFields) {\n lines.push(` ${modelsWithInput ? renderInputField(field, modelsWithInput, target) : renderField(field, target)}`);\n }\n lines.push('}');\n\n return lines;\n}\n\n// ─── Field rendering ──────────────────────────────────────────────────────\n\n/** Prefix a field declaration with a JSDoc comment built from `@deprecated` / description parts,\n * neutralizing any block-comment terminator and expanding embedded newlines into continuation lines. */\nfunction withFieldJsDoc(jsdocParts: string[], line: string): string {\n if (jsdocParts.length === 0) return line;\n const contentLines = escapeJsDocLines(jsdocParts.join(' '));\n if (contentLines.length === 1) {\n return `/** ${contentLines[0]} */\\n ${line}`;\n }\n const body = contentLines.map(l => ` * ${l}`).join('\\n');\n return `/**\\n${body}\\n */\\n ${line}`;\n}\n\nfunction renderField(field: FieldNode, target: TsRenderTarget): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderTsType(field.type, target);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n return withFieldJsDoc(jsdocParts, line);\n}\n\nfunction renderInputField(field: FieldNode, modelsWithInput: Set<string>, target: TsRenderTarget): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n let typeStr = renderInputTsType(field.type, modelsWithInput, target);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(field.name)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n return withFieldJsDoc(jsdocParts, line);\n}\n\n// ─── Output (post-transform wire shape) ──────────────────────────────────\n\nfunction camelToSnake(s: string): string {\n return s.replace(/[A-Z]/g, c => `_${c.toLowerCase()}`);\n}\n\nfunction camelToPascal(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction applyOutputCase(name: string, c: 'camel' | 'snake' | 'pascal' | undefined): string {\n if (!c || c === 'camel') return name;\n if (c === 'snake') return camelToSnake(name);\n return camelToPascal(name);\n}\n\n/**\n * Emit `${name}Output` for a model in the output transitive set.\n * - Direct hits (model.outputCase set): rename keys per the transform and substitute nested refs.\n * - Transitive hits: keep field names as-is but substitute nested refs with their Output variants.\n *\n * `extends` is dropped for direct-hit models because the Zod schema flattens fields when an\n * ancestor has format(...) (see `flattenFormatChain` in codegen-contract); we mirror that here\n * so the plain interface matches the wire shape produced by the Zod transform.\n */\nfunction generateOutputModel(model: ModelNode, target: TsRenderTarget, modelsWithOutput: Set<string>): string[] {\n const lines: string[] = [];\n const outputCase = model.outputCase && model.outputCase !== 'camel' ? model.outputCase : undefined;\n const readFields = model.fields.filter(f => f.visibility !== 'writeonly');\n\n // Transitive-only (no direct outputCase): preserve `extends` and original key names.\n if (!outputCase) {\n const baseExt =\n model.bases?.[0] && modelsWithOutput.has(model.bases?.[0])\n ? ` extends ${model.bases?.[0]}Output`\n : model.bases?.[0]\n ? ` extends ${model.bases?.[0]}`\n : '';\n lines.push(`export interface ${model.name}Output${baseExt} {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, model.outputCase, modelsWithOutput, target)}`);\n }\n lines.push('}');\n return lines;\n }\n\n // Direct hit: emit a flat interface with renamed keys.\n lines.push(`export interface ${model.name}Output {`);\n for (const field of readFields) {\n lines.push(` ${renderOutputField(field, outputCase, modelsWithOutput, target)}`);\n }\n lines.push('}');\n return lines;\n}\n\nfunction renderOutputField(\n field: FieldNode,\n outputCase: 'camel' | 'snake' | 'pascal' | undefined,\n modelsWithOutput: Set<string>,\n target: TsRenderTarget,\n): string {\n const opt = field.optional || field.default !== undefined ? '?' : '';\n const key = applyOutputCase(field.name, outputCase);\n let typeStr = renderOutputTsType(field.type, modelsWithOutput, target);\n if (field.nullable) typeStr += ' | null';\n const line = `${quoteKey(key)}${opt}: ${typeStr};`;\n const jsdocParts: string[] = [];\n if (field.deprecated) jsdocParts.push('@deprecated');\n if (field.description) jsdocParts.push(field.description);\n return withFieldJsDoc(jsdocParts, line);\n}\n","import type { ServerFramework } from './server-framework.js';\n\n/** Module the Fastify flavour of ServerKit publishes its router and route middleware from. */\nconst FASTIFY_RUNTIME_MODULE = '@maroonedsoftware/fastify';\n\n/**\n * Symbols importable from {@link FASTIFY_RUNTIME_MODULE}. Every one is a name the adapter itself\n * emits, so none can collide with a service class or router name derived from a contract.\n *\n * `requestMediaType` is here because Fastify has no accessor that strips the parameters off\n * `Content-Type`, and it is only referenced when an operation declares several request MIME types.\n */\nconst FASTIFY_RUNTIME_SYMBOLS = ['ServerKitRouter', 'bodyParserMiddleware', 'requirePolicy', 'requireSignature', 'requestMediaType'] as const;\n\n/**\n * ServerKit on Fastify: `ServerKitRouter()` collects routes the way a Koa app reads and mounts them\n * as a Fastify plugin, handlers take `(request, reply)` where the request *is* the ServerKit\n * context, and a response is sent by returning `reply.send(...)` rather than by assignment.\n */\nexport const FASTIFY_SERVER_FRAMEWORK: ServerFramework = {\n name: 'fastify',\n\n imports(uses) {\n const symbols = FASTIFY_RUNTIME_SYMBOLS.filter(uses);\n return symbols.length > 0 ? [`import { ${symbols.join(', ')} } from '${FASTIFY_RUNTIME_MODULE}';`] : [];\n },\n\n routerDeclaration(routerName) {\n return `export const ${routerName} = ServerKitRouter();`;\n },\n\n pathParam(identifier) {\n return `:${identifier}`;\n },\n\n handlerLocals: ['request', 'reply'],\n\n routeOpen(routerName, method, path, middlewares) {\n const middlewareStr = middlewares.length > 0 ? `, ${middlewares.join(', ')},` : ',';\n return `${routerName}.${method}('${path}'${middlewareStr} async (request, reply) => {`;\n },\n\n routeClose() {\n return ['});'];\n },\n\n middleware: {\n policy(args) {\n return `requirePolicy(${args})`;\n },\n bodyParser(tokensExpr) {\n return `bodyParserMiddleware([${tokensExpr}])`;\n },\n signature(args) {\n return `requireSignature(${args})`;\n },\n },\n\n request: {\n params: 'request.params',\n query: 'request.query',\n headers: 'request.headers',\n // ServerKit parses lazily per route, so Fastify's own `request.body` is never populated.\n parsedBody: 'request.parsedBody',\n // A call, not a property: the raw header carries `; charset=utf-8`, which would match none of\n // the declared MIME literals the generated switch compares against.\n contentType: 'requestMediaType(request)',\n },\n\n resolveService(className) {\n return `request.container.get(${className})`;\n },\n\n response: {\n status(expr) {\n return `reply.status(${expr});`;\n },\n header(name, valueExpr) {\n return `reply.header('${name}', ${valueExpr});`;\n },\n type(expr) {\n return `reply.type(${expr});`;\n },\n send(bodyExpr) {\n // Unlike Koa, a bodyless response still needs a statement: a handler that neither returns\n // a body nor calls `send` leaves the request hanging.\n return bodyExpr === undefined ? ['return reply.send();'] : [`return reply.send(${bodyExpr});`];\n },\n caseEnd() {\n // Every status case has already returned, so a `break` here would be unreachable code.\n return [];\n },\n },\n\n mcpRouter({ path }) {\n return `import { type ServerKitRouterType, bodyParserMiddleware, requireSignature, requestHeader } from '${FASTIFY_RUNTIME_MODULE}';\nimport { McpDispatcher, createMcpRequestContext, MCP_AUTH_POLICY } from '@maroonedsoftware/mcp';\n\n/** Mount the MCP endpoint onto a ServerKit router. Bind \\`registerMcpTools\\` to the \\`McpToolHandlerMap\\` token. */\nexport function mountMcp(router: ServerKitRouterType): void {\n router.post('${path}', bodyParserMiddleware(['json']), requireSignature('mcp', { policy: MCP_AUTH_POLICY }), async (request, reply) => {\n const dispatcher = request.container.get(McpDispatcher);\n const context = createMcpRequestContext({ requestId: request.requestId, logger: request.logger });\n if (dispatcher.sessionMode === 'stateful') {\n // Fastify's equivalent of Koa's \\`ctx.respond = false\\`: the dispatcher writes the raw\n // response itself, and the request scope is disposed on the raw socket close instead.\n reply.hijack();\n await dispatcher.dispatchStateful(\n {\n req: request.raw,\n res: reply.raw,\n body: request.parsedBody,\n // \\`requestHeader\\` returns '' for an absent header; the session id is optional.\n sessionId: requestHeader(request, 'mcp-session-id') || undefined,\n },\n context,\n );\n return;\n }\n const response = await dispatcher.dispatch(JSON.parse(String(request.rawBody)), context);\n if (response) return reply.send(response);\n reply.status(202); // a notification — nothing to return\n return reply.send();\n });\n}\n`;\n },\n};\n","import { KOA_SERVER_FRAMEWORK } from './server-framework-koa.js';\nimport { FASTIFY_SERVER_FRAMEWORK } from './server-framework-fastify.js';\n\n/**\n * HTTP frameworks the server sub-generator can target. Adding a name here without adding an adapter\n * to {@link SERVER_FRAMEWORKS} fails to compile, which is the point of keeping the two in step.\n */\nexport const SERVER_FRAMEWORK_NAMES = ['koa', 'fastify'] as const;\n\n/** One of {@link SERVER_FRAMEWORK_NAMES}. */\nexport type ServerFrameworkName = (typeof SERVER_FRAMEWORK_NAMES)[number];\n\n/** The framework assumed when a config names none. */\nexport const DEFAULT_SERVER_FRAMEWORK_NAME: ServerFrameworkName = 'koa';\n\n/**\n * Every framework-specific string the router and MCP router generators emit.\n *\n * Granularity is one statement (or one fragment) per method, so the shared codegen keeps ownership\n * of control flow — which branches exist, what order they run in, and which values reach them — and\n * an adapter only decides how a given step is spelled. Anything an adapter cannot express as a\n * statement, such as ending a response, is returned as a list of lines so it can also be empty.\n */\nexport interface ServerFramework {\n readonly name: ServerFrameworkName;\n\n /**\n * Import lines for the framework runtime, already filtered down to what the generated body uses.\n *\n * The adapter applies `uses` itself rather than declaring a symbol list, because a framework may\n * need more than one import line, and because only names the adapter chooses ever go through the\n * word-boundary probe — a handler-local identifier can never be mistaken for an import.\n */\n imports(uses: (symbol: string) => boolean): string[];\n\n /** The module-level router value every handler attaches to. */\n routerDeclaration(routerName: string): string;\n\n /** Placeholder syntax for one path parameter, given a name already mapped to a valid identifier. */\n pathParam(identifier: string): string;\n\n /**\n * Identifiers the handler signature itself binds — `ctx`, or `request` and `reply`. A path\n * parameter is destructured into the handler body, so one declared with the same name would\n * shadow the handler's own parameter: a redeclaration under `tsc`, and a temporal-dead-zone\n * `ReferenceError` at runtime. Codegen renames the local binding to avoid these.\n */\n readonly handlerLocals: readonly string[];\n\n /** Opening line of a handler, including its middleware and the handler function's parameters. */\n routeOpen(routerName: string, method: string, path: string, middlewares: readonly string[]): string;\n\n /** Lines that close a handler opened by {@link routeOpen}. */\n routeClose(): string[];\n\n /** Route middleware factory calls, rendered as expressions for {@link routeOpen}. */\n readonly middleware: {\n policy(args: string): string;\n bodyParser(tokensExpr: string): string;\n signature(args: string): string;\n };\n\n /** Expressions a handler reads the request through. */\n readonly request: {\n params: string;\n query: string;\n headers: string;\n /** The body already parsed by the body-parser middleware. */\n parsedBody: string;\n /**\n * The request's media type with any parameters stripped. It is matched against declared MIME\n * literals, so an adapter whose framework exposes only the raw header must normalise it here\n * — a `; charset=utf-8` left on the end matches nothing.\n */\n contentType: string;\n };\n\n /** Expression resolving a service class out of the request-scoped DI container. */\n resolveService(className: string): string;\n\n /** Statements a handler writes the response with. */\n readonly response: {\n status(expr: string): string;\n /**\n * One statement setting a response header. It is emitted bare or behind an `if` guard for an\n * optional header, so it must stay a single statement.\n */\n header(name: string, valueExpr: string): string;\n type(expr: string): string;\n /**\n * The terminal write for a response, or for one without a body when `bodyExpr` is undefined.\n * A framework that ends a response by returning needs a statement in both cases; Koa, which\n * ends it by assignment, emits nothing for a bodyless one.\n */\n send(bodyExpr: string | undefined): string[];\n /** What closes one `case` of the multi-status switch, after that status has been written. */\n caseEnd(): string[];\n };\n\n /** The whole `mcp.router.ts` file, which is boilerplate rather than a per-operation render. */\n mcpRouter(options: { path: string }): string;\n}\n\n/**\n * Every supported framework, keyed by name. The annotation is what ties this to\n * {@link SERVER_FRAMEWORK_NAMES}: adding a name without an adapter is a compile error.\n */\nexport const SERVER_FRAMEWORKS: Readonly<Record<ServerFrameworkName, ServerFramework>> = {\n koa: KOA_SERVER_FRAMEWORK,\n fastify: FASTIFY_SERVER_FRAMEWORK,\n};\n\n/**\n * Resolve a configured framework name to its adapter.\n *\n * @param name The `server.framework` value, or undefined for {@link DEFAULT_SERVER_FRAMEWORK_NAME}.\n * @throws When `name` is not a supported framework. Config arrives as JSON, so this is a runtime\n * check and not something the `ServerFrameworkName` type can enforce on its own.\n */\nexport function resolveServerFramework(name: string | undefined): ServerFramework {\n const resolved = name ?? DEFAULT_SERVER_FRAMEWORK_NAME;\n const framework = (SERVER_FRAMEWORKS as Record<string, ServerFramework | undefined>)[resolved];\n if (!framework) {\n throw new Error(\n `plugin-typescript: server.framework '${resolved}' is not supported — expected one of: ${SERVER_FRAMEWORK_NAMES.join(', ')}.`,\n );\n }\n return framework;\n}\n","import type { OpRootNode, OpRouteNode, OpOperationNode, McpConfigNode, ParamSource, ContractTypeNode } from '@contractkit/core';\nimport { resolveModifiers, emittedResponses, toIdentifier } from '@contractkit/core';\nimport { renderType, renderInputType, pascalToDotCase } from './codegen-contract.js';\nimport { inferService, deriveModulePath, buildArgs, deriveBaseName } from './codegen-operation.js';\nimport { quoteKey, escapeSingleQuoted, sourceLink } from './ts-render.js';\nimport { DECIMAL_IMPORT, DECIMAL_PRELUDE_LINES } from './decimal-runtime.js';\nimport { basename, dirname, relative } from 'node:path';\nimport type { ServerFramework } from './server-framework.js';\nimport { KOA_SERVER_FRAMEWORK } from './server-framework-koa.js';\n\n// ─── Options ────────────────────────────────────────────────────────────────\n\nexport interface McpCodegenOptions {\n /** Absolute path of the file being generated. Used to compute relative imports. */\n outPath?: string;\n /** Map from schema identifier (model name / `${name}Input`) → absolute output file. */\n modelOutPaths?: Map<string, string>;\n /** Model names that have an Input variant schema. */\n modelsWithInput?: Set<string>;\n /** Model names that have an Output variant schema. */\n modelsWithOutput?: Set<string>;\n /** Import-path template for service implementations (same semantics as ServerConfig). */\n servicePathTemplate?: string;\n /** Emit tools for `internal` operations. Default false. */\n includeInternal?: boolean;\n}\n\n// ─── MCP flag helpers ─────────────────────────────────────────────────────\n\n/** The explicit settings block, if the operation used the object form of `mcp:`. */\nfunction mcpConfig(op: OpOperationNode): McpConfigNode | undefined {\n return op.mcp && typeof op.mcp === 'object' ? op.mcp : undefined;\n}\n\n/**\n * True if the root has at least one MCP-exposed operation. With `includeInternal: false`\n * (default) `internal` operations don't count. Mirrors `hasPublicOperations`.\n */\nexport function hasMcpOperations(root: OpRootNode, includeInternal = false): boolean {\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!op.mcp) continue;\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n return true;\n }\n }\n return false;\n}\n\n// ─── Name derivation ────────────────────────────────────────────────────────\n\n/** camelCase / PascalCase / spaced / hyphenated → snake_case. */\nfunction toSnake(s: string): string {\n return s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[\\s\\-.]+/g, '_')\n .toLowerCase()\n .replace(/[^a-z0-9_]/g, '')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n}\n\n/** snake_case → PascalCase. */\nfunction toPascal(s: string): string {\n return s\n .split('_')\n .filter(Boolean)\n .map(p => p.charAt(0).toUpperCase() + p.slice(1))\n .join('');\n}\n\n/** Inferred snake_case tool name from method + path, e.g. GET /payments/{id} → get_payments_by_id. */\nfunction inferToolName(method: string, path: string): string {\n const parts: string[] = [method.toLowerCase()];\n for (const seg of path.split('/').filter(Boolean)) {\n if (seg.startsWith('{')) {\n parts.push('by', toSnake(seg.slice(1, -1)));\n } else {\n parts.push(toSnake(seg));\n }\n }\n return parts.filter(Boolean).join('_');\n}\n\n/** Tool name: explicit `mcp.name` (verbatim) → `sdk` → `name` → inferred; derived forms snake_cased. */\nfunction deriveToolName(op: OpOperationNode, route: OpRouteNode): string {\n const cfg = mcpConfig(op);\n if (cfg?.name) return cfg.name;\n if (op.sdk) return toSnake(op.sdk);\n if (op.name) return toSnake(op.name);\n return inferToolName(op.method, route.path);\n}\n\n/** Tool class name — PascalCase of the tool name with an `McpTool` suffix for clarity. */\nfunction deriveToolClassName(toolName: string): string {\n return `${toPascal(toolName)}McpTool`;\n}\n\n// ─── Input args schema ────────────────────────────────────────────────────\n\ninterface ArgsProp {\n key: string;\n expr: string;\n optional: boolean;\n}\n\n/** Build the flat args properties for a tool, matching the router's `buildArgs` variable names. */\nfunction buildArgsProps(route: OpRouteNode, op: OpOperationNode, modelsWithInput?: Set<string>): ArgsProp[] {\n const props: ArgsProp[] = [];\n\n // Path params — spread individually (inline) or as a single `params` object (ref/type).\n if (route.params) {\n if (route.params.kind === 'params') {\n for (const node of route.params.nodes) {\n // The handler destructures these, so the key has to be a valid identifier. The MCP\n // input schema is ours to name — nothing on an HTTP wire depends on it.\n props.push({ key: toIdentifier(node.name), expr: renderInputType(node.type, modelsWithInput), optional: false });\n }\n } else if (route.params.kind === 'ref') {\n props.push({ key: 'params', expr: refSchema(route.params.name, modelsWithInput), optional: false });\n } else {\n props.push({ key: 'params', expr: renderInputType(route.params.node, modelsWithInput), optional: false });\n }\n }\n\n // Body — single JSON body maps to a `body` field; multipart/binary/multi bodies aren't cleanly\n // representable as JSON tool args, so they fall back to `z.unknown()` (advisory only).\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 1 && bodies[0]!.contentType === 'multipart/form-data') {\n props.push({ key: 'multipartBody', expr: 'z.unknown()', optional: false });\n } else if (bodies.length === 1) {\n props.push({ key: 'body', expr: renderInputType(bodies[0]!.bodyType, modelsWithInput), optional: false });\n } else if (bodies.length > 1) {\n props.push({ key: 'body', expr: 'z.unknown()', optional: false });\n }\n\n // Query / headers — whole objects, optional.\n if (op.query) props.push({ key: 'query', expr: paramSourceSchema(op.query, modelsWithInput), optional: true });\n if (op.headers) props.push({ key: 'headers', expr: paramSourceSchema(op.headers, modelsWithInput), optional: true });\n\n return props;\n}\n\nfunction refSchema(name: string, modelsWithInput?: Set<string>): string {\n return modelsWithInput?.has(name) ? `${name}Input` : name;\n}\n\nfunction paramSourceSchema(src: ParamSource, modelsWithInput?: Set<string>): string {\n if (src.kind === 'ref') return refSchema(src.name, modelsWithInput);\n if (src.kind === 'type') return renderInputType(src.node, modelsWithInput);\n const fields = src.nodes.map(n => `${quoteKey(n.name)}: ${renderInputType(n.type, modelsWithInput)}`).join(', ');\n return `z.object({ ${fields} })`;\n}\n\nfunction argsSchemaExpr(props: ArgsProp[]): string {\n if (props.length === 0) return 'z.object({})';\n const fields = props.map(p => `${quoteKey(p.key)}: ${p.expr}${p.optional ? '.optional()' : ''}`).join(', ');\n return `z.object({ ${fields} })`;\n}\n\n// ─── Output schema ──────────────────────────────────────────────────────────\n\n/**\n * The body an MCP tool reports as its output: the first body the service can actually return.\n *\n * Documented and thrown statuses are skipped — an MCP tool describes what a successful call\n * produces, not what the operation is allowed to document.\n */\nfunction primaryResponseBody(op: OpOperationNode): ContractTypeNode | undefined {\n for (const resp of emittedResponses(op)) {\n if (resp.bodies[0]) return resp.bodies[0].bodyType;\n }\n return undefined;\n}\n\n/** MCP output schemas must be objects — only model refs and inline objects qualify. */\nfunction outputSchemaExpr(op: OpOperationNode): string | undefined {\n const body = primaryResponseBody(op);\n if (!body) return undefined;\n if (body.kind === 'ref') return body.name;\n if (body.kind === 'inlineObject') return renderType(body);\n return undefined;\n}\n\n// ─── Annotations ────────────────────────────────────────────────────────────\n\nconst HINT_KEYS = ['readOnlyHint', 'destructiveHint', 'idempotentHint', 'openWorldHint'] as const;\n\nfunction annotationsExpr(cfg: McpConfigNode | undefined): string | undefined {\n if (!cfg) return undefined;\n const parts: string[] = [];\n for (const key of HINT_KEYS) {\n const val = cfg[key];\n if (val !== undefined) parts.push(`${key}: ${val}`);\n }\n return parts.length > 0 ? `{ ${parts.join(', ')} }` : undefined;\n}\n\n// ─── Schema-import collection ───────────────────────────────────────────────\n\nfunction walkTypeRefs(type: ContractTypeNode, ids: Set<string>, variant: 'input' | 'read', modelsWithInput?: Set<string>): void {\n switch (type.kind) {\n case 'ref':\n ids.add(variant === 'input' ? refSchema(type.name, modelsWithInput) : type.name);\n break;\n case 'array':\n walkTypeRefs(type.item, ids, variant, modelsWithInput);\n break;\n case 'tuple':\n type.items.forEach(t => walkTypeRefs(t, ids, variant, modelsWithInput));\n break;\n case 'record':\n walkTypeRefs(type.key, ids, variant, modelsWithInput);\n walkTypeRefs(type.value, ids, variant, modelsWithInput);\n break;\n case 'union':\n case 'discriminatedUnion':\n case 'intersection':\n type.members.forEach(t => walkTypeRefs(t, ids, variant, modelsWithInput));\n break;\n case 'inlineObject':\n type.fields.forEach(f => walkTypeRefs(f.type, ids, variant, modelsWithInput));\n break;\n case 'lazy':\n walkTypeRefs(type.inner, ids, variant, modelsWithInput);\n break;\n }\n}\n\nfunction walkSourceRefs(src: ParamSource | undefined, ids: Set<string>, modelsWithInput?: Set<string>): void {\n if (!src) return;\n if (src.kind === 'ref') ids.add(refSchema(src.name, modelsWithInput));\n else if (src.kind === 'params') src.nodes.forEach(n => walkTypeRefs(n.type, ids, 'input', modelsWithInput));\n else walkTypeRefs(src.node, ids, 'input', modelsWithInput);\n}\n\n/** Collect every schema identifier the emitted tools import (input variants + read variants for output). */\nfunction collectSchemaIds(ops: { route: OpRouteNode; op: OpOperationNode }[], modelsWithInput?: Set<string>): Set<string> {\n const ids = new Set<string>();\n for (const { route, op } of ops) {\n walkSourceRefs(route.params, ids, modelsWithInput);\n const bodies = op.request?.bodies ?? [];\n if (bodies.length === 1 && bodies[0]!.contentType !== 'multipart/form-data') {\n walkTypeRefs(bodies[0]!.bodyType, ids, 'input', modelsWithInput);\n }\n walkSourceRefs(op.query, ids, modelsWithInput);\n walkSourceRefs(op.headers, ids, modelsWithInput);\n\n const body = primaryResponseBody(op);\n if (body && (body.kind === 'ref' || body.kind === 'inlineObject')) walkTypeRefs(body, ids, 'read');\n }\n return ids;\n}\n\nfunction schemaImportLines(ids: Set<string>, options: McpCodegenOptions): string[] {\n const lines: string[] = [];\n const { modelOutPaths, outPath } = options;\n if (ids.size === 0) return lines;\n if (modelOutPaths && outPath) {\n const byFile = new Map<string, string[]>();\n const unresolved: string[] = [];\n for (const id of ids) {\n const p = modelOutPaths.get(id);\n if (p) {\n const group = byFile.get(p) ?? [];\n group.push(id);\n byFile.set(p, group);\n } else {\n unresolved.push(id);\n }\n }\n const fromDir = dirname(outPath);\n for (const [file, names] of byFile) {\n let rel = relative(fromDir, file).replace(/\\.ts$/, '.js');\n if (!rel.startsWith('.')) rel = './' + rel;\n lines.push(`import { ${names.sort().join(', ')} } from '${rel}';`);\n }\n for (const id of unresolved.sort()) lines.push(`import { ${id} } from './${pascalToDotCase(id)}.js';`);\n } else {\n for (const id of [...ids].sort()) lines.push(`import { ${id} } from './${pascalToDotCase(id)}.js';`);\n }\n return lines;\n}\n\n// ─── Zod scalar helper preludes ─────────────────────────────────────────────\n\nfunction scalarHelperLines(body: string): string[] {\n const lines: string[] = [];\n if (body.includes('_ZodBinary')) {\n lines.push(`const _ZodBinary = z.custom<Buffer>((val) => Buffer.isBuffer(val), { error: 'Must be binary data' });`);\n }\n if (body.includes('_ZodDatetime')) {\n lines.push(\n `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' }));`,\n );\n }\n if (body.includes('_ZodDecimal')) {\n lines.push(...DECIMAL_PRELUDE_LINES);\n }\n if (body.includes('_ZodInterval')) {\n lines.push(\n `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()!);`,\n );\n }\n if (body.includes('_ZodJson')) {\n lines.push(`type _JsonValue = string | number | boolean | null | _JsonValue[] | { [key: string]: _JsonValue };`);\n lines.push(\n `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)]));`,\n );\n }\n return lines;\n}\n\n// ─── Per-tool codegen ─────────────────────────────────────────────────────\n\ninterface ToolPlan {\n route: OpRouteNode;\n op: OpOperationNode;\n toolName: string;\n className: string;\n argsConstName: string;\n}\n\nfunction planTools(root: OpRootNode, includeInternal: boolean): ToolPlan[] {\n const plans: ToolPlan[] = [];\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!op.mcp) continue;\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n const toolName = deriveToolName(op, route);\n const className = deriveToolClassName(toolName);\n plans.push({ route, op, toolName, className, argsConstName: `${toPascal(toolName)}Args` });\n }\n }\n return plans;\n}\n\nfunction renderToolClass(plan: ToolPlan, file: string, options: McpCodegenOptions): string[] {\n const { route, op, toolName, className, argsConstName } = plan;\n const cfg = mcpConfig(op);\n const lines: string[] = [];\n\n // JSDoc source link\n lines.push('/**');\n lines.push(` * from ${sourceLink(basename(file), options.outPath, file, op.loc.line)}`);\n lines.push(' */');\n\n lines.push('@Injectable()');\n lines.push(`export class ${className} implements McpToolHandler {`);\n\n // definition\n lines.push(' readonly definition: Tool = {');\n lines.push(` name: '${escapeSingleQuoted(toolName)}',`);\n if (cfg?.title) lines.push(` title: '${escapeSingleQuoted(cfg.title)}',`);\n const desc = cfg?.description ?? op.description ?? route.description;\n if (desc) lines.push(` description: '${escapeSingleQuoted(desc)}',`);\n lines.push(` inputSchema: z.toJSONSchema(${argsConstName}, { unrepresentable: 'any' }) as Tool['inputSchema'],`);\n const outExpr = outputSchemaExpr(op);\n if (outExpr) lines.push(` outputSchema: z.toJSONSchema(${outExpr}, { unrepresentable: 'any' }) as Tool['outputSchema'],`);\n const annotations = annotationsExpr(cfg);\n if (annotations) lines.push(` annotations: ${annotations},`);\n lines.push(' };');\n lines.push('');\n\n // constructor injects the operation's service\n const service = inferService(op, route, file);\n lines.push(` constructor(private readonly service: ${service.className}) {}`);\n lines.push('');\n\n // handle\n const props = buildArgsProps(route, op, options.modelsWithInput);\n const destructure = props.map(p => p.key);\n const callArgs = buildArgs(route, op);\n const isVoid = !primaryResponseBody(op);\n const structured = !!outExpr;\n\n // No args to destructure means the parameter goes unread, which trips no-unused-vars in\n // consumers that lint generated output; the leading underscore opts it out.\n const argsParam = destructure.length > 0 ? 'args' : '_args';\n lines.push(` async handle(${argsParam}: Record<string, unknown>, _context: McpToolContext): Promise<CallToolResult> {`);\n if (destructure.length > 0) {\n lines.push(` const { ${destructure.join(', ')} } = await parseAndValidate(args, ${argsConstName});`);\n }\n if (isVoid) {\n lines.push(` await this.service.${service.methodName}(${callArgs});`);\n lines.push(` return { content: [{ type: 'text', text: 'OK' }] };`);\n } else {\n lines.push(` const result = await this.service.${service.methodName}(${callArgs});`);\n if (structured) {\n lines.push(` return { content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result };`);\n } else {\n lines.push(` return { content: [{ type: 'text', text: JSON.stringify(result) }] };`);\n }\n }\n lines.push(' }');\n lines.push('}');\n\n return lines;\n}\n\n// ─── Public entry points ────────────────────────────────────────────────────\n\n/** The exported register-fn name for an op-root file, e.g. `payments.op` → `registerPaymentsMcpTools`. */\nexport function deriveMcpRegisterFnName(file: string): string {\n return `register${deriveBaseName(file)}McpTools`;\n}\n\n/** Generate one `<filename>.mcp.ts` for an op-root: tool handler classes + a per-file register fn. */\nexport function generateMcpFile(root: OpRootNode, options: McpCodegenOptions = {}): string {\n const includeInternal = options.includeInternal ?? false;\n const plans = planTools(root, includeInternal);\n\n // Args schema consts (also drive the JSON-Schema definitions).\n const argsConsts = plans.map(p => `const ${p.argsConstName} = ${argsSchemaExpr(buildArgsProps(p.route, p.op, options.modelsWithInput))};`);\n\n // Tool classes.\n const classes = plans.map(p => renderToolClass(p, root.file, options).join('\\n'));\n\n // Per-file register fn.\n const registerFn: string[] = [];\n registerFn.push(`/** Add this file's tools to the shared catalog. */`);\n registerFn.push(`export function ${deriveMcpRegisterFnName(root.file)}(map: McpToolHandlerMap, container: Container): void {`);\n for (const p of plans) registerFn.push(` map.set('${escapeSingleQuoted(p.toolName)}', container.get(${p.className}));`);\n registerFn.push('}');\n\n const bodyCore = [argsConsts.join('\\n'), classes.join('\\n\\n'), registerFn.join('\\n')].filter(Boolean).join('\\n\\n');\n\n // Zod scalar helper consts (must precede the args consts that reference them).\n const helperConsts = scalarHelperLines(bodyCore);\n const bodyWithHelpers = [helperConsts.join('\\n'), bodyCore].filter(Boolean).join('\\n\\n');\n\n // ── Imports ──\n const needsParseAndValidate = plans.some(p => buildArgsProps(p.route, p.op, options.modelsWithInput).length > 0);\n const imports: string[] = [];\n imports.push(`import { Injectable, type Container } from 'injectkit';`);\n imports.push(`import { z } from 'zod';`);\n\n const luxon: string[] = [];\n if (/\\bDateTime\\b/.test(bodyWithHelpers)) luxon.push('DateTime');\n if (/\\bInterval\\b/.test(bodyWithHelpers)) luxon.push('Interval');\n if (/\\bDuration\\b/.test(bodyWithHelpers)) luxon.push('Duration');\n if (luxon.length > 0) imports.push(`import { ${luxon.join(', ')} } from 'luxon';`);\n if (/\\bDecimal\\b/.test(bodyWithHelpers)) imports.push(DECIMAL_IMPORT);\n\n imports.push(`import type { CallToolResult, Tool } from '@modelcontextprotocol/sdk/types.js';`);\n imports.push(`import type { McpToolHandler, McpToolHandlerMap, McpToolContext } from '@maroonedsoftware/mcp';`);\n if (needsParseAndValidate) imports.push(`import { parseAndValidate } from '@maroonedsoftware/zod';`);\n\n // Service imports (one per distinct service used by the emitted tools).\n const serviceModules = new Map<string, string>();\n for (const p of plans) {\n const svc = inferService(p.op, p.route, root.file).className;\n if (!serviceModules.has(svc)) {\n serviceModules.set(svc, root.services?.[svc] ?? root.meta[svc] ?? deriveModulePath(svc, options.servicePathTemplate));\n }\n }\n for (const [svc, mod] of [...serviceModules.entries()].sort(([a], [b]) => a.localeCompare(b))) {\n imports.push(`import { ${svc} } from '${mod}';`);\n }\n\n // Schema imports.\n imports.push(...schemaImportLines(collectSchemaIds(plans, options.modelsWithInput), options));\n\n const header = `// Auto-generated MCP tools\\n// generated from ${sourceLink(basename(root.file), options.outPath, root.file)}`;\n\n return `${header}\\n${imports.join('\\n')}\\n\\n${bodyWithHelpers}\\n`;\n}\n\n/** One entry per emitted `<filename>.mcp.ts` for the aggregator to import. */\nexport interface McpAggregatorEntry {\n /** The file's exported register fn name, e.g. `registerPaymentsMcpTools`. */\n registerFn: string;\n /** Module specifier for the file, relative to the aggregator and `.js`-suffixed. */\n importPath: string;\n}\n\n/** Generate the aggregator `mcp.tools.ts` that assembles the single McpToolHandlerMap. */\nexport function generateMcpAggregator(entries: McpAggregatorEntry[]): string {\n const sorted = [...entries].sort((a, b) => a.registerFn.localeCompare(b.registerFn));\n const lines: string[] = [];\n lines.push(`import { type Container } from 'injectkit';`);\n lines.push(`import { McpToolHandlerMap } from '@maroonedsoftware/mcp';`);\n for (const e of sorted) lines.push(`import { ${e.registerFn} } from '${e.importPath}';`);\n lines.push('');\n lines.push('/**');\n lines.push(' * Build the MCP tool catalog.');\n lines.push(' *');\n lines.push(' * Bind it to the `McpToolHandlerMap` token from a factory, which is what supplies the');\n lines.push(' * `Container` needed to resolve each handler:');\n lines.push(' *');\n lines.push(' * ```ts');\n lines.push(' * registry.register(McpToolHandlerMap).useFactory(registerMcpTools).asSingleton();');\n lines.push(' * ```');\n lines.push(' */');\n lines.push('export function registerMcpTools(container: Container): McpToolHandlerMap {');\n lines.push(' const map = new McpToolHandlerMap();');\n for (const e of sorted) lines.push(` ${e.registerFn}(map, container);`);\n lines.push(' return map;');\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Generate the optional `mcp.router.ts` — the standard ServerKit route wiring for the dispatcher.\n *\n * The whole file is framework-specific boilerplate rather than a per-operation render, so the\n * adapter owns the template. Defaults to Koa, matching the router generator.\n */\nexport function generateMcpRouter(options: { path?: string; framework?: ServerFramework } = {}): string {\n const framework = options.framework ?? KOA_SERVER_FRAMEWORK;\n return framework.mcpRouter({ path: options.path ?? '/mcp' });\n}\n","import { resolve, join, relative, dirname, isAbsolute } from 'node:path';\nimport type { ContractRootNode, OpRootNode } from '@contractkit/core';\nimport { collectTypeRefs, collectPublicTypeNames } from '@contractkit/core';\n\nexport const TEMPLATE_VAR_RE = /\\{\\w+\\}/;\n\n/**\n * Guard against path traversal in output-path templates. Output-path template variables\n * (`{area}`, `{dir}`, `{filename}`, `{name}`) can be sourced from a `.ck` file's\n * `options { keys }` block, so a malicious value like `../../../tmp/x` could escape the\n * plugin's output directory. After the final absolute path is computed, verify it stays\n * within `baseOutDir`; otherwise throw.\n */\nfunction assertWithinBase(baseOutDir: string, outPath: string): string {\n const rel = relative(resolve(baseOutDir), resolve(outPath));\n if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) {\n throw new Error(\n `Refusing to emit outside output directory: resolved path \"${outPath}\" escapes \"${baseOutDir}\" (check options { keys } values used in output path templates)`,\n );\n }\n return outPath;\n}\n\n/** Global-flagged twin of {@link TEMPLATE_VAR_RE}, for finding every variable in a string. */\nexport const TEMPLATE_VAR_RE_G = /\\{(\\w+)\\}/g;\n\n/**\n * Substitute `{key}` placeholders from `vars`.\n *\n * An unknown key is left in place rather than throwing, because the caller is mid-way through\n * building a path and has better context for the complaint — see the check at the emit funnel in\n * `index.ts`, which reports it against the file it would have been written to.\n */\nexport function resolveTemplate(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{(\\w+)\\}/g, (_, key) => vars[key] ?? `{${key}}`);\n}\n\nexport function includesFilename(p: string): boolean {\n const last = p.split('/').pop() ?? '';\n return last.includes('.');\n}\n\nexport function commonDir(files: string[], rootDir: string): string {\n if (files.length === 0) return resolve(rootDir);\n const parts = files.map(f => dirname(f).split('/'));\n const first = parts[0]!;\n let depth = first.length;\n for (const p of parts) {\n for (let i = 0; i < depth; i++) {\n if (p[i] !== first[i]) {\n depth = i;\n break;\n }\n }\n }\n return first.slice(0, depth).join('/') || '/';\n}\n\n// ─── Server / Zod output paths ─────────────────────────────────────────────\n\nexport function computeOpOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n const baseName = filePath.split('/').pop()!;\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n const defaultName = `${filename}${defaultSuffix}`;\n const baseOutDir = resolve(baseDir);\n\n if (output && TEMPLATE_VAR_RE.test(output)) {\n const resolved = resolveTemplate(output, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return assertWithinBase(baseOutDir, join(baseOutDir, resolved));\n return assertWithinBase(baseOutDir, join(baseOutDir, resolved, defaultName));\n }\n if (output) {\n if (includesFilename(output)) return assertWithinBase(baseOutDir, join(baseOutDir, output));\n return assertWithinBase(baseOutDir, join(baseOutDir, output, relDir, defaultName));\n }\n return assertWithinBase(baseOutDir, join(baseOutDir, relDir, defaultName));\n}\n\nexport function computeContractOutPath(\n filePath: string,\n baseDir: string,\n output: string | undefined,\n defaultSuffix: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string {\n return computeOpOutPath(filePath, baseDir, output, defaultSuffix, commonRoot, meta);\n}\n\n// ─── SDK output paths ──────────────────────────────────────────────────────\n\nexport function computeSdkOutPath(\n filePath: string,\n rootDir: string,\n clientOutput: string | undefined,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.client.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return assertWithinBase(baseOutDir, join(baseOutDir, resolved));\n return assertWithinBase(baseOutDir, join(baseOutDir, resolved, defaultOutName));\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput));\n return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput, relDir, defaultOutName));\n }\n return assertWithinBase(baseOutDir, join(baseOutDir, relDir, defaultOutName));\n}\n\n/**\n * Resolve the output path for a synthesized `<area>.client.ts` — the file holding the\n * `<Area>Client` class that aggregates an area's inlined methods and subarea wiring.\n *\n * Uses the same `output.clients` template as leaf clients, with `{filename}` and `{area}`\n * substituted to the area name and `{subarea}` substituted to the empty string. Resulting\n * double-slashes from the empty substitution are collapsed, and a final segment that\n * would otherwise begin with a dot (e.g. `.client.ts` from `{subarea}.client.ts`) is\n * prefixed with the area so the file isn't hidden.\n */\nexport function computeSdkAreaClientOutPath(area: string, rootDir: string, clientOutput: string | undefined): string {\n const filename = area;\n const baseOutDir = resolve(rootDir);\n const fixHiddenSegment = (path: string): string => {\n const segments = path.split('/');\n const last = segments[segments.length - 1] ?? '';\n if (last.startsWith('.')) segments[segments.length - 1] = `${filename}${last}`;\n return segments.join('/');\n };\n if (clientOutput && TEMPLATE_VAR_RE.test(clientOutput)) {\n const resolved = resolveTemplate(clientOutput, { filename, dir: '', ext: 'ck', area, subarea: '' });\n const cleaned = fixHiddenSegment(resolved.replace(/\\/+/g, '/').replace(/^\\//, ''));\n if (includesFilename(cleaned)) return assertWithinBase(baseOutDir, join(baseOutDir, cleaned));\n return assertWithinBase(baseOutDir, join(baseOutDir, cleaned, `${filename}.client.ts`));\n }\n if (clientOutput) {\n if (includesFilename(clientOutput)) return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput));\n return assertWithinBase(baseOutDir, join(baseOutDir, clientOutput, `${filename}.client.ts`));\n }\n return assertWithinBase(baseOutDir, join(baseOutDir, `${filename}.client.ts`));\n}\n\nexport function computeSdkTypeOutPath(\n filePath: string,\n rootDir: string,\n typeOutput: string,\n commonRoot: string,\n meta: Record<string, string> = {},\n): string | null {\n if (!filePath.endsWith('.ck')) return null;\n const baseName = filePath.split('/').pop()!;\n const defaultOutName = baseName.replace(/\\.ck$/, '.ts');\n const baseOutDir = resolve(rootDir);\n const relDir = relative(commonRoot, dirname(filePath));\n const filename = baseName.replace(/\\.ck$/, '');\n\n if (TEMPLATE_VAR_RE.test(typeOutput)) {\n const resolved = resolveTemplate(typeOutput, { filename, dir: relDir, ext: 'ck', ...meta });\n if (includesFilename(resolved)) return assertWithinBase(baseOutDir, join(baseOutDir, resolved));\n return assertWithinBase(baseOutDir, join(baseOutDir, resolved, defaultOutName));\n }\n if (includesFilename(typeOutput)) return assertWithinBase(baseOutDir, join(baseOutDir, typeOutput));\n return assertWithinBase(baseOutDir, join(baseOutDir, typeOutput, relDir, defaultOutName));\n}\n\nexport function generateBarrelFiles(contractPaths: string[]): { outPath: string; content: string }[] {\n const byDir = new Map<string, string[]>();\n for (const outPath of contractPaths) {\n const dir = dirname(outPath);\n const group = byDir.get(dir) ?? [];\n group.push(outPath);\n byDir.set(dir, group);\n }\n const results: { outPath: string; content: string }[] = [];\n for (const [dir, files] of byDir) {\n const exports = files\n .map(f => `export * from './${f.split('/').pop()!.replace(/\\.ts$/, '.js')}';`)\n .sort()\n .join('\\n');\n results.push({ outPath: join(dir, 'index.ts'), content: `// Auto-generated barrel file\\n${exports}\\n` });\n }\n return results;\n}\n\nexport function computePubliclyReachableTypes(\n opAsts: OpRootNode[],\n contractAsts: ContractRootNode[],\n modelsWithInput: Set<string>,\n modelsWithOutput: Set<string> = new Set(),\n): Set<string> | null {\n if (opAsts.length === 0) return null;\n const reachable = new Set<string>();\n for (const opAst of opAsts) {\n for (const name of collectPublicTypeNames(opAst, modelsWithInput, modelsWithOutput)) reachable.add(name);\n }\n const modelDeps = new Map<string, Set<string>>();\n for (const contractAst of contractAsts) {\n for (const model of contractAst.models) {\n const deps = new Set<string>();\n if (model.bases) for (const b of model.bases) deps.add(b);\n if (model.type) collectTypeRefs(model.type, deps);\n for (const field of model.fields) collectTypeRefs(field.type, deps);\n modelDeps.set(model.name, deps);\n }\n }\n const frontier = [...reachable];\n while (frontier.length > 0) {\n const name = frontier.pop()!;\n const baseName = name.endsWith('Input') ? name.slice(0, -5) : name.endsWith('Output') ? name.slice(0, -6) : name;\n for (const dep of modelDeps.get(baseName) ?? []) {\n if (!reachable.has(dep)) {\n reachable.add(dep);\n frontier.push(dep);\n }\n if (modelsWithInput.has(dep)) {\n const inputDep = `${dep}Input`;\n if (!reachable.has(inputDep)) {\n reachable.add(inputDep);\n frontier.push(inputDep);\n }\n }\n if (modelsWithOutput.has(dep)) {\n const outputDep = `${dep}Output`;\n if (!reachable.has(outputDep)) {\n reachable.add(outputDep);\n frontier.push(outputDep);\n }\n }\n }\n }\n return reachable;\n}\n"],"mappings":";;;;AAAA,SAASA,WAAAA,UAASC,QAAAA,OAAMC,YAAAA,WAAUC,WAAAA,UAASC,YAAAA,iBAAgB;AAC3D,SAASC,YAAYC,cAAcC,eAAeC,WAAWC,QAAQC,aAAaC,iBAAiB;;;ACDnG,SAASC,YAAAA,WAAUC,WAAAA,gBAAe;AAkBlC,SACIC,iBACAC,2BAA2BC,2BAC3BC,6BAA6BC,mCAC1B;;;ACtBP,SAASC,SAASC,gBAAgB;AAI3B,IAAMC,uBAAuB;AAG7B,SAASC,SAASC,MAAY;A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I6P,cAAcjS,SAASkS,IAAAA,EAAO,QAAOA;AACzC,QAAMpD,OAAOoD,KAAK9P,QAAQ,WAAW,EAAA;AACrC,SAAO6P,cAAcjS,SAAS8O,IAAAA,IAAQA,OAAOoD;AACjD;AALSP;AAOT,SAASI,sBAAqBrR,MAAcyR,UAAiB;AACzD,QAAMrD,OACFpO,KACKmJ,MAAM,GAAA,EACNkF,IAAG,GACF3M,QAAQ,cAAc,EAAA,KAAO;AACvC,QAAMgQ,SAAStD,KAAKjF,MAAM,GAAA,EAAK,CAAA,KAAMiF;AACrC,MAAIqD,UAAU;AACV,WAAOA,SAAS/P,QAAQ,eAAegQ,MAAAA,EAAQhQ,QAAQ,aAAa0M,IAAAA;EACxE;AACA,SAAO,YAAYsD,MAAAA;AACvB;AAXSL,OAAAA,uBAAAA;AAgBF,SAASM,qBAAAA;AACZ,SAAO;IACH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACAtP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACFD,KAAK,IAAA;AACX;AAxGgBuP;AA6GhB,IAAMC,wBAAwB;EAC1BC,KAAK;EACLvO,OAAO;EACPwO,WAAW;EACXC,YAAY;EACZC,YAAY;AAChB;AAiBO,SAASC,uBAAuBC,OAA8C;AACjF,QAAMC,eAAuC,CAAC;AAC9C,MAAID,MAAME,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A;QACtB,OAAO;AACH;QACJ;MACJ,QAAQ;AACJ;MACJ;IACJ;EACJ;AACJ;AAzBSvP;AA4BT,SAASsF,gBAAgB5H,QAAe;AACpC,SAAOgS,KAAKC,UAAUjS,UAAU,IAAA;AACpC;AAFS4H;","names":["resolve","join","relative","dirname","basename","existsSync","readFileSync","writeFileSync","mkdirSync","rmSync","readdirSync","rmdirSync","relative","dirname","collectTypeRefs","computeModelsWithOutput","ckComputeModelsWithOutput","collectExternalOutputRefs","ckCollectExternalOutputRefs","dirname","relative","JSON_VALUE_TYPE_DECL","quoteKey","name","test","escapeJsDocLines","text","replace","split","escapeSingleQuoted","s","sourceLink","label","outPath","sourceFile","line","rel","relative","dirname","href","startsWith","undefined","headerNameToProperty","parts","filter","Boolean","map","p","i","lower","toLowerCase","charAt","toUpperCase","slice","join","renderTsType","type","target","kind","renderTsScalar","inner","item","needsParens","items","key","value","values","v","String","members","m","renderTsInlineObject","fields","_exhaustive","Error","entries","f","opt","optional","renderInputTsType","modelsWithInput","size","has","renderOutputTsType","modelsWithOutput","DECIMAL_IMPORT","DECIMAL_CONFIG_LINE","DECIMAL_ZOD_SCHEMA_LINE","DECIMAL_PRELUDE_LINES","COERCE_DECLS","DECIMAL_COERCE_DECL","coerceDeclsFor","lines","haystack","join","Object","entries","filter","prefix","includes","flatMap","decl","coerceLuxonImports","needed","Set","add","sort","reviveFnName","model","variant","applyCase","name","caseTransform","replace","c","toLowerCase","charAt","toUpperCase","slice","DEFAULT_REVIVABLE_SCALARS","typeReachesDecimal","type","opts","kind","revivableScalars","has","modelsWithDecimal","item","inner","items","some","t","value","members","fields","f","scalarCoercion","slot","path","format","Scope","n","next","emit","scope","reviveRefName","arr","i","map","l","idx","rec","k","relevant","length","obj","body","fieldStatements","undefined","m","real","target","find","branches","disc","member","tag","discriminatorTag","discriminator","push","JSON","stringify","modelMap","get","field","values","objVar","outputCase","key","optional","nullable","modelsWithOutput","renderInlineReviver","fnName","tsType","renderReviveFunctions","renderOne","typeName","modeToWrapper","mode","computeModelsWithInput","models","externalModelsWithInput","Set","result","model","fields","some","f","visibility","add","name","changed","has","refs","field","collectTypeRefs","type","bases","b","ref","generateComments","outPath","lines","push","deprecated","description","l","escapeJsDocLines","sourceLink","loc","file","line","generateContract","root","context","needsDateTime","rootNeedsDateTime","needsDuration","rootNeedsScalar","needsInterval","needsBinary","needsDatetime","needsJson","needsDecimal","externalRefs","collectExternalRefs","modelsWithInput","localModelsWithInput","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","ckComputeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","ckCollectExternalOutputRefs","allExternalRefs","sort","luxonImports","length","join","DECIMAL_IMPORT","importPath","resolveImportPath","names","emitRevivers","modelsWithDecimal","reviveFnName","target","DECIMAL_PRELUDE_LINES","modelMap","Map","map","m","reviveOpts","undefined","bodyLines","topoSortModels","generateModel","currentOutPath","revivers","renderReviveFunctions","coerceDecls","coerceDeclsFor","flattenFormatChain","firstBase","parent","get","flatParent","parentHasFormat","inputCase","outputCase","merged","set","values","generateTypeAlias","effective","needsInputSplit","generateThreeSchemaModel","generateSimpleModel","renderType","renderInputType","wrapper","hasInputTransform","hasOutputTransform","inputBody","renderFieldsAsSnakeCase","renderFieldsAsPascalCase","renderFields","inputKey","applyCase","outputKey","optional","guard","quoteKey","typeSource","body","head","tail","slice","buildExtendChain","resolveName","collectEffectiveWritableFieldNames","modelName","base","delete","allFields","readFields","filter","readBody","writeFields","writeBody","renderInputFields","fieldsToOmit","omitClause","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","caseTransform","defaultMode","flatMap","renderField","pascalKey","expr","default","nullable","dv","escapeString","String","snakeKey","applyFieldModifiers","parseCaseTransform","kind","renderScalar","renderArray","renderTuple","renderRecord","renderEnum","renderLiteral","renderUnion","renderDiscriminatedUnion","renderIntersection","inner","renderInlineObject","renderRegexLiteral","source","regexHasAnchor","startsWith","endsWith","i","backslashes","NUMERIC_PREPROCESS","e","min","max","len","regex","checks","scale","messageParts","fmt","format","validParts","validation","message","_exhaustive","Error","a","item","t","items","r","key","value","vals","v","u","members","discriminator","first","rest","every","member","fieldLines","o","snakeLines","joined","transformEntries","pascalLines","renderInputScalar","renderInputField","renderQueryType","renderQueryField","isValidIdentifier","test","typeNeedsDateTime","typeNeedsScalar","localNames","collectInputTypeRefs","out","forEach","deps","localDeps","inDegree","d","dep","remaining","queue","sorted","shift","other","rem","includes","refName","refOutPath","modelOutPaths","fromDir","dirname","rel","relative","moduleName","pascalToDotCase","resolveModifiers","resolveSecurity","SECURITY_NONE","classifyContentType","emittedResponses","PATH_PARAM_RE_G","toIdentifier","basename","dirname","relative","KOA_RUNTIME_MODULE","KOA_RUNTIME_SYMBOLS","KOA_SERVER_FRAMEWORK","name","imports","uses","symbols","filter","length","join","routerDeclaration","routerName","pathParam","identifier","handlerLocals","routeOpen","method","path","middlewares","middlewareStr","routeClose","middleware","policy","args","bodyParser","tokensExpr","signature","request","params","query","headers","parsedBody","contentType","resolveService","className","response","status","expr","header","valueExpr","type","send","bodyExpr","undefined","caseEnd","mcpRouter","GENERATOR_HANDLER_LOCALS","bindPathParams","nodes","handlerLocals","reserved","Set","taken","bindings","Map","node","local","toIdentifier","name","has","add","set","bodyParserToken","contentType","classifyContentType","bodyTypesStructurallyEqual","a","b","kind","bb","min","max","len","scale","regex","format","item","items","length","every","x","i","key","value","values","v","members","m","discriminator","lazy","inner","mode","fields","f","g","optional","nullable","visibility","default","deprecated","type","generateOp","root","options","resolved","framework","KOA_SERVER_FRAMEWORK","types","collectTypes","modelsWithInput","modelsWithOutput","services","collectServices","routerName","deriveRouterName","file","lines","push","sourceLink","basename","outPath","routerDeclaration","includeInternal","route","routes","op","operations","resolveModifiers","includes","generateHandler","handlerBody","join","references","symbol","RegExp","test","helpers","DECIMAL_PRELUDE_LINES","needsZodJson","generated","uses","body","imports","svc","filter","modulePath","meta","deriveModulePath","servicePathTemplate","usedTypes","generateTypeImports","luxonImports","DECIMAL_IMPORT","allContent","needsZod","desc","description","l","escapeJsDocLines","loc","line","effectiveSecurity","resolveSecurity","SECURITY_NONE","mods","method","path","replace","PATH_PARAM_RE_G","_m","pathParam","bodies","request","hasBody","isSingleMultipart","middlewares","policy","args","undefined","middleware","parserTokens","Array","from","map","tokensExpr","t","bodyParser","signature","sigArgs","signaturePolicy","escapeSingleQuoted","routeOpen","pathBindings","params","generateParamValidation","paramsMode","query","queryMode","headers","headersMode","parsedBody","renderInputType","bodyType","annotation","emitted","emittedResponses","serviceParts","inferService","call","methodName","buildArgs","generateMultiStatusResult","className","generateSingleStatusResult","routeClose","resp","respHeaders","hasRespHeaders","headersAnnotation","renderHeadersAnnotation","bodySchema","prelude","formatTypeAnnotation","responseBodySchema","resolveService","rendered","renderResponseMembers","includeStatus","varPrefix","preludes","response","status","String","statusCode","headerSetLines","indent","send","responseBodyExpr","bodySchemas","member","get","caseEnd","opts","leading","trailing","uniform","h","quoteKey","headerNameToProperty","renderOutputTsType","pad","accessor","JSON","stringify","write","header","service","cls","split","baseName","deriveBaseName","inferMethodName","hasParam","p","serverTsScalar","_exhaustive","Error","varName","schema","renderType","isRevalidatable","modelsWithTransform","rec","first","rest","usesExtendChain","preludeVar","validateResponses","source","sourceExpr","suffix","isQuery","isPathParams","typeName","bind","lhs","wire","modeToWrapper","param","bound","isValidIdentifier","base","renderQueryType","applyFieldModifiers","opFile","modelOutPaths","byFile","unresolved","typeOutPath","group","fromDir","dirname","names","rel","relative","startsWith","sort","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","responses","collectOutputTypeNodeRefs","out","forEach","inferredService","pop","s","charAt","toUpperCase","slice","serviceName","template","kebab","toLowerCase","module","runIncrementalCodegen","parseIncrementalManifest","emptyIncrementalManifest","serializeIncrementalManifest","hashFingerprint","collectTransitiveModelRefs","computeModelsWithCaseTransform","computeModelsWithScalar","resolveModifiers","isJsonMime","classifyContentType","observableResponses","thrownResponses","PATH_PARAM_RE_G","toIdentifier","basename","dirname","relative","jsonOrFormSerialize","varName","contentType","renderSerializeExpr","bodies","ctVar","arms","slice","last","length","expr","i","arm","classifyBodyStrategy","op","request","kind","body","every","b","bodyTypesStructurallyEqual","bodyType","some","hasPublicOperations","root","includeInternal","route","routes","operations","resolveModifiers","includes","generateSdk","options","lines","types","collectTypes","modelsWithInput","modelsWithOutput","clientClassName","deriveClientClassName","file","inlineRevivers","Map","classBody","mods","push","generateMethod","inlineReviverDecls","values","flat","decimalPrelude","decimalPreludeFor","errorAliases","generateErrorBodyAliases","referenced","referencedTypes","generateTypeImports","usedRevivers","imports","headerLuxon","headerLuxonImport","sdkOptionsPath","outPath","rel","relative","dirname","replace","startsWith","jsonImport","sdkNeedsJson","valueImports","sdkNeedsBigIntReplacer","sdkParsesJsonResponse","sdkResponsesUseBigInt","sdkNeedsQueryString","sdkNeedsReadContentType","join","JSON_VALUE_TYPE_DECL","decls","decl","sourceLink","basename","generateClientMethods","methodNames","deriveMethodName","declLines","preludeLines","flatMap","needsDecimalImport","coerceDeclsFor","preamble","l","DECIMAL_IMPORT","DECIMAL_CONFIG_LINE","luxon","coerceLuxonImports","methodLines","existingImports","undefined","needed","filter","c","emitted","haystack","t","escaped","RegExp","test","found","Set","m","matchAll","add","sort","revive","modelsWithDecimal","size","modelMap","nameHint","methodName","where","method","toUpperCase","path","mRevive","hint","charAt","httpMethod","params","buildMethodParams","paramStr","map","p","name","optional","type","observable","observableResponses","thrown","thrownResponses","isMultiStatus","primaryResponse","primaryBodies","isVoid","respHeaders","headers","hasRespHeaders","headersShape","renderSdkHeadersShape","returnMembers","returnType","r","sdkResponseMembers","dataType","sdkDataType","expectStatuses","statusCode","desc","description","errorBodyName","errorBodyTypeName","deprecated","tags","contentLines","escapeJsDocLines","member","urlExpr","buildUrlExpression","hasQuery","query","fetchUrl","strategy","hasBody","hasOpHeaders","defaultCt","nonMultipart","find","fetchArgs","cat","classifyContentType","lastHeaderIdx","findIndex","a","existing","inner","needsResult","resultPrefix","split","fallback","rest","resp","sdkReturnLines","headerEntries","sdkHeaderEntries","sdkReadExpr","category","renderOutputTsType","tsType","read","reviver","reviveExprFor","segment","ctx","opts","revivableScalars","typeReachesDecimal","refName","pick","reviveFnName","has","direct","item","fnName","renderInlineReviver","set","fields","h","quoteKey","headerNameToProperty","sdkHeaderEntry","raw","key","scalar","convert","v","format","Error","describeHeaderType","includeStatus","leading","trailing","dataTypes","indent","cast","entries","first","fallbackFields","PATH_PARAM_RE_G","_m","toIdentifier","access","JSON","stringify","nodes","renderInputTsType","typeName","node","ctUnion","inlineArgParam","normaliseOptionalOrder","source","isOptional","Boolean","default","lastRequired","reduce","sdk","nameToMethodName","inferMethodName","parts","toLowerCase","segments","s","seg","paramName","segParts","sp","deriveBaseName","base","pop","deriveClientPropertyName","getAreaSubarea","area","meta","subarea","pascal","value","camel","deriveAreaClientClassName","deriveAreaPropertyName","deriveSubareaClientClassName","deriveSubareaPropertyName","publicOps","collectParamSourceRefs","collectParamSourceInputRefs","collectTypeNodeRefs","collectInputTypeNodeRefs","responses","collectOutputTypeNodeRefs","out","members","forEach","f","param","isJsonMime","tainted","modelsWithBigInt","reachesBigInt","items","typeNeedsScalar","check","src","opFile","revivers","modelOutPaths","byFile","unresolved","typeOutPath","get","group","fromDir","names","fromHere","reviverModelName","moduleName","pascalToDotCase","typeImport","deriveTypeImportPath","typeImportPathTemplate","namesInModule","stem","template","module","generateSdkOptions","SCAFFOLD_DEP_VERSIONS","zod","decimalJs","typesLuxon","typescript","generateSdkPackageJson","input","dependencies","deps","decimal","devDependencies","pkg","version","main","exports","import","files","scripts","build","Object","keys","generateSdkTsconfig","tsconfig","compilerOptions","target","moduleResolution","declaration","outDir","rootDir","strict","esModuleInterop","skipLibCheck","forceConsistentCasingInFileNames","include","exclude","generateAreaClient","inlineFiles","subareaClients","className","collectedMethodLines","collectedRevivePrelude","areaNeedsDecimalImport","reviversByImportPath","collectedErrorAliases","seenMethods","typesByImportPath","unresolvedTypes","needsJson","needsBigIntReplacer","needsParseJson","needsBigIntReviver","needsQueryString","needsReadContentType","inline","codegenOptions","alias","modelOut","typesForFile","sdkOptionsRel","areaHeaderLuxon","importedClients","sc","client","importPath","propertyName","fetchModifier","ln","generateSdkAggregator","sdkOptionsImportPath","sdkClassName","pushClientImport","areas","topLevelClients","computeModelsWithOutput","collectExternalOutputRefs","generatePlainTypes","root","context","target","externalRefs","collectExternalRefs","lines","externalModelsWithInput","modelsWithInput","Set","localModelsWithInput","computeModelsWithInput","models","allModelsWithInput","externalModelsWithOutput","modelsWithOutput","localModelsWithOutput","computeModelsWithOutput","allModelsWithOutput","externalInputRefs","size","collectExternalInputRefs","externalOutputRefs","collectExternalOutputRefs","allExternalRefs","sort","needsDecimal","rootNeedsScalar","emitRevivers","modelsWithDecimal","some","m","has","name","push","DECIMAL_IMPORT","luxonImports","length","join","ref","importPath","resolveImportPath","reviveFnName","jsonValueImportPath","JSON_VALUE_TYPE_DECL","modelMap","Map","map","reviveOpts","undefined","bodyLines","model","topoSortModels","generateModel","currentOutPath","revivers","renderReviveFunctions","DECIMAL_CONFIG_LINE","coerceDecls","coerceDeclsFor","outPath","type","generateTypeAlias","needsInputSplit","fields","f","visibility","generateVisibilityModel","generateSimpleModel","generateOutputModel","collectInheritedFieldNames","bases","result","visit","get","add","b","computeOverrideNames","inherited","filter","override","generateComments","deprecated","description","l","escapeJsDocLines","sourceLink","loc","file","line","renderTsType","renderInputTsType","renderOutputTsType","buildExtendsClause","overrideNames","baseNameResolver","omitKeys","n","wrapped","field","renderField","readFields","writeFields","inputResolver","renderInputField","withFieldJsDoc","jsdocParts","contentLines","body","opt","optional","default","typeStr","nullable","quoteKey","camelToSnake","s","replace","c","toLowerCase","camelToPascal","charAt","toUpperCase","slice","applyOutputCase","outputCase","baseExt","renderOutputField","key","FASTIFY_RUNTIME_MODULE","FASTIFY_RUNTIME_SYMBOLS","FASTIFY_SERVER_FRAMEWORK","name","imports","uses","symbols","filter","length","join","routerDeclaration","routerName","pathParam","identifier","handlerLocals","routeOpen","method","path","middlewares","middlewareStr","routeClose","middleware","policy","args","bodyParser","tokensExpr","signature","request","params","query","headers","parsedBody","contentType","resolveService","className","response","status","expr","header","valueExpr","type","send","bodyExpr","undefined","caseEnd","mcpRouter","SERVER_FRAMEWORK_NAMES","DEFAULT_SERVER_FRAMEWORK_NAME","SERVER_FRAMEWORKS","koa","KOA_SERVER_FRAMEWORK","fastify","FASTIFY_SERVER_FRAMEWORK","resolveServerFramework","name","resolved","framework","Error","join","resolveModifiers","emittedResponses","toIdentifier","basename","dirname","relative","mcpConfig","op","mcp","undefined","hasMcpOperations","root","includeInternal","route","routes","operations","resolveModifiers","includes","toSnake","s","replace","toLowerCase","toPascal","split","filter","Boolean","map","p","charAt","toUpperCase","slice","join","inferToolName","method","path","parts","seg","startsWith","push","deriveToolName","cfg","name","sdk","deriveToolClassName","toolName","buildArgsProps","modelsWithInput","props","params","kind","node","nodes","key","toIdentifier","expr","renderInputType","type","optional","refSchema","bodies","request","length","contentType","bodyType","query","paramSourceSchema","headers","has","src","fields","n","quoteKey","argsSchemaExpr","primaryResponseBody","resp","emittedResponses","outputSchemaExpr","body","renderType","HINT_KEYS","annotationsExpr","val","walkTypeRefs","ids","variant","add","item","items","forEach","t","value","members","f","inner","walkSourceRefs","collectSchemaIds","ops","Set","schemaImportLines","options","lines","modelOutPaths","outPath","size","byFile","Map","unresolved","id","get","group","set","fromDir","dirname","file","names","rel","relative","sort","pascalToDotCase","scalarHelperLines","DECIMAL_PRELUDE_LINES","planTools","plans","className","argsConstName","renderToolClass","plan","sourceLink","basename","loc","line","escapeSingleQuoted","title","desc","description","outExpr","annotations","service","inferService","destructure","callArgs","buildArgs","isVoid","structured","argsParam","methodName","deriveMcpRegisterFnName","deriveBaseName","generateMcpFile","argsConsts","classes","registerFn","bodyCore","helperConsts","bodyWithHelpers","needsParseAndValidate","some","imports","luxon","test","DECIMAL_IMPORT","serviceModules","svc","services","meta","deriveModulePath","servicePathTemplate","mod","entries","a","b","localeCompare","header","generateMcpAggregator","sorted","e","importPath","generateMcpRouter","framework","KOA_SERVER_FRAMEWORK","mcpRouter","resolve","join","relative","dirname","isAbsolute","collectTypeRefs","collectPublicTypeNames","TEMPLATE_VAR_RE","assertWithinBase","baseOutDir","outPath","rel","relative","resolve","startsWith","isAbsolute","Error","TEMPLATE_VAR_RE_G","resolveTemplate","template","vars","replace","_","key","includesFilename","p","last","split","pop","includes","commonDir","files","rootDir","length","parts","map","f","dirname","first","depth","i","slice","join","computeOpOutPath","filePath","baseDir","output","defaultSuffix","commonRoot","meta","baseName","relDir","filename","defaultName","test","resolved","dir","ext","computeContractOutPath","computeSdkOutPath","clientOutput","endsWith","defaultOutName","computeSdkAreaClientOutPath","area","fixHiddenSegment","path","segments","subarea","cleaned","computeSdkTypeOutPath","typeOutput","generateBarrelFiles","contractPaths","byDir","Map","group","get","push","set","results","exports","sort","content","computePubliclyReachableTypes","opAsts","contractAsts","modelsWithInput","modelsWithOutput","Set","reachable","opAst","name","collectPublicTypeNames","add","modelDeps","contractAst","model","models","deps","bases","b","type","collectTypeRefs","field","fields","frontier","dep","has","inputDep","outputDep","BIGINT_SCALARS","Set","TYPESCRIPT_CODEGEN_VERSION","CACHE_MANIFEST_FILENAME","plugin","name","generateTargets","inputs","ctx","config","options","runTypescriptCodegen","rootDir","createTypescriptPlugin","assertValidConfig","framework","server","undefined","SERVER_FRAMEWORK_NAMES","includes","Error","String","join","validateResponses","zod","manifestPath","resolve","cacheDir","prevManifest","cacheEnabled","readManifest","emptyIncrementalManifest","units","globalFiles","collectServerOutput","sdk","collectSdkOutput","collectZodOutput","types","collectTypesOutput","mcp","collectMcpOutput","result","runIncrementalCodegen","codegenVersion","fileExists","existsSync","deleteStalePaths","deletedPaths","unresolved","relativePath","content","ifAbsent","filesToWrite","key","matchAll","TEMPLATE_VAR_RE_G","add","emitFile","entry","sort","outPath","split","warn","writeManifest","manifest","buildModelMap","contractRoots","map","Map","root","model","models","set","collectContractRootRefs","modelMap","seeds","m","type","push","f","fields","bases","b","kind","collectTransitiveModelRefs","collectOpRootRefs","route","routes","params","paramSourceTypes","op","operations","query","headers","request","body","bodies","bodyType","resp","responses","h","src","out","n","nodes","node","sliceOutPathMap","refs","modelOutPaths","modelsWithInput","modelsWithOutput","slice","ref","p","get","has","ip","sliceModelSet","ownNames","serverBase","baseDir","resolveServerFramework","modelsWithTransform","computeModelsWithCaseTransform","flatMap","r","allFiles","file","opRoots","commonRoot","commonDir","subConfigKey","stableSubConfig","serverModelOutPaths","typeEntries","output","ast","typeOutPath","computeContractOutPath","meta","fingerprint","hashFingerprint","v","outPathSlice","sub","render","renderCtx","currentOutPath","target","generateContract","generatePlainTypes","computeOpOutPath","servicePathTemplate","includeInternal","generateOp","sdkBase","sdkName","sdkOutput","sdkEntryPath","TEMPLATE_VAR_RE","test","resolveTemplate","sdkOptionsPath","dirname","modelsWithDecimal","computeModelsWithScalar","DEFAULT_REVIVABLE_SCALARS","modelsWithBigInt","ckCommonRoot","sdkModelOutPaths","sdkTypePaths","sdkClientInfos","sdkContractEntries","publicTypes","computePubliclyReachableTypes","computeSdkTypeOutPath","some","emitRevivers","rel","relative","replace","startsWith","jsonValueImportPath","areaBuckets","topLevelEntries","clients","sdkOutPath","computeSdkOutPath","hasPublicOperations","area","subarea","getAreaSubarea","bucket","leaves","inlineRoots","entries","leaf","className","deriveSubareaClientClassName","propertyName","deriveSubareaPropertyName","generateSdk","typeImportPathTemplate","clientClassName","deriveClientClassName","deriveClientPropertyName","generateSdkOptions","hasAnything","length","size","areaClientOutPaths","sdkEntryDir","sdkOptionsRel","sdkOptionsImportPath","sdkClassName","s","charAt","toUpperCase","toClientImport","sourceDir","info","importPath","topLevelClients","e","areaInfos","sortedAreas","a","localeCompare","areaClientOutPath","computeSdkAreaClientOutPath","areaClassName","deriveAreaClientClassName","areaPropertyName","deriveAreaPropertyName","subareaClients","l","client","allInlineRefs","inlineFilesForGen","codegenOptions","generateAreaClient","inlineFiles","generateSdkAggregator","areas","sdkSrcDir","sdkTypeBarrels","generateBarrelFiles","barrel","rootExports","basename","c","scaffold","coveredRoots","deps","luxon","rootNeedsScalar","decimal","generateSdkPackageJson","generateSdkTsconfig","zodBase","typesBase","resolveMcpModelOutPaths","base","template","suffix","fullConfig","mcpBase","hasMcpOperations","tools","generateMcpFile","registerFn","deriveMcpRegisterFnName","indexPath","index","aggregatorEntries","generateMcpAggregator","emitRouter","routerPath","router","generateMcpRouter","path","parseIncrementalManifest","readFileSync","mkdirSync","recursive","writeFileSync","serializeIncrementalManifest","absPaths","removedDirs","abs","rmSync","force","dir","current","readdirSync","rmdirSync","JSON","stringify"]}
|