@openmirai/typeforge 0.1.7

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init-BBNO0SYd.js","names":["resolveObjectSchema","resolveObjectSchema","resolveObjectSchema"],"sources":["../src/json/types.ts","../src/config/types.ts","../src/config/load.ts","../src/utils/tsconfig-paths.ts","../src/utils/imports.ts","../src/utils/naming.ts","../src/utils/path-params.ts","../src/utils/type-names.ts","../src/emitters/functions/index.ts","../src/emitters/runtime/index.ts","../src/emitters/routes/index.ts","../src/emitters/resolve-schema.ts","../src/envelope-guard/index.ts","../src/parser/index.ts","../src/color/index.ts","../src/emitters/recursive-ref-error.ts","../src/plugins/known-types/matchers.ts","../src/plugins/known-types/load.ts","../src/plugins/known-types/index.ts","../src/emitters/schema-renderer.ts","../src/emitters/types/index.ts","../src/envelope-guard/diagnostic.ts","../src/color/diagnostic.ts","../src/parser/loader.ts","../src/utils/output.ts","../src/generate/index.ts","../src/init/index.ts"],"sourcesContent":["export type JsonPrimitive = string | number | boolean | null;\n\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\nexport type JsonArray = Array<JsonValue>;\n\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\nexport type QueryParamValue = string | number | boolean | null | undefined;\n\nexport type QueryParams = Record<string, QueryParamValue>;\n\nexport function isJsonPrimitive(value: JsonValue): value is JsonPrimitive {\n return (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nexport function isJsonValue(value: unknown): value is JsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (Array.isArray(value)) {\n return value.every(isJsonValue);\n }\n\n if (typeof value === \"object\" && value !== null) {\n return Object.values(value).every(isJsonValue);\n }\n\n return false;\n}\n\nexport function isJsonObject(value: unknown): value is JsonObject {\n return (\n isJsonValue(value) &&\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n );\n}\n\nexport function isJsonArray(value: unknown): value is JsonArray {\n return Array.isArray(value) && value.every(isJsonValue);\n}\n\nexport function parseJson(text: string): JsonValue {\n const parsed: unknown = JSON.parse(text);\n if (!isJsonValue(parsed)) {\n throw new TypeError(\"JSON text did not parse to a valid JSON value\");\n }\n return parsed;\n}\n\nexport function readJsonObject(text: string): JsonObject {\n const parsed = parseJson(text);\n if (!isJsonObject(parsed)) {\n throw new TypeError(\"JSON text did not parse to a JSON object\");\n }\n return parsed;\n}\n\nexport function readJsonPrimitives(\n values: JsonValue | undefined\n): Array<JsonPrimitive> {\n if (!isJsonArray(values)) {\n return [];\n }\n\n return values.filter(isJsonPrimitive);\n}\n","export interface TypeforgeConfig {\n apiRoot?: string;\n}\n\n/** @deprecated Use `TypeforgeConfig`. */\nexport type OpenApiCodegenConfig = TypeforgeConfig;\n\nexport type GenerationMode = \"authoritative\" | \"merge\";\n\nexport type NamingStrategy = \"path\" | \"operationId\";\n\nexport interface QueryExtendsConfig {\n page?: string;\n limit?: string;\n sortBy?: string;\n sortOrder?: string;\n paginationTypeName?: string;\n paginationImportPath?: string;\n sortTypeName?: string;\n sortImportPath?: string;\n}\n\nexport interface SourceConfig {\n /**\n * Project-relative directory for generated API function files.\n * Defaults to `<apiRoot>/<source>/generated/functions`.\n */\n functionsDir?: string;\n /**\n * Project-relative directory for generated API type files.\n * Defaults to `<apiRoot>/<source>/generated/types`.\n */\n typesDir?: string;\n pathPrefix?: string;\n ignorePaths?: Array<string>;\n stripApiPrefix?: boolean;\n routeEnumName?: string;\n generationMode?: GenerationMode;\n naming?: NamingStrategy;\n maxRenderDepth?: number;\n resolveMapKeyRefs?: boolean;\n /**\n * Emit an envelope's `data` schema as the operation response type.\n * Enable this only when the project's HTTPFetch implementation already\n * unwraps response envelopes before returning its `{ data }` value.\n */\n unwrapResponseData?: boolean;\n queryExtends?: QueryExtendsConfig;\n /** When true, emit TanStack Query helpers for GET endpoints (requires query-scope.ts). */\n tanstackQuery?: boolean;\n /**\n * Explicit import base for generated function files pointing back to the\n * `generated/` directory. When set, overrides both relative paths and\n * tsconfig alias auto-detection.\n *\n * Example: `\"@mirai/utils/src/api/v2/generated\"` produces imports like\n * `import ... from \"@mirai/utils/src/api/v2/generated/runtime\"`.\n */\n importBase?: string;\n /**\n * Path to the OpenAPI spec file, relative to the project root.\n * Used as the default spec source when no --spec flag or env var is provided.\n * Example: \"../mirai-core-api/cmd/admin/docs/swagger.json\"\n */\n spec?: string;\n}\n\nexport const DEFAULT_API_ROOT = \"src/api\";\nexport const DEFAULT_ROUTE_ENUM_NAME = \"RouteTargets\";\nexport const DEFAULT_MAX_RENDER_DEPTH = 50;\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nimport { readJsonObject } from \"../json/types\";\nimport type {\n TypeforgeConfig,\n QueryExtendsConfig,\n SourceConfig,\n} from \"./types\";\nimport { DEFAULT_API_ROOT } from \"./types\";\n\nfunction readOptionalJson(path: string): TypeforgeConfig {\n if (!existsSync(path)) {\n return {};\n }\n\n try {\n const raw = readJsonObject(readFileSync(path, \"utf8\"));\n const config: TypeforgeConfig = {};\n if (typeof raw[\"apiRoot\"] === \"string\") {\n config.apiRoot = raw[\"apiRoot\"];\n }\n return config;\n } catch {\n return {};\n }\n}\n\nfunction readPackageConfig(path: string): TypeforgeConfig {\n if (!existsSync(path)) {\n return {};\n }\n\n try {\n const raw = readJsonObject(readFileSync(path, \"utf8\"));\n const typeforge = raw[\"typeforge\"] ?? raw[\"openapiCodegen\"];\n if (\n typeof typeforge !== \"object\" ||\n typeforge === null ||\n Array.isArray(typeforge)\n ) {\n return {};\n }\n\n const config: TypeforgeConfig = {};\n if (typeof typeforge[\"apiRoot\"] === \"string\") {\n config.apiRoot = typeforge[\"apiRoot\"];\n }\n return config;\n } catch {\n return {};\n }\n}\n\nfunction unwrapDefineSourceConfig(content: string): string {\n const match = content.match(\n /defineSourceConfig\\s*(?:<[^>]*>)?\\s*\\(\\s*\\{([\\s\\S]*)\\}\\s*\\)/\n );\n if (match?.[1] !== undefined) {\n return `{${match[1]}}`;\n }\n return content;\n}\n\nfunction parseSourceConfigContent(content: string): SourceConfig {\n const normalized = unwrapDefineSourceConfig(content);\n const config: SourceConfig = {};\n\n const pathPrefix = normalized.match(/pathPrefix:\\s*[\"'`]([^\"'`]+)[\"'`]/);\n if (pathPrefix?.[1] !== undefined) {\n config.pathPrefix = pathPrefix[1];\n }\n\n const functionsDir = normalized.match(/functionsDir:\\s*[\"'`]([^\"'`]+)[\"'`]/);\n if (functionsDir?.[1] !== undefined) {\n config.functionsDir = functionsDir[1];\n }\n\n const typesDir = normalized.match(/typesDir:\\s*[\"'`]([^\"'`]+)[\"'`]/);\n if (typesDir?.[1] !== undefined) {\n config.typesDir = typesDir[1];\n }\n\n const ignoreMatch = normalized.match(/ignorePaths:\\s*\\[([\\s\\S]*?)\\]/);\n if (ignoreMatch?.[1] !== undefined) {\n const paths = [...ignoreMatch[1].matchAll(/[\"'`]([^\"'`]+)[\"'`]/g)]\n .map((match) => match[1])\n .filter((path): path is string => path !== undefined);\n if (paths.length > 0) {\n config.ignorePaths = paths;\n }\n }\n\n if (/stripApiPrefix:\\s*true/.test(normalized)) {\n config.stripApiPrefix = true;\n }\n\n const routeEnumName = normalized.match(\n /routeEnumName:\\s*[\"'`]([^\"'`]+)[\"'`]/\n );\n if (routeEnumName?.[1] !== undefined) {\n config.routeEnumName = routeEnumName[1];\n }\n\n const generationMode = normalized.match(\n /generationMode:\\s*[\"'`](authoritative|merge)[\"'`]/\n );\n if (\n generationMode?.[1] === \"authoritative\" ||\n generationMode?.[1] === \"merge\"\n ) {\n config.generationMode = generationMode[1];\n }\n\n const naming = normalized.match(/naming:\\s*[\"'`](path|operationId)[\"'`]/);\n if (naming?.[1] === \"path\" || naming?.[1] === \"operationId\") {\n config.naming = naming[1];\n }\n\n if (/resolveMapKeyRefs:\\s*false/.test(normalized)) {\n config.resolveMapKeyRefs = false;\n }\n\n if (/unwrapResponseData:\\s*true/.test(normalized)) {\n config.unwrapResponseData = true;\n }\n\n if (/tanstackQuery:\\s*true/.test(normalized)) {\n config.tanstackQuery = true;\n }\n\n const importBase = normalized.match(/importBase:\\s*[\"'`]([^\"'`]+)[\"'`]/);\n if (importBase?.[1] !== undefined) {\n config.importBase = importBase[1];\n }\n\n const maxRenderDepth = normalized.match(/maxRenderDepth:\\s*(\\d+)/)?.[1];\n if (maxRenderDepth !== undefined) {\n config.maxRenderDepth = Number.parseInt(maxRenderDepth, 10);\n }\n\n const queryExtends = parseQueryExtends(normalized);\n if (queryExtends !== undefined) {\n config.queryExtends = queryExtends;\n }\n\n const spec = normalized.match(/spec:\\s*[\"'`]([^\"'`]+)[\"'`]/);\n if (spec?.[1] !== undefined) {\n config.spec = spec[1];\n }\n\n return config;\n}\n\nfunction parseQueryExtends(content: string): QueryExtendsConfig | undefined {\n const block = content.match(/queryExtends:\\s*\\{([\\s\\S]*?)\\}/)?.[1];\n if (block === undefined) {\n return undefined;\n }\n\n const config: QueryExtendsConfig = {};\n const read = (key: string): string | undefined =>\n block.match(new RegExp(`${key}:\\\\s*[\"'\\`]([^\"'\\`]+)[\"'\\`]`))?.[1];\n\n const page = read(\"page\");\n const limit = read(\"limit\");\n const sortBy = read(\"sortBy\");\n const sortOrder = read(\"sortOrder\");\n const paginationTypeName = read(\"paginationTypeName\");\n const paginationImportPath = read(\"paginationImportPath\");\n const sortTypeName = read(\"sortTypeName\");\n const sortImportPath = read(\"sortImportPath\");\n\n if (page !== undefined) {\n config.page = page;\n }\n if (limit !== undefined) {\n config.limit = limit;\n }\n if (sortBy !== undefined) {\n config.sortBy = sortBy;\n }\n if (sortOrder !== undefined) {\n config.sortOrder = sortOrder;\n }\n if (paginationTypeName !== undefined) {\n config.paginationTypeName = paginationTypeName;\n }\n if (paginationImportPath !== undefined) {\n config.paginationImportPath = paginationImportPath;\n }\n if (sortTypeName !== undefined) {\n config.sortTypeName = sortTypeName;\n }\n if (sortImportPath !== undefined) {\n config.sortImportPath = sortImportPath;\n }\n\n return Object.keys(config).length > 0 ? config : undefined;\n}\n\nexport function loadProjectConfig(cwd: string): TypeforgeConfig {\n const fromJson = readOptionalJson(resolve(cwd, \"typeforge.json\"));\n const fromLegacyJson = readOptionalJson(resolve(cwd, \"openapi-codegen.json\"));\n const fromPackage = readPackageConfig(resolve(cwd, \"package.json\"));\n\n return {\n apiRoot:\n fromJson.apiRoot ??\n fromLegacyJson.apiRoot ??\n fromPackage.apiRoot ??\n DEFAULT_API_ROOT,\n };\n}\n\nexport function loadSourceConfig(\n cwd: string,\n apiRoot: string,\n sourceKey: string\n): SourceConfig {\n const sourcePath = resolve(cwd, apiRoot, sourceKey, \"source.ts\");\n if (!existsSync(sourcePath)) {\n return {};\n }\n\n return parseSourceConfigContent(readFileSync(sourcePath, \"utf8\"));\n}\n\nexport function readModelsFile(\n cwd: string,\n apiRoot: string\n): string | undefined {\n const modelsPath = resolve(cwd, apiRoot, \"models.ts\");\n if (!existsSync(modelsPath)) {\n return undefined;\n }\n return readFileSync(modelsPath, \"utf8\");\n}\n\nexport function hasQueryScopeFile(cwd: string, apiRoot: string): boolean {\n return existsSync(resolve(cwd, apiRoot, \"query-scope.ts\"));\n}\n\nexport function detectHttpMode(\n cwd: string,\n apiRoot: string\n): \"singleton\" | \"injected\" {\n const httpPath = resolve(cwd, apiRoot, \"http.ts\");\n if (!existsSync(httpPath)) {\n return \"injected\";\n }\n\n const content = readFileSync(httpPath, \"utf8\");\n if (/export\\s+(const|function)\\s+httpFetch\\b/.test(content)) {\n return \"singleton\";\n }\n if (/export\\s*\\{[^}]*\\bhttpFetch\\b/.test(content)) {\n return \"singleton\";\n }\n return \"injected\";\n}\n\nexport function listSourceKeys(cwd: string, apiRoot: string): Array<string> {\n const apiRootPath = resolve(cwd, apiRoot);\n if (!existsSync(apiRootPath)) {\n return [];\n }\n\n return readdirSync(apiRootPath).filter((entry) => {\n const entryPath = join(apiRootPath, entry);\n if (!statSync(entryPath).isDirectory()) {\n return false;\n }\n return existsSync(join(entryPath, \"source.ts\"));\n });\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, parse, resolve } from \"node:path\";\n\nexport interface TsconfigPathsConfig {\n /** Absolute directory containing tsconfig.json. */\n baseDir: string;\n /** Resolved baseUrl (absolute path). */\n resolvedBaseUrl: string;\n /** Raw paths map from compilerOptions.paths. */\n paths: Record<string, Array<string>>;\n}\n\n/**\n * Strip line comments (//) and block comments from a JSON string, and\n * remove trailing commas before closing braces/brackets.\n * Handles tsconfig.json / jsonc format.\n */\nfunction stripJsonComments(text: string): string {\n let result = \"\";\n let i = 0;\n const len = text.length;\n let inString = false;\n\n while (i < len) {\n const ch = text[i];\n\n if (inString) {\n result += ch;\n if (ch === \"\\\\\") {\n i++;\n if (i < len) {\n result += text[i];\n }\n } else if (ch === '\"') {\n inString = false;\n }\n i++;\n continue;\n }\n\n if (ch === '\"') {\n inString = true;\n result += ch;\n i++;\n continue;\n }\n\n // Line comment\n if (ch === \"/\" && text[i + 1] === \"/\") {\n while (i < len && text[i] !== \"\\n\") {\n i++;\n }\n continue;\n }\n\n // Block comment\n if (ch === \"/\" && text[i + 1] === \"*\") {\n i += 2;\n while (i < len && !(text[i] === \"*\" && text[i + 1] === \"/\")) {\n i++;\n }\n i += 2;\n continue;\n }\n\n result += ch;\n i++;\n }\n\n // Remove trailing commas before } or ]\n return result.replace(/,(\\s*[}\\]])/g, \"$1\");\n}\n\n/**\n * Load `compilerOptions.paths` and `baseUrl` from the nearest `tsconfig.json`\n * found at or above `startDir`. Returns `undefined` when no tsconfig has paths.\n */\nexport function loadTsconfigPaths(\n startDir: string\n): TsconfigPathsConfig | undefined {\n let currentDir = resolve(startDir);\n const rootDir = parse(currentDir).root;\n\n while (true) {\n const config = readTsconfigPaths(currentDir);\n if (config !== undefined) {\n return config;\n }\n\n if (currentDir === rootDir) {\n return undefined;\n }\n currentDir = dirname(currentDir);\n }\n}\n\nfunction readTsconfigPaths(configDir: string): TsconfigPathsConfig | undefined {\n const tsconfigPath = resolve(configDir, \"tsconfig.json\");\n if (!existsSync(tsconfigPath)) {\n return undefined;\n }\n\n try {\n const raw = JSON.parse(\n stripJsonComments(readFileSync(tsconfigPath, \"utf8\"))\n ) as unknown;\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return undefined;\n }\n\n const opts = (raw as Record<string, unknown>)[\"compilerOptions\"];\n if (typeof opts !== \"object\" || opts === null || Array.isArray(opts)) {\n return undefined;\n }\n\n const compilerOptions = opts as Record<string, unknown>;\n const rawPaths = compilerOptions[\"paths\"];\n if (\n typeof rawPaths !== \"object\" ||\n rawPaths === null ||\n Array.isArray(rawPaths)\n ) {\n return undefined;\n }\n\n const baseUrl =\n typeof compilerOptions[\"baseUrl\"] === \"string\"\n ? compilerOptions[\"baseUrl\"]\n : \".\";\n\n const normalizedPaths: Record<string, Array<string>> = {};\n for (const [key, value] of Object.entries(\n rawPaths as Record<string, unknown>\n )) {\n if (Array.isArray(value) && value.every((v) => typeof v === \"string\")) {\n normalizedPaths[key] = value as Array<string>;\n }\n }\n\n if (Object.keys(normalizedPaths).length === 0) {\n return undefined;\n }\n\n return {\n baseDir: configDir,\n paths: normalizedPaths,\n resolvedBaseUrl: resolve(configDir, baseUrl),\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Try to find a tsconfig path alias for `absoluteTarget`.\n *\n * Returns the alias import string (e.g. `@mirai/utils/api/v2/generated/runtime`)\n * when a match is found, or `undefined` when no alias covers the target.\n *\n * Supports:\n * - Wildcard patterns: `\"@foo/*\"` → `[\"packages/foo/src/*\"]`\n * - Exact patterns: `\"@foo/bar\"` → `[\"packages/foo/src/bar\"]`\n */\nexport function resolveAliasImport(\n absoluteTarget: string,\n config: TsconfigPathsConfig\n): string | undefined {\n for (const [alias, mappings] of Object.entries(config.paths)) {\n for (const mapping of mappings) {\n if (alias.endsWith(\"/*\") && mapping.endsWith(\"/*\")) {\n const aliasBase = alias.slice(0, -2);\n const mappingBase = mapping.slice(0, -2);\n const resolvedBase = resolve(config.resolvedBaseUrl, mappingBase);\n\n if (absoluteTarget.startsWith(`${resolvedBase}/`)) {\n const suffix = absoluteTarget.slice(resolvedBase.length + 1);\n return `${aliasBase}/${suffix}`;\n }\n if (absoluteTarget === resolvedBase) {\n return aliasBase;\n }\n } else if (!alias.includes(\"*\") && !mapping.includes(\"*\")) {\n const resolvedMapping = resolve(config.resolvedBaseUrl, mapping);\n if (\n stripTsExtension(absoluteTarget) === stripTsExtension(resolvedMapping)\n ) {\n return alias;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction stripTsExtension(p: string): string {\n return p.replace(/\\.(d\\.ts|ts|js)$/, \"\");\n}\n","import { dirname, join, relative } from \"node:path\";\n\nimport type { TsconfigPathsConfig } from \"./tsconfig-paths\";\nimport { resolveAliasImport } from \"./tsconfig-paths\";\n\nfunction stripTypeScriptExtension(filePath: string): string {\n return filePath.replace(/\\.d\\.ts$/, \"\").replace(/\\.ts$/, \"\");\n}\n\nexport function relativeImportPath(\n fromFilePath: string,\n toPathWithoutExtension: string\n): string {\n const fromDir = dirname(stripTypeScriptExtension(fromFilePath));\n const toPath = stripTypeScriptExtension(toPathWithoutExtension);\n const rel = relative(fromDir, toPath).replace(/\\\\/g, \"/\");\n if (rel.startsWith(\".\")) {\n return rel;\n }\n return `./${rel}`;\n}\n\n/** Import path from a generated function file to a sibling under `generated/`. */\nexport function relativeImportFromFunctionFile(\n cleanPath: string,\n targetRelativeToGenerated: string\n): string {\n const depth = cleanPath.split(\"/\").filter(Boolean).length + 1;\n return `${\"../\".repeat(depth)}${targetRelativeToGenerated}`;\n}\n\n/**\n * Minimum number of `../` segments before we prefer an alias import over a\n * relative one. Paths with fewer segments are already concise.\n */\nconst MIN_DOTDOT_FOR_ALIAS = 3;\n\nexport interface AliasAwareImportOptions {\n /** Absolute path of the generated file that contains the import statement. */\n fromAbsolutePath: string;\n /** Absolute path of the import target (no extension). */\n toAbsolutePath: string;\n /**\n * When set, overrides auto-resolution. The import becomes\n * `${importBase}/<suffix-relative-to-generatedDir>`.\n */\n importBase?: string;\n /** Absolute path of the `generated/` directory. Used with `importBase`. */\n generatedDir?: string;\n /** Loaded tsconfig paths config for alias auto-detection. */\n tsconfigPaths?: TsconfigPathsConfig;\n}\n\n/**\n * Resolve the best import path from `fromAbsolutePath` to `toAbsolutePath`.\n *\n * Resolution priority:\n * 1. `importBase` explicit override (e.g. `@mirai/utils/src/api/v2/generated`)\n * 2. tsconfig path alias auto-detection (when relative has ≥3 `../` segments)\n * 3. Relative fallback\n */\nexport function resolveAliasAwareImport(\n options: AliasAwareImportOptions\n): string {\n const {\n fromAbsolutePath,\n toAbsolutePath,\n importBase,\n generatedDir,\n tsconfigPaths,\n } = options;\n\n // 1. Explicit importBase override\n if (importBase !== undefined && generatedDir !== undefined) {\n const strippedGenDir = generatedDir.replace(/\\/$/, \"\");\n const strippedTarget = stripTypeScriptExtension(toAbsolutePath);\n if (strippedTarget.startsWith(`${strippedGenDir}/`)) {\n const suffix = strippedTarget.slice(strippedGenDir.length + 1);\n return `${importBase}/${suffix}`;\n }\n if (strippedTarget === strippedGenDir) {\n return importBase;\n }\n }\n\n const rel = relativeImportPath(fromAbsolutePath, toAbsolutePath);\n\n // 2. Tsconfig alias auto-detection (only for deep relative paths)\n if (tsconfigPaths !== undefined) {\n const dotdotCount = (rel.match(/\\.\\.\\//g) ?? []).length;\n if (dotdotCount >= MIN_DOTDOT_FOR_ALIAS) {\n const aliasImport = resolveAliasImport(toAbsolutePath, tsconfigPaths);\n if (aliasImport !== undefined) {\n return aliasImport;\n }\n }\n }\n\n // 3. Relative fallback\n return rel;\n}\n\n/**\n * Compute the absolute path of a generated function file.\n *\n * @param functionsDir - absolute path to the `functions/` directory\n * @param cleanPath - path segment like `api/v2/auth/email/validate`\n * @param method - HTTP method in uppercase, e.g. `GET`\n */\nexport function functionFileAbsPath(\n functionsDir: string,\n cleanPath: string,\n method: string\n): string {\n return join(functionsDir, cleanPath, `${method}.ts`);\n}\n","import type { HttpMethod, IRSchema } from \"../parser/types\";\n\nexport function pathToEnumName(routePath: string): string {\n return routePath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n const withoutBraces = segment.replace(/[{}]/g, \"\");\n return withoutBraces.replace(/[^a-zA-Z0-9]/g, \"_\").toUpperCase();\n })\n .join(\"_\");\n}\n\nexport function pathToRouteValue(\n routePath: string,\n stripApiPrefix = false\n): string {\n const value = stripApiPrefix ? routePath.replace(/^\\/api\\//, \"/\") : routePath;\n return value.replace(/\\{(\\w+)\\}/g, \":$1\");\n}\n\nexport function pathToFunctionName(\n cleanPath: string,\n method: HttpMethod\n): string {\n const parts = cleanPath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) =>\n segment\n .replace(/[{[\\]}/]/g, \"\")\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\"\")\n );\n\n const resourceName = parts.join(\"\");\n const action = method === \"get\" ? \"get\" : method;\n return `${action}${resourceName}`;\n}\n\nexport function getFunctionFilePath(\n cleanPath: string,\n method: HttpMethod\n): string {\n const normalizedPath = cleanPath\n .replace(/\\{([^}]+)\\}/g, \"[$1]\")\n .split(\"/\")\n .filter(Boolean);\n return [...normalizedPath, `${method.toUpperCase()}.ts`].join(\"/\");\n}\n\nexport function getTypeFilePath(cleanPath: string, method: HttpMethod): string {\n const normalizedPath = cleanPath\n .replace(/\\{([^}]+)\\}/g, \"[$1]\")\n .split(\"/\")\n .filter(Boolean);\n return [...normalizedPath, `${method.toUpperCase()}.d.ts`].join(\"/\");\n}\n\nexport function schemaKindLabel(schema: IRSchema): string {\n if (schema.kind === \"array\") {\n return \"array\";\n }\n if (schema.kind === \"object\") {\n return \"object\";\n }\n if (schema.kind === \"ref\") {\n return `ref:${schema.ref ?? \"unknown\"}`;\n }\n if (\n schema.kind === \"oneOf\" ||\n schema.kind === \"anyOf\" ||\n schema.kind === \"allOf\"\n ) {\n return schema.kind;\n }\n if (schema.enum !== undefined && schema.enum.length > 0) {\n return \"enum\";\n }\n return schema.kind;\n}\n\nexport function isSuccessStatusCode(statusCode: string): boolean {\n const code = Number.parseInt(statusCode, 10);\n return !Number.isNaN(code) && code >= 200 && code < 300;\n}\n","import type { IRPath, IRSchema } from \"../parser/types\";\n\nexport function renderPathParamTypeFromSchema(schema: IRSchema): string {\n if (schema.enum !== undefined && schema.enum.length > 0) {\n return schema.enum.map((value) => JSON.stringify(value)).join(\" | \");\n }\n if (schema.kind === \"number\") {\n return \"number\";\n }\n if (schema.kind === \"boolean\") {\n return \"boolean\";\n }\n return \"string\";\n}\n\nexport function resolvePathParamSchemas(\n pathItem: IRPath\n): Map<string, IRSchema> {\n const schemas = new Map<string, IRSchema>();\n for (const operation of pathItem.operations) {\n for (const param of operation.pathParams) {\n if (!schemas.has(param.name)) {\n schemas.set(param.name, param.schema);\n }\n }\n }\n return schemas;\n}\n\nexport function renderPathParamType(\n schemas: Map<string, IRSchema>,\n param: string\n): string {\n const schema = schemas.get(param);\n if (schema === undefined) {\n return \"string\";\n }\n return renderPathParamTypeFromSchema(schema);\n}\n","import type { HttpMethod, IROperation, IRSchema } from \"../parser/types\";\nimport { isSuccessStatusCode } from \"./naming\";\n\nexport function getFunctionTypeName(\n cleanPath: string,\n method: HttpMethod\n): string {\n const parts = cleanPath\n .split(\"/\")\n .filter(Boolean)\n .map((segment) =>\n segment\n .replace(/[{[\\]}/]/g, \"\")\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\"\")\n )\n .join(\"\");\n\n return `${method.toUpperCase()}${parts}`;\n}\n\nexport function hasMeaningfulRequestBody(operation: IROperation): boolean {\n const schema = operation.requestBody?.schema;\n if (schema === undefined) {\n return false;\n }\n return !isEmptySchema(schema);\n}\n\nfunction isEmptySchema(schema: IRSchema): boolean {\n if (schema.kind === \"unknown\") {\n return true;\n }\n if (schema.kind === \"object\") {\n if (schema.properties === undefined) {\n return true;\n }\n return Object.keys(schema.properties).length === 0;\n }\n return false;\n}\n\nexport function getSuccessResponseSchema(\n operation: IROperation\n): IRSchema | undefined {\n const success = operation.responses.find(\n (response) =>\n isSuccessStatusCode(response.statusCode) && response.schema !== undefined\n );\n return success?.schema;\n}\n","import { join } from \"node:path\";\n\nimport type {\n HttpMethod,\n IROperation,\n IRPath,\n IRSchema,\n} from \"../../parser/types\";\nimport type { TsconfigPathsConfig } from \"../../utils/tsconfig-paths\";\nimport {\n functionFileAbsPath,\n resolveAliasAwareImport,\n} from \"../../utils/imports\";\nimport { pathToEnumName, pathToFunctionName } from \"../../utils/naming\";\nimport {\n renderPathParamType,\n resolvePathParamSchemas,\n} from \"../../utils/path-params\";\nimport {\n getFunctionTypeName,\n hasMeaningfulRequestBody,\n} from \"../../utils/type-names\";\n\nexport interface FunctionsEmitterOptions {\n paths: Array<IRPath>;\n httpMode: \"singleton\" | \"injected\";\n hasQueryScope: boolean;\n routeEnumName: string;\n functionsDir: string;\n generatedDir: string;\n typesDir: string;\n /**\n * Explicit import base for function→generated imports (overrides auto-resolution).\n * Example: `\"@mirai/utils/src/api/v2/generated\"`\n */\n importBase?: string;\n /** Loaded tsconfig paths for alias auto-detection. */\n tsconfigPaths?: TsconfigPathsConfig;\n}\n\nfunction extractPathParams(routePath: string): Array<string> {\n const matches = routePath.match(/\\{([^}]+)\\}/g) ?? [];\n return matches.map((match) => match.slice(1, -1));\n}\n\nfunction getTypeImportPath(\n cleanPath: string,\n method: HttpMethod,\n options: FunctionsEmitterOptions\n): string {\n const normalizedPath = cleanPath\n .replace(/\\{([^}]+)\\}/g, \"[$1]\")\n .split(\"/\")\n .filter(Boolean)\n .join(\"/\");\n\n const fromAbs = functionFileAbsPath(\n options.functionsDir,\n cleanPath,\n method.toUpperCase()\n );\n const toAbs = join(options.typesDir, normalizedPath, method.toUpperCase());\n return resolveAliasAwareImport({\n fromAbsolutePath: fromAbs,\n generatedDir: options.generatedDir,\n toAbsolutePath: toAbs,\n ...(options.importBase !== undefined\n ? { importBase: options.importBase }\n : {}),\n ...(options.tsconfigPaths !== undefined\n ? { tsconfigPaths: options.tsconfigPaths }\n : {}),\n });\n}\n\nfunction getRuntimeImportPath(\n cleanPath: string,\n options: FunctionsEmitterOptions,\n method: HttpMethod\n): string {\n const fromAbs = functionFileAbsPath(\n options.functionsDir,\n cleanPath,\n method.toUpperCase()\n );\n const toAbs = join(options.generatedDir, \"runtime\");\n return resolveAliasAwareImport({\n fromAbsolutePath: fromAbs,\n generatedDir: options.generatedDir,\n toAbsolutePath: toAbs,\n ...(options.importBase !== undefined\n ? { importBase: options.importBase }\n : {}),\n ...(options.tsconfigPaths !== undefined\n ? { tsconfigPaths: options.tsconfigPaths }\n : {}),\n });\n}\n\nfunction renderOperationPathParamType(\n operation: IROperation,\n schemas: Map<string, IRSchema>,\n param: string\n): string {\n const pathParam = operation.pathParams.find((entry) => entry.name === param);\n if (pathParam !== undefined) {\n return renderPathParamType(new Map([[param, pathParam.schema]]), param);\n }\n return renderPathParamType(schemas, param);\n}\n\nexport interface GeneratedFunctionFile {\n relativePath: string;\n content: string;\n}\n\nexport function emitFunctionFiles(\n options: FunctionsEmitterOptions\n): Array<GeneratedFunctionFile> {\n const files: Array<GeneratedFunctionFile> = [];\n\n for (const pathItem of options.paths) {\n for (const operation of pathItem.operations) {\n files.push({\n content: renderFunctionFile(pathItem, operation, options),\n relativePath: `${pathItem.cleanPath}/${operation.method.toUpperCase()}.ts`,\n });\n }\n }\n\n return files;\n}\n\nfunction renderFunctionFile(\n pathItem: IRPath,\n operation: IROperation,\n options: FunctionsEmitterOptions\n): string {\n const method = operation.method;\n const functionName = pathToFunctionName(pathItem.cleanPath, method);\n const enumName = pathToEnumName(pathItem.path);\n const typeName = getFunctionTypeName(pathItem.cleanPath, method);\n const pathParams = extractPathParams(pathItem.path);\n const pathParamSchemas = resolvePathParamSchemas(pathItem);\n const propsTypeName = `${capitalize(functionName)}Props`;\n const queryOptionsPropsTypeName = `${capitalize(functionName)}QueryOptionsProps`;\n const hasRequestBody =\n method !== \"get\" && hasMeaningfulRequestBody(operation);\n const queryParamsPresent = operation.queryParams.length > 0;\n const typeImportPath = getTypeImportPath(pathItem.cleanPath, method, options);\n const runtimeImportPath = getRuntimeImportPath(\n pathItem.cleanPath,\n options,\n method\n );\n\n const lines: Array<string> = [\n \"// Auto-generated from OpenAPI spec\",\n `// Path: ${method.toUpperCase()} ${pathItem.path}`,\n \"// DO NOT EDIT - This file is automatically generated\",\n \"\",\n ];\n\n lines.push(\"import type {\");\n lines.push(` ${typeName}Response,`);\n if (queryParamsPresent) {\n lines.push(` ${typeName}Params,`);\n }\n if (hasRequestBody) {\n lines.push(` ${typeName}Body,`);\n }\n lines.push(`} from \"${typeImportPath}\";`);\n lines.push(\"\");\n\n const needsRouteTargets = options.hasQueryScope;\n const routeTargetsImport = needsRouteTargets ? \", RouteTargets\" : \"\";\n\n if (options.httpMode === \"singleton\") {\n lines.push(\n `import { httpFetch, Routes${routeTargetsImport}${options.hasQueryScope ? \", getQueryScopeKey, queryOptions\" : \"\"} } from \"${runtimeImportPath}\";`\n );\n } else {\n lines.push(\n `import { Routes${routeTargetsImport}${options.hasQueryScope ? \", getQueryScopeKey, queryOptions\" : \"\"} } from \"${runtimeImportPath}\";`\n );\n }\n const httpFetchTypeImport =\n options.httpMode === \"injected\" ? \"HTTPFetch, \" : \"\";\n const queryParamsTypeImport = queryParamsPresent ? \"\" : \", QueryParams\";\n lines.push(\n `import type { ${httpFetchTypeImport}HTTPFetchConfig${queryParamsTypeImport}${options.hasQueryScope ? \", QueryScope\" : \"\"} } from \"${runtimeImportPath}\";`\n );\n lines.push(\"\");\n\n lines.push(`export interface ${propsTypeName} {`);\n if (options.httpMode === \"injected\") {\n lines.push(\" http: HTTPFetch;\");\n }\n for (const param of pathParams) {\n lines.push(\n ` ${param}: ${renderOperationPathParamType(operation, pathParamSchemas, param)};`\n );\n }\n if (queryParamsPresent) {\n const optional = operation.queryParams.some((param) => param.required)\n ? \"\"\n : \"?\";\n lines.push(` params${optional}: ${typeName}Params;`);\n }\n if (hasRequestBody) {\n lines.push(` body: ${typeName}Body;`);\n }\n const configType = queryParamsPresent\n ? `Omit<HTTPFetchConfig<${typeName}Params, ${typeName}Response>, \"params\" | \"signal\">`\n : `Omit<HTTPFetchConfig<QueryParams, ${typeName}Response>, \"params\" | \"signal\">`;\n lines.push(` config?: ${configType};`);\n lines.push(\" signal?: AbortSignal;\");\n lines.push(\"}\");\n lines.push(\"\");\n\n if (method === \"get\" && options.hasQueryScope) {\n lines.push(\n `export interface ${queryOptionsPropsTypeName} extends ${propsTypeName} {`\n );\n lines.push(\" queryScope: QueryScope;\");\n lines.push(\"}\");\n lines.push(\"\");\n }\n\n const httpClient =\n options.httpMode === \"singleton\" ? \"httpFetch\" : \"props.http\";\n const destructuredProps = [\n ...(options.httpMode === \"injected\" ? [\"http\"] : []),\n ...pathParams.map((param) => param),\n ...(queryParamsPresent ? [\"params\"] : []),\n ...(hasRequestBody ? [\"body\"] : []),\n \"config\",\n \"signal\",\n ];\n\n lines.push(\n `export async function ${functionName}(props: ${propsTypeName}): Promise<${typeName}Response> {`\n );\n if (destructuredProps.length > 0) {\n lines.push(` const { ${destructuredProps.join(\", \")} } = props;`);\n lines.push(\"\");\n }\n\n let routeCall = `Routes.${enumName}`;\n if (pathParams.length > 0) {\n routeCall = `Routes.${enumName}({ ${pathParams.map((param) => `${param}`).join(\", \")} })`;\n }\n\n const fetchConfig = queryParamsPresent\n ? `{ ...config, params, signal }`\n : \"{ ...config, signal }\";\n const getGeneric = queryParamsPresent\n ? `<${typeName}Response, ${typeName}Params>`\n : `<${typeName}Response>`;\n const mutationGeneric = `<${typeName}Response, ${hasRequestBody ? `${typeName}Body` : \"undefined\"}${queryParamsPresent ? `, ${typeName}Params` : \"\"}>`;\n const mutationBody = hasRequestBody ? \"body\" : \"undefined\";\n const mutationConfig = queryParamsPresent\n ? \"{ ...config, params, signal }\"\n : \"{ ...config, signal }\";\n\n switch (method) {\n case \"get\":\n lines.push(\n ` const { data } = await ${httpClient}.get${getGeneric}(${routeCall}, ${fetchConfig});`\n );\n break;\n case \"post\":\n lines.push(\n ` const { data } = await ${httpClient}.post${mutationGeneric}(${routeCall}, ${mutationBody}, ${mutationConfig});`\n );\n break;\n case \"put\":\n lines.push(\n ` const { data } = await ${httpClient}.put${mutationGeneric}(${routeCall}, ${mutationBody}, ${mutationConfig});`\n );\n break;\n case \"patch\":\n lines.push(\n ` const { data } = await ${httpClient}.patch${mutationGeneric}(${routeCall}, ${mutationBody}, ${mutationConfig});`\n );\n break;\n case \"delete\": {\n let deleteConfig = fetchConfig;\n if (hasRequestBody) {\n deleteConfig = queryParamsPresent\n ? \"{ ...config, data: body, params, signal }\"\n : \"{ ...config, data: body, signal }\";\n }\n lines.push(\n ` const { data } = await ${httpClient}.delete${getGeneric}(${routeCall}, ${deleteConfig});`\n );\n break;\n }\n }\n\n lines.push(\" return data;\");\n lines.push(\"}\");\n\n if (method === \"get\" && options.hasQueryScope) {\n const queryOptionsName = `${functionName}QueryOptions`;\n lines.push(\"\");\n lines.push(\n `export function ${queryOptionsName}(props: ${queryOptionsPropsTypeName}) {`\n );\n lines.push(\n ` const { ${queryParamsPresent ? \"params, \" : \"\"}queryScope } = props;`\n );\n lines.push(\" return queryOptions({\");\n lines.push(\n ` queryKey: [RouteTargets.${enumName}, ...getQueryScopeKey(queryScope)${pathParams.length > 0 ? `, ${pathParams.map((param) => `props.${param}`).join(\", \")}` : \"\"}${queryParamsPresent ? \", params\" : \"\"}],`\n );\n lines.push(\n ` queryFn: ({ signal }) => ${functionName}({ ...props, signal }).then((data) => data),`\n );\n if (pathParams.length > 0) {\n lines.push(\n ` enabled: [${pathParams.map((param) => `props.${param}`).join(\", \")}].every(Boolean),`\n );\n }\n lines.push(\" });\");\n lines.push(\"}\");\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\nfunction capitalize(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n","export interface RuntimeEmitterOptions {\n httpMode: \"singleton\" | \"injected\";\n hasQueryScope: boolean;\n}\n\nexport function emitRuntimeFile(options: RuntimeEmitterOptions): string {\n const lines = [\n \"// Auto-generated from OpenAPI spec\",\n \"// DO NOT EDIT - This file is automatically generated\",\n \"\",\n `export type { HTTPFetch, HTTPFetchConfig, QueryParams } from \"../../http\";`,\n ];\n\n if (options.httpMode === \"singleton\") {\n lines.push(`export { httpFetch } from \"../../http\";`);\n }\n\n lines.push(`export { Routes, RouteTargets, buildRoute } from \"./routes\";`);\n\n if (options.hasQueryScope) {\n lines.push(`export type { QueryScope } from \"../../query-scope\";`);\n lines.push(`export { getQueryScopeKey } from \"../../query-scope\";`);\n lines.push(`export { queryOptions } from \"@tanstack/react-query\";`);\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n","import type { IRPath, IRSchema } from \"../../parser/types\";\nimport {\n renderPathParamType,\n resolvePathParamSchemas,\n} from \"../../utils/path-params\";\nimport { pathToEnumName, pathToRouteValue } from \"../../utils/naming\";\n\nexport interface RoutesEmitterOptions {\n paths: Array<IRPath>;\n routeEnumName: string;\n stripApiPrefix?: boolean;\n}\n\ninterface RouteEntry {\n enumName: string;\n routeValue: string;\n pathParamNames: Array<string>;\n pathParamSchemas: Map<string, IRSchema>;\n}\n\nfunction extractPathParamNames(routePath: string): Array<string> {\n const matches = routePath.match(/\\{([^}]+)\\}/g) ?? [];\n return matches.map((match) => match.slice(1, -1));\n}\n\nfunction collectRouteEntries(options: RoutesEmitterOptions): Array<RouteEntry> {\n const seen = new Set<string>();\n const entries: Array<RouteEntry> = [];\n\n for (const pathItem of options.paths) {\n const enumName = pathToEnumName(pathItem.path);\n if (seen.has(enumName)) {\n continue;\n }\n seen.add(enumName);\n\n entries.push({\n enumName,\n pathParamNames: extractPathParamNames(pathItem.path),\n pathParamSchemas: resolvePathParamSchemas(pathItem),\n routeValue: pathToRouteValue(\n pathItem.path,\n options.stripApiPrefix === true\n ),\n });\n }\n\n return entries;\n}\n\nfunction renderRouteParamsType(entries: Array<RouteEntry>): Array<string> {\n const lines = [\"export type RouteParams = {\"];\n for (const entry of entries) {\n if (entry.pathParamNames.length === 0) {\n lines.push(` ${entry.enumName}: undefined;`);\n continue;\n }\n\n lines.push(` ${entry.enumName}: {`);\n for (const param of entry.pathParamNames) {\n lines.push(\n ` ${param}: ${renderPathParamType(entry.pathParamSchemas, param)};`\n );\n }\n lines.push(\" };\");\n }\n lines.push(\"};\", \"export type RouteKey = keyof RouteParams;\", \"\");\n return lines;\n}\n\nexport function emitRoutesFile(options: RoutesEmitterOptions): string {\n const entries = collectRouteEntries(options);\n const lines = [\n \"// Auto-generated from OpenAPI spec\",\n \"// DO NOT EDIT - This file is automatically generated\",\n \"\",\n \"import {\",\n \" buildRouteFromHandlers,\",\n \" createRouteHandlers,\",\n '} from \"@openmirai/typeforge/routes\";',\n \"\",\n ...renderRouteParamsType(entries),\n `export enum ${options.routeEnumName} {`,\n ];\n\n for (const entry of entries) {\n lines.push(` ${entry.enumName} = \"${entry.routeValue}\",`);\n }\n\n lines.push(\"}\", \"\");\n if (options.routeEnumName !== \"RouteTargets\") {\n lines.push(`export { ${options.routeEnumName} as RouteTargets };`);\n lines.push(\"\");\n }\n lines.push(\n `export const Routes = createRouteHandlers<RouteParams>(${options.routeEnumName});`\n );\n lines.push(\n \"export const buildRoute = buildRouteFromHandlers<RouteParams>(Routes);\",\n \"\"\n );\n return lines.join(\"\\n\");\n}\n\nexport function mergeRoutesFile(\n existingContent: string,\n newContent: string,\n routeEnumName: string,\n pathPrefix?: string\n): string {\n const existingEntries = parseEnumEntries(existingContent, routeEnumName);\n const newEntries = parseEnumEntries(newContent, routeEnumName);\n\n if (pathPrefix !== undefined) {\n for (const [name, value] of existingEntries.entries()) {\n if (value.startsWith(pathPrefix) && !newEntries.has(name)) {\n existingEntries.delete(name);\n }\n }\n }\n\n const merged = new Map([...existingEntries, ...newEntries]);\n const paths = [...merged.entries()].map(([, value]) => ({\n cleanPath: value.replace(/:[^/]+/g, (match) => `{${match.slice(1)}}`),\n operations: [],\n path: value.includes(\":\") ? value.replace(/:([^/]+)/g, \"{$1}\") : value,\n }));\n\n return emitRoutesFile({\n paths,\n routeEnumName,\n stripApiPrefix: false,\n });\n}\n\nfunction parseEnumEntries(\n content: string,\n enumName: string\n): Map<string, string> {\n const entries = new Map<string, string>();\n const enumStart = content.indexOf(`export enum ${enumName} {`);\n if (enumStart === -1) {\n return entries;\n }\n\n const enumBody = content.slice(enumStart);\n const enumEnd = enumBody.indexOf(\"}\");\n if (enumEnd === -1) {\n return entries;\n }\n\n const enumContent = enumBody.slice(0, enumEnd);\n const staticRegex = /(\\w+)\\s*=\\s*\"([^\"]+)\"/g;\n let match: RegExpExecArray | null;\n while ((match = staticRegex.exec(enumContent)) !== null) {\n const name = match[1];\n const value = match[2];\n if (name !== undefined && value !== undefined) {\n entries.set(name, value);\n }\n }\n\n return entries;\n}\n","import type { IRSchema } from \"../parser/types\";\n\nexport function resolveRef(\n schema: IRSchema,\n components: Record<string, IRSchema>\n): IRSchema {\n if (schema.kind !== \"ref\" || schema.ref === undefined) {\n return schema;\n }\n\n const refName = schema.ref.split(\"/\").pop();\n if (refName === undefined || components[refName] === undefined) {\n return { kind: \"unknown\" };\n }\n\n return components[refName];\n}\n\n/**\n * Resolve an object schema through component references and `allOf` composition.\n * The returned object is a new flattened view; component schemas are never mutated.\n */\nexport function resolveObjectSchema(\n schema: IRSchema,\n components: Record<string, IRSchema>,\n visitedRefs: ReadonlySet<string> = new Set()\n): IRSchema | undefined {\n if (schema.kind === \"object\") {\n return schema;\n }\n\n if (schema.kind === \"ref\") {\n const refName = refNameFromSchema(schema);\n if (refName === undefined || visitedRefs.has(refName)) {\n return undefined;\n }\n const resolved = components[refName];\n if (resolved === undefined) {\n return undefined;\n }\n return resolveObjectSchema(\n resolved,\n components,\n new Set([...visitedRefs, refName])\n );\n }\n\n if (schema.kind !== \"allOf\" || schema.allOf === undefined) {\n return undefined;\n }\n\n const properties: NonNullable<IRSchema[\"properties\"]> = {};\n const required = new Set<string>();\n for (const member of schema.allOf) {\n const resolved = resolveObjectSchema(member, components, visitedRefs);\n if (resolved?.properties === undefined) {\n return undefined;\n }\n for (const [name, property] of Object.entries(resolved.properties)) {\n const existing = properties[name];\n properties[name] =\n existing === undefined\n ? { ...property }\n : {\n required: existing.required || property.required,\n schema:\n JSON.stringify(existing.schema) ===\n JSON.stringify(property.schema)\n ? existing.schema\n : {\n allOf: [existing.schema, property.schema],\n kind: \"allOf\",\n },\n };\n if (property.required) {\n required.add(name);\n }\n }\n }\n\n return {\n kind: \"object\",\n properties,\n required: [...required],\n };\n}\n\nexport function refNameFromSchema(schema: IRSchema): string | undefined {\n if (schema.kind !== \"ref\" || schema.ref === undefined) {\n return undefined;\n }\n return schema.ref.split(\"/\").pop();\n}\n","import type { IRSchema, IRSchemaProperty, IRSource } from \"../parser/types\";\nimport { resolveObjectSchema, resolveRef } from \"../emitters/resolve-schema\";\nimport { isSuccessStatusCode, schemaKindLabel } from \"../utils/naming\";\n\nexport type EnvelopeMode = \"shared\" | \"raw\" | \"mixed\";\n\nexport interface EnvelopeField {\n name: string;\n required: boolean;\n kind: string;\n}\n\nexport interface EnvelopeShape {\n fields: Array<EnvelopeField>;\n schema: IRSchema;\n}\n\nexport interface OperationEnvelope {\n method: string;\n path: string;\n shape: EnvelopeShape;\n}\n\nexport interface EnvelopeAnalysis {\n mode: EnvelopeMode;\n shared?: EnvelopeShape;\n operations: Array<OperationEnvelope>;\n groups: Map<string, Array<OperationEnvelope>>;\n}\n\nexport interface EnvelopeFieldDiff {\n field: string;\n issue: \"missing\" | \"extra\" | \"type-changed\" | \"required-changed\";\n spec?: EnvelopeField;\n user?: EnvelopeField;\n}\n\nexport interface UserBaseResponseShape {\n fields: Array<EnvelopeField>;\n sourcePath: string;\n}\n\nfunction resolveSchema(\n schema: IRSchema,\n components: Record<string, IRSchema>\n): IRSchema {\n if (schema.kind === \"ref\") {\n return resolveRef(schema, components);\n }\n return schema;\n}\n\nfunction extractEnvelopeShape(\n schema: IRSchema | undefined,\n components: Record<string, IRSchema>\n): EnvelopeShape | undefined {\n if (schema === undefined) {\n return undefined;\n }\n\n const resolved = resolveObjectSchema(schema, components);\n if (resolved?.properties === undefined) {\n return undefined;\n }\n\n const fields: Array<EnvelopeField> = [];\n for (const [name, property] of Object.entries(resolved.properties)) {\n fields.push({\n kind:\n name === \"data\"\n ? \"generic\"\n : schemaKindLabel(resolveSchema(property.schema, components)),\n name,\n required: property.required,\n });\n }\n\n fields.sort((a, b) => a.name.localeCompare(b.name));\n return { fields, schema: resolved };\n}\n\nfunction fingerprint(shape: EnvelopeShape): string {\n return JSON.stringify(\n shape.fields.map((field) => ({\n kind: field.kind,\n name: field.name,\n required: field.required,\n }))\n );\n}\n\nexport function matchesEnvelopeShape(\n schema: IRSchema,\n components: Record<string, IRSchema>,\n expected: EnvelopeShape\n): boolean {\n const actual = extractEnvelopeShape(schema, components);\n return actual !== undefined && fingerprint(actual) === fingerprint(expected);\n}\n\nconst ENVELOPE_METADATA_FIELDS = new Set([\n \"error\",\n \"message\",\n \"requestId\",\n \"success\",\n \"timestamp\",\n]);\n\nfunction looksLikeEnvelope(shape: EnvelopeShape): boolean {\n const names = new Set(shape.fields.map((field) => field.name));\n if (names.has(\"data\")) {\n return true;\n }\n if (!names.has(\"success\")) {\n return false;\n }\n return [...names].every((name) => ENVELOPE_METADATA_FIELDS.has(name));\n}\n\nexport function isEnvelopeSchema(\n schema: IRSchema,\n components: Record<string, IRSchema>\n): boolean {\n const shape = extractEnvelopeShape(schema, components);\n return shape !== undefined && looksLikeEnvelope(shape);\n}\n\nexport function collectOperationEnvelopes(\n source: IRSource\n): Array<OperationEnvelope> {\n const envelopes: Array<OperationEnvelope> = [];\n\n for (const pathItem of source.paths) {\n for (const operation of pathItem.operations) {\n const success = operation.responses.find(\n (response) =>\n isSuccessStatusCode(response.statusCode) &&\n response.schema !== undefined\n );\n if (success?.schema === undefined) {\n continue;\n }\n\n const shape = extractEnvelopeShape(\n success.schema,\n source.components.schemas\n );\n if (shape === undefined) {\n continue;\n }\n\n envelopes.push({\n method: operation.method.toUpperCase(),\n path: pathItem.path,\n shape,\n });\n }\n }\n\n return envelopes;\n}\n\nexport function analyzeEnvelope(source: IRSource): EnvelopeAnalysis {\n const operations = collectOperationEnvelopes(source);\n const groups = new Map<string, Array<OperationEnvelope>>();\n\n for (const operation of operations) {\n const key = fingerprint(operation.shape);\n const existing = groups.get(key) ?? [];\n existing.push(operation);\n groups.set(key, existing);\n }\n\n if (operations.length === 0) {\n return { groups, mode: \"raw\", operations };\n }\n\n if (groups.size === 1) {\n const shared = operations[0]?.shape;\n if (shared !== undefined && looksLikeEnvelope(shared)) {\n return { groups, mode: \"shared\", operations, shared };\n }\n return { groups, mode: \"raw\", operations };\n }\n\n const envelopeGroups = [...groups.entries()].filter(([, items]) => {\n const first = items[0];\n return first !== undefined && looksLikeEnvelope(first.shape);\n });\n\n if (envelopeGroups.length === 0) {\n return { groups, mode: \"raw\", operations };\n }\n\n if (envelopeGroups.length === 1) {\n const group = envelopeGroups[0];\n const firstOperation = group?.[1][0];\n if (\n group !== undefined &&\n group[1].length === operations.length &&\n firstOperation !== undefined\n ) {\n return {\n groups,\n mode: \"shared\",\n operations,\n shared: firstOperation.shape,\n };\n }\n }\n\n return { groups, mode: \"mixed\", operations };\n}\n\n/** Largest envelope group that includes a `data` field; used for mixed-mode base.ts. */\nexport function getPrimaryEnvelopeShape(\n analysis: EnvelopeAnalysis\n): EnvelopeShape | undefined {\n if (analysis.shared !== undefined) {\n return analysis.shared;\n }\n if (analysis.mode !== \"mixed\") {\n return undefined;\n }\n\n let best: EnvelopeShape | undefined;\n let bestCount = 0;\n for (const items of analysis.groups.values()) {\n const first = items[0];\n if (first === undefined || !looksLikeEnvelope(first.shape)) {\n continue;\n }\n if (!first.shape.fields.some((field) => field.name === \"data\")) {\n continue;\n }\n if (items.length > bestCount) {\n bestCount = items.length;\n best = first.shape;\n }\n }\n return best;\n}\n\nexport function parseUserBaseResponse(\n content: string\n): UserBaseResponseShape | undefined {\n const match = content.match(\n /export\\s+interface\\s+BaseResponse\\s*<[^>]*>\\s*\\{([\\s\\S]*?)\\}/\n );\n if (match === null) {\n const plain = content.match(\n /export\\s+interface\\s+BaseResponse\\s*\\{([\\s\\S]*?)\\}/\n );\n if (plain === null) {\n return undefined;\n }\n return parseBaseResponseBody(plain[1]!);\n }\n\n return parseBaseResponseBody(match[1]!);\n}\n\nfunction parseBaseResponseBody(body: string): UserBaseResponseShape {\n const fields: Array<EnvelopeField> = [];\n const lineRegex = /^\\s*(\\w+)(\\?)?:\\s*([^;]+);/gm;\n let match: RegExpExecArray | null;\n while ((match = lineRegex.exec(body)) !== null) {\n const [, name, optional, rawType] = match;\n if (name === undefined || rawType === undefined) {\n continue;\n }\n fields.push({\n kind: rawType.trim().replace(/\\s+/g, \" \"),\n name,\n required: optional === undefined,\n });\n }\n\n fields.sort((a, b) => a.name.localeCompare(b.name));\n return { fields, sourcePath: \"models.ts\" };\n}\n\nexport function diffEnvelopeFields(\n spec: EnvelopeShape,\n user: UserBaseResponseShape\n): Array<EnvelopeFieldDiff> {\n const diffs: Array<EnvelopeFieldDiff> = [];\n const specMap = new Map(\n spec.fields\n .filter((field) => field.name !== \"data\")\n .map((field) => [field.name, field])\n );\n const userMap = new Map(\n user.fields\n .filter((field) => field.name !== \"data\" && field.name !== \"T\")\n .map((field) => [field.name, field])\n );\n\n for (const [name, specField] of specMap.entries()) {\n const userField = userMap.get(name);\n if (userField === undefined) {\n diffs.push({ field: name, issue: \"missing\", spec: specField });\n continue;\n }\n if (specField.required !== userField.required) {\n diffs.push({\n field: name,\n issue: \"required-changed\",\n spec: specField,\n user: userField,\n });\n }\n if (specField.kind !== userField.kind && name !== \"data\") {\n diffs.push({\n field: name,\n issue: \"type-changed\",\n spec: specField,\n user: userField,\n });\n }\n }\n\n for (const [name, userField] of userMap.entries()) {\n if (!specMap.has(name)) {\n diffs.push({ field: name, issue: \"extra\", user: userField });\n }\n }\n\n return diffs;\n}\n\nexport function getDataFieldSchema(shape: EnvelopeShape): IRSchema | undefined {\n const dataField = shape.schema.properties?.data;\n return dataField?.schema;\n}\n\nfunction formatEnvelopeFieldType(\n field: EnvelopeField,\n property: IRSchemaProperty | undefined,\n genericName: string\n): string {\n if (property === undefined) {\n return \"unknown\";\n }\n if (field.kind === \"generic\") {\n return genericName;\n }\n return field.kind;\n}\n\nexport function buildBaseResponseInterface(\n shape: EnvelopeShape,\n genericName = \"T\"\n): string {\n const lines = [`export interface BaseResponse<${genericName}> {`];\n for (const field of shape.fields) {\n if (field.name === \"data\") {\n lines.push(` data?: ${genericName};`);\n continue;\n }\n const optional = field.required ? \"\" : \"?\";\n const property = shape.schema.properties?.[field.name];\n const type = formatEnvelopeFieldType(field, property, genericName);\n lines.push(` ${field.name}${optional}: ${type};`);\n }\n lines.push(\"}\");\n return lines.join(\"\\n\");\n}\n","import type {\n HttpMethod,\n IROperation,\n IRPath,\n IRPathParam,\n IRQueryParam,\n IRRequestBody,\n IRResponse,\n IRSchema,\n IRSchemaProperty,\n IRSource,\n} from \"./types\";\nimport type { JsonObject, JsonValue } from \"../json/types\";\nimport { isJsonArray, isJsonObject, readJsonPrimitives } from \"../json/types\";\n\nconst HTTP_METHODS: Array<HttpMethod> = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\n\nfunction readObjectArray(value: JsonValue | undefined): Array<JsonObject> {\n if (!isJsonArray(value)) {\n return [];\n }\n\n return value.filter(isJsonObject);\n}\n\nfunction extractRefName(ref: string): string {\n const parts = ref.split(\"/\");\n return parts.at(-1) ?? ref;\n}\n\nfunction toCleanPath(pathStr: string): string {\n return pathStr.replace(/^\\//, \"\").replace(/\\{([^}]+)\\}/g, \"[$1]\");\n}\n\n// ---------------------------------------------------------------------------\n// Schema parsing\n// ---------------------------------------------------------------------------\n\nexport function parseSchema(raw: JsonValue): IRSchema {\n if (!isJsonObject(raw)) {\n return { kind: \"unknown\" };\n }\n\n // $ref — preserve as named reference; no inline resolution avoids circular-ref loops\n if (typeof raw[\"$ref\"] === \"string\") {\n return { kind: \"ref\", ref: extractRefName(raw[\"$ref\"]) };\n }\n\n // Composition keywords (check before type to match specs that omit type alongside these)\n if (isJsonArray(raw[\"oneOf\"]) && raw[\"oneOf\"].length > 0) {\n return {\n kind: \"oneOf\",\n oneOf: raw[\"oneOf\"].map(parseSchema),\n };\n }\n if (isJsonArray(raw[\"anyOf\"]) && raw[\"anyOf\"].length > 0) {\n return {\n anyOf: raw[\"anyOf\"].map(parseSchema),\n kind: \"anyOf\",\n };\n }\n if (isJsonArray(raw[\"allOf\"]) && raw[\"allOf\"].length > 0) {\n return {\n allOf: raw[\"allOf\"].map(parseSchema),\n kind: \"allOf\",\n };\n }\n\n const rawType = typeof raw[\"type\"] === \"string\" ? raw[\"type\"] : undefined,\n nullable = raw[\"nullable\"] === true;\n\n // Array\n if (rawType === \"array\") {\n const schema: IRSchema = { kind: \"array\" };\n if (raw[\"items\"] !== undefined) {\n schema.items = parseSchema(raw[\"items\"]);\n }\n if (nullable) {\n schema.nullable = true;\n }\n return schema;\n }\n\n // Object — explicit type or inferred from presence of properties/additionalProperties\n const looksLikeObject =\n rawType === \"object\" ||\n (rawType === undefined &&\n (isJsonObject(raw[\"properties\"]) ||\n raw[\"additionalProperties\"] !== undefined));\n\n if (looksLikeObject) {\n return buildObjectSchema(raw, nullable);\n }\n\n // Numerics\n if (rawType === \"integer\" || rawType === \"number\") {\n const schema: IRSchema = { kind: \"number\" };\n if (typeof raw[\"format\"] === \"string\") {\n schema.format = raw[\"format\"];\n }\n if (nullable) {\n schema.nullable = true;\n }\n if (Array.isArray(raw[\"enum\"])) {\n schema.enum = readJsonPrimitives(raw[\"enum\"]);\n }\n if (typeof raw[\"x-map-key-ref\"] === \"string\") {\n schema[\"x-map-key-ref\"] = raw[\"x-map-key-ref\"];\n }\n return schema;\n }\n\n if (rawType === \"string\") {\n const schema: IRSchema = { kind: \"string\" };\n if (typeof raw[\"format\"] === \"string\") {\n schema.format = raw[\"format\"];\n }\n if (nullable) {\n schema.nullable = true;\n }\n if (Array.isArray(raw[\"enum\"])) {\n schema.enum = readJsonPrimitives(raw[\"enum\"]);\n }\n if (typeof raw[\"x-map-key-ref\"] === \"string\") {\n schema[\"x-map-key-ref\"] = raw[\"x-map-key-ref\"];\n }\n return schema;\n }\n\n if (rawType === \"boolean\") {\n const schema: IRSchema = { kind: \"boolean\" };\n if (nullable) {\n schema.nullable = true;\n }\n return schema;\n }\n\n if (rawType === \"null\") {\n return { kind: \"null\" };\n }\n\n return { kind: \"unknown\" };\n}\n\nfunction buildObjectSchema(raw: JsonObject, nullable: boolean): IRSchema {\n const schema: IRSchema = { kind: \"object\" };\n if (nullable) {\n schema.nullable = true;\n }\n\n if (isJsonObject(raw[\"properties\"])) {\n const requiredList = isJsonArray(raw[\"required\"])\n ? raw[\"required\"].filter(\n (entry): entry is string => typeof entry === \"string\"\n )\n : [],\n properties: Record<string, IRSchemaProperty> = {};\n for (const [key, propRaw] of Object.entries(raw[\"properties\"])) {\n properties[key] = {\n required: requiredList.includes(key),\n schema: parseSchema(propRaw),\n };\n }\n schema.properties = properties;\n if (requiredList.length > 0) {\n schema.required = requiredList;\n }\n }\n\n if (raw[\"additionalProperties\"] !== undefined) {\n if (typeof raw[\"additionalProperties\"] === \"boolean\") {\n schema.additionalProperties = raw[\"additionalProperties\"];\n } else {\n schema.additionalProperties = parseSchema(raw[\"additionalProperties\"]);\n }\n }\n\n if (typeof raw[\"x-map-key-ref\"] === \"string\") {\n schema[\"x-map-key-ref\"] = raw[\"x-map-key-ref\"];\n }\n\n return schema;\n}\n\n// ---------------------------------------------------------------------------\n// Swagger 2 helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Swagger 2 parameter's inline type attributes to an IRSchema.\n * Swagger 2 parameters carry `type`, `format`, `enum` directly (no `schema` sub-object\n * unless `in: body`).\n */\nfunction swaggerParamToSchema(param: JsonObject): IRSchema {\n if (isJsonObject(param[\"schema\"])) {\n return parseSchema(param[\"schema\"]);\n }\n\n const paramSchema: JsonObject = {};\n if (param[\"enum\"] !== undefined) {\n paramSchema.enum = param[\"enum\"];\n }\n if (typeof param[\"format\"] === \"string\") {\n paramSchema.format = param[\"format\"];\n }\n if (typeof param[\"type\"] === \"string\") {\n paramSchema.type = param[\"type\"];\n }\n\n return parseSchema(paramSchema);\n}\n\nfunction parseSwagger2(raw: JsonObject, opts: ParseOpts): IRSource {\n const schemas: Record<string, IRSchema> = {},\n definitions = isJsonObject(raw[\"definitions\"]) ? raw[\"definitions\"] : {};\n for (const [name, def] of Object.entries(definitions)) {\n schemas[name] = parseSchema(def);\n }\n\n const paths = parsePaths(raw, \"swagger2\", opts);\n\n return { components: { schemas }, key: \"\", paths };\n}\n\n// ---------------------------------------------------------------------------\n// OpenAPI 3 helpers\n// ---------------------------------------------------------------------------\n\nfunction parseOpenAPI3(raw: JsonObject, opts: ParseOpts): IRSource {\n const schemas: Record<string, IRSchema> = {},\n components = isJsonObject(raw[\"components\"]) ? raw[\"components\"] : {},\n compSchemas = isJsonObject(components[\"schemas\"])\n ? components[\"schemas\"]\n : {};\n for (const [name, def] of Object.entries(compSchemas)) {\n schemas[name] = parseSchema(def);\n }\n\n const paths = parsePaths(raw, \"openapi3\", opts);\n\n return { components: { schemas }, key: \"\", paths };\n}\n\n// ---------------------------------------------------------------------------\n// Shared path/operation parsing\n// ---------------------------------------------------------------------------\n\ntype SpecVersion = \"swagger2\" | \"openapi3\";\n\ninterface ParseOpts {\n pathPrefix?: string;\n ignorePaths?: Array<string>;\n}\n\nfunction parsePaths(\n raw: JsonObject,\n version: SpecVersion,\n opts: ParseOpts\n): Array<IRPath> {\n const result: Array<IRPath> = [],\n rawPaths = raw[\"paths\"];\n if (!isJsonObject(rawPaths)) {\n return result;\n }\n\n for (const [pathStr, pathItemRaw] of Object.entries(rawPaths)) {\n if (opts.pathPrefix !== undefined && !pathStr.startsWith(opts.pathPrefix)) {\n continue;\n }\n if (opts.ignorePaths?.includes(pathStr)) {\n continue;\n }\n if (!isJsonObject(pathItemRaw)) {\n continue;\n }\n\n const pathLevelParams = readObjectArray(pathItemRaw[\"parameters\"]),\n operations: Array<IROperation> = [];\n\n for (const method of HTTP_METHODS) {\n const opRaw = pathItemRaw[method];\n if (!isJsonObject(opRaw)) {\n continue;\n }\n\n const op = parseOperation(method, opRaw, pathLevelParams, version);\n operations.push(op);\n }\n\n if (operations.length > 0) {\n result.push({\n cleanPath: toCleanPath(pathStr),\n operations,\n path: pathStr,\n });\n }\n }\n\n return result;\n}\n\nfunction mergeParams(\n pathLevel: Array<JsonObject>,\n opLevel: Array<JsonObject>\n): Array<JsonObject> {\n const map = new Map<string, JsonObject>();\n for (const p of pathLevel) {\n if (typeof p[\"name\"] === \"string\") {\n map.set(p[\"name\"], p);\n }\n }\n for (const p of opLevel) {\n if (typeof p[\"name\"] === \"string\") {\n map.set(p[\"name\"], p);\n }\n }\n return [...map.values()];\n}\n\nfunction resolveOpenAPI3ParamSchema(param: JsonObject): IRSchema {\n if (isJsonObject(param[\"schema\"])) {\n return parseSchema(param[\"schema\"]);\n }\n return { kind: \"unknown\" };\n}\n\nfunction resolveParamSchema(param: JsonObject, version: SpecVersion): IRSchema {\n if (version === \"openapi3\") {\n return resolveOpenAPI3ParamSchema(param);\n }\n return swaggerParamToSchema(param);\n}\n\nfunction parseOperation(\n method: HttpMethod,\n opRaw: JsonObject,\n pathLevelParams: Array<JsonObject>,\n version: SpecVersion\n): IROperation {\n const opParams = readObjectArray(opRaw[\"parameters\"]),\n params = mergeParams(pathLevelParams, opParams),\n pathParams: Array<IRPathParam> = [],\n queryParams: Array<IRQueryParam> = [];\n\n for (const param of params) {\n if (typeof param[\"name\"] !== \"string\") {\n continue;\n }\n\n if (param[\"in\"] === \"path\") {\n pathParams.push({\n name: param[\"name\"],\n schema: resolveParamSchema(param, version),\n });\n } else if (param[\"in\"] === \"query\") {\n queryParams.push({\n name: param[\"name\"],\n required: param[\"required\"] === true,\n schema: resolveParamSchema(param, version),\n });\n }\n }\n\n const requestBody =\n version === \"swagger2\"\n ? parseSwagger2Body(params)\n : parseOpenAPI3Body(opRaw),\n responses = parseResponses(opRaw, version),\n operation: IROperation = { method, pathParams, queryParams, responses };\n if (typeof opRaw[\"operationId\"] === \"string\") {\n operation.operationId = opRaw[\"operationId\"];\n }\n if (requestBody !== undefined) {\n operation.requestBody = requestBody;\n }\n\n return operation;\n}\n\nfunction parseSwagger2Body(\n params: Array<JsonObject>\n): IRRequestBody | undefined {\n const bodyParam = params.find((p) => p[\"in\"] === \"body\");\n if (bodyParam === undefined) {\n return undefined;\n }\n\n const schema = isJsonObject(bodyParam[\"schema\"])\n ? parseSchema(bodyParam[\"schema\"])\n : { kind: \"unknown\" as const };\n\n return { required: bodyParam[\"required\"] === true, schema };\n}\n\nfunction parseOpenAPI3Body(opRaw: JsonObject): IRRequestBody | undefined {\n if (!isJsonObject(opRaw[\"requestBody\"])) {\n return undefined;\n }\n const reqBodyRaw = opRaw[\"requestBody\"],\n content = isJsonObject(reqBodyRaw[\"content\"]) ? reqBodyRaw[\"content\"] : {},\n jsonContent = isJsonObject(content[\"application/json\"])\n ? content[\"application/json\"]\n : {},\n schema = isJsonObject(jsonContent[\"schema\"])\n ? parseSchema(jsonContent[\"schema\"])\n : { kind: \"unknown\" as const };\n\n return { required: reqBodyRaw[\"required\"] === true, schema };\n}\n\nfunction parseResponses(\n opRaw: JsonObject,\n version: SpecVersion\n): Array<IRResponse> {\n const result: Array<IRResponse> = [];\n if (!isJsonObject(opRaw[\"responses\"])) {\n return result;\n }\n\n for (const [statusCode, respRaw] of Object.entries(opRaw[\"responses\"])) {\n if (!isJsonObject(respRaw)) {\n result.push({ statusCode });\n continue;\n }\n\n const irResp: IRResponse = { statusCode };\n\n if (version === \"swagger2\") {\n if (isJsonObject(respRaw[\"schema\"])) {\n irResp.schema = parseSchema(respRaw[\"schema\"]);\n }\n } else {\n const content = isJsonObject(respRaw[\"content\"])\n ? respRaw[\"content\"]\n : {},\n jsonContent = isJsonObject(content[\"application/json\"])\n ? content[\"application/json\"]\n : {};\n if (isJsonObject(jsonContent[\"schema\"])) {\n irResp.schema = parseSchema(jsonContent[\"schema\"]);\n }\n }\n\n result.push(irResp);\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport function parseSpec(\n raw: JsonValue,\n opts: { pathPrefix?: string; ignorePaths?: Array<string> }\n): IRSource {\n if (!isJsonObject(raw)) {\n return { components: { schemas: {} }, key: \"\", paths: [] };\n }\n\n const parseOpts: ParseOpts = {};\n if (opts.pathPrefix !== undefined) {\n parseOpts.pathPrefix = opts.pathPrefix;\n }\n if (opts.ignorePaths !== undefined) {\n parseOpts.ignorePaths = opts.ignorePaths;\n }\n\n if (raw[\"swagger\"] === \"2.0\") {\n return parseSwagger2(raw, parseOpts);\n }\n\n if (typeof raw[\"openapi\"] === \"string\" && raw[\"openapi\"].startsWith(\"3.\")) {\n return parseOpenAPI3(raw, parseOpts);\n }\n\n return { components: { schemas: {} }, key: \"\", paths: [] };\n}\n","import chalk from \"chalk\";\n\nexport function isColorEnabled(): boolean {\n if (process.env[\"NO_COLOR\"] !== undefined) {\n return false;\n }\n return process.stdout.isTTY === true;\n}\n\nfunction paint(formatter: (text: string) => string, text: string): string {\n return isColorEnabled() ? formatter(text) : text;\n}\n\nexport function bold(text: string): string {\n return paint(chalk.bold, text);\n}\n\nexport function red(text: string): string {\n return paint(chalk.red, text);\n}\n\nexport function dim(text: string): string {\n return paint(chalk.dim, text);\n}\n\nexport function cyan(text: string): string {\n return paint(chalk.cyan, text);\n}\n\nexport function yellow(text: string): string {\n return paint(chalk.yellow, text);\n}\n\nexport function white(text: string): string {\n return paint(chalk.white, text);\n}\n","import { bold, cyan, dim, red } from \"../color/index\";\n\nexport class RecursiveRefError extends Error {\n readonly cycle: Array<string>;\n readonly schemaPath: string;\n readonly sourceKey: string;\n\n constructor(sourceKey: string, cycle: Array<string>, schemaPath: string) {\n super(formatRecursiveRefError(sourceKey, cycle, schemaPath));\n this.name = \"RecursiveRefError\";\n this.cycle = cycle;\n this.schemaPath = schemaPath;\n this.sourceKey = sourceKey;\n }\n}\n\nexport function formatRecursiveRefError(\n sourceKey: string,\n cycle: Array<string>,\n schemaPath: string\n): string {\n const lines = [\n bold(red(`typeforge: recursive schema reference in source \"${sourceKey}\"`)),\n \"\",\n bold(\"Cycle:\"),\n ` ${cycle.join(\" → \")}`,\n \"\",\n bold(\"At:\"),\n dim(` ${schemaPath}`),\n \"\",\n bold(\"Fix:\"),\n \" • Add a known-type override in known-types.ts for this shape, or\",\n \" • Simplify the OpenAPI schema to remove the circular reference\",\n cyan(` • typeforge generate --source ${sourceKey} --spec <path>`),\n ];\n return lines.join(\"\\n\");\n}\n","import type { IRSchema } from \"../../parser/types\";\nimport { resolveRef } from \"../../emitters/resolve-schema\";\nimport type { DeclarativeKnownTypeRule } from \"./types\";\n\nfunction resolveObjectSchema(\n schema: IRSchema,\n components: Record<string, IRSchema>\n): IRSchema | undefined {\n const resolved =\n schema.kind === \"ref\" ? resolveRef(schema, components) : schema;\n return resolved.kind === \"object\" ? resolved : undefined;\n}\n\nfunction sortedStrings(values: Array<string>): Array<string> {\n return values.slice().toSorted((left, right) => left.localeCompare(right));\n}\n\nexport function matchesExactProperties(\n schema: IRSchema,\n components: Record<string, IRSchema>,\n exactProperties: Array<string>\n): boolean {\n const objectSchema = resolveObjectSchema(schema, components);\n if (objectSchema?.properties === undefined) {\n return false;\n }\n const keys = sortedStrings(Object.keys(objectSchema.properties));\n const expected = sortedStrings(exactProperties);\n return (\n keys.length === expected.length &&\n keys.every((key, index) => key === expected[index])\n );\n}\n\nexport function matchesDeclarativeRule(\n schema: IRSchema,\n components: Record<string, IRSchema>,\n rule: Pick<\n DeclarativeKnownTypeRule,\n | \"exactProperties\"\n | \"requireProperties\"\n | \"excludeProperties\"\n | \"maxPropertyCount\"\n >\n): boolean {\n const objectSchema = resolveObjectSchema(schema, components);\n if (objectSchema?.properties === undefined) {\n return false;\n }\n\n const keys = Object.keys(objectSchema.properties);\n if (\n rule.maxPropertyCount !== undefined &&\n keys.length > rule.maxPropertyCount\n ) {\n return false;\n }\n if (\n rule.exactProperties !== undefined &&\n !matchesExactProperties(schema, components, rule.exactProperties)\n ) {\n return false;\n }\n if (rule.requireProperties !== undefined) {\n for (const required of rule.requireProperties) {\n if (!(required in objectSchema.properties)) {\n return false;\n }\n }\n }\n if (rule.excludeProperties !== undefined) {\n for (const excluded of rule.excludeProperties) {\n if (excluded in objectSchema.properties) {\n return false;\n }\n }\n }\n return (\n rule.exactProperties !== undefined || rule.requireProperties !== undefined\n );\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nimport type { DeclarativeKnownTypeRule, KnownTypeRule } from \"./types\";\nimport { matchesDeclarativeRule } from \"./matchers\";\n\nfunction parseStringArray(\n block: string | undefined\n): Array<string> | undefined {\n if (block === undefined) {\n return undefined;\n }\n const values = [...block.matchAll(/[\"'`]([^\"'`]+)[\"'`]/g)].map(\n (match) => match[1]!\n );\n return values.length > 0 ? values : undefined;\n}\n\nfunction parseDeclarativeRules(\n content: string\n): Array<DeclarativeKnownTypeRule> {\n const rules: Array<DeclarativeKnownTypeRule> = [];\n const objectBlocks = content.matchAll(/\\{([^{}]*(?:\\{[^{}]*\\}[^{}]*)*)\\}/g);\n\n for (const block of objectBlocks) {\n const body = block[1];\n if (body === undefined || !body.includes(\"typeName\")) {\n continue;\n }\n\n const name = body.match(/name:\\s*[\"'`]([^\"'`]+)[\"'`]/)?.[1];\n const typeName = body.match(/typeName:\\s*[\"'`]([^\"'`]+)[\"'`]/)?.[1];\n if (name === undefined || typeName === undefined) {\n continue;\n }\n\n const rule: DeclarativeKnownTypeRule = { name, typeName };\n const importPath = body.match(\n /importPath:\\s*(null|[\"'`]([^\"'`]*)[\"'`])/\n )?.[2];\n if (body.includes(\"importPath: null\")) {\n rule.importPath = null;\n } else if (importPath !== undefined) {\n rule.importPath = importPath;\n }\n\n const exactProperties = parseStringArray(\n body.match(/exactProperties:\\s*\\[([\\s\\S]*?)\\]/)?.[1]\n );\n if (exactProperties !== undefined) {\n rule.exactProperties = exactProperties;\n }\n\n const requireProperties = parseStringArray(\n body.match(/requireProperties:\\s*\\[([\\s\\S]*?)\\]/)?.[1]\n );\n if (requireProperties !== undefined) {\n rule.requireProperties = requireProperties;\n }\n\n const excludeProperties = parseStringArray(\n body.match(/excludeProperties:\\s*\\[([\\s\\S]*?)\\]/)?.[1]\n );\n if (excludeProperties !== undefined) {\n rule.excludeProperties = excludeProperties;\n }\n\n const maxPropertyCount = body.match(/maxPropertyCount:\\s*(\\d+)/)?.[1];\n if (maxPropertyCount !== undefined) {\n rule.maxPropertyCount = Number.parseInt(maxPropertyCount, 10);\n }\n\n rules.push(rule);\n }\n\n return rules;\n}\n\nexport function loadUserKnownTypes(\n cwd: string,\n apiRoot: string\n): Array<KnownTypeRule> {\n const knownTypesPath = resolve(cwd, apiRoot, \"known-types.ts\");\n if (!existsSync(knownTypesPath)) {\n return [];\n }\n\n const content = readFileSync(knownTypesPath, \"utf8\");\n return parseDeclarativeRules(content).map((rule): KnownTypeRule => ({\n importPath: rule.importPath ?? null,\n matcher: (schema, components) =>\n matchesDeclarativeRule(schema, components, rule),\n name: rule.name,\n typeName: rule.typeName,\n }));\n}\n","import type { IRSchema } from \"../../parser/types\";\nimport { loadUserKnownTypes } from \"./load\";\nimport type { KnownTypeMatch, KnownTypeRule } from \"./types\";\n\nexport type {\n DeclarativeKnownTypeRule,\n KnownTypeMatch,\n KnownTypeRule,\n} from \"./types\";\nexport { loadUserKnownTypes } from \"./load\";\nexport { matchesDeclarativeRule, matchesExactProperties } from \"./matchers\";\n\nexport function loadKnownTypeRules(\n cwd: string,\n apiRoot: string\n): Array<KnownTypeRule> {\n return loadUserKnownTypes(cwd, apiRoot);\n}\n\nexport function matchKnownType(\n schema: IRSchema,\n components: Record<string, IRSchema>,\n rules: Array<KnownTypeRule>\n): KnownTypeMatch | undefined {\n for (const rule of rules) {\n if (rule.matcher(schema, components)) {\n return {\n importPath: rule.importPath,\n rule,\n typeName: rule.typeName,\n };\n }\n }\n return undefined;\n}\n","import type { JsonObject, JsonValue } from \"../json/types\";\nimport { isJsonObject } from \"../json/types\";\nimport type { IRSchema } from \"../parser/types\";\nimport { parseSchema } from \"../parser/index\";\nimport { RecursiveRefError } from \"./recursive-ref-error\";\nimport { refNameFromSchema, resolveRef } from \"./resolve-schema\";\nimport { matchKnownType } from \"../plugins/known-types/index\";\nimport type { KnownTypeRule } from \"../plugins/known-types/index\";\n\nexport interface SchemaRenderContext {\n components: Record<string, IRSchema>;\n knownTypes?: Array<KnownTypeRule>;\n knownTypeImports?: Map<string, string | null>;\n visitedRefs?: Set<string>;\n refStack?: Array<string>;\n schemaPath?: string;\n sourceKey?: string;\n rawSpec?: JsonObject;\n maxDepth?: number;\n depth?: number;\n resolveMapKeyRefs?: boolean;\n}\n\nconst DEFAULT_MAX_DEPTH = 50;\n\nfunction indent(level: number): string {\n return \" \".repeat(level);\n}\n\nfunction formatEnumLiteral(value: string | number | boolean | null): string {\n if (typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value === null) {\n return \"null\";\n }\n return \"unknown\";\n}\n\nfunction formatEnumUnion(\n enumValues: Array<string | number | boolean | null>\n): string {\n return [...new Set(enumValues.map(formatEnumLiteral))].join(\" | \");\n}\n\nfunction withNullable(type: string, schema: IRSchema): string {\n if (schema.nullable === true) {\n return `${type} | null`;\n }\n return type;\n}\n\nfunction decodeJsonPointerSegment(segment: string): string {\n return decodeURIComponent(segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n}\n\nfunction readJsonPointerValue(\n value: JsonValue,\n segment: string\n): JsonValue | undefined {\n if (Array.isArray(value)) {\n const index = Number(segment);\n if (!Number.isInteger(index) || index < 0 || index >= value.length) {\n return undefined;\n }\n return value[index];\n }\n if (isJsonObject(value) && segment in value) {\n return value[segment];\n }\n return undefined;\n}\n\nfunction resolveOpenApiPointer(\n spec: JsonObject,\n pointer: string\n): IRSchema | undefined {\n if (!pointer.startsWith(\"#/\")) {\n return undefined;\n }\n\n let value: JsonValue | undefined = spec;\n for (const part of pointer\n .slice(2)\n .split(\"/\")\n .map(decodeJsonPointerSegment)) {\n value = value === undefined ? undefined : readJsonPointerValue(value, part);\n if (value === undefined) {\n return undefined;\n }\n }\n\n return parseSchema(value);\n}\n\nfunction getMapKeyType(schema: IRSchema, ctx: SchemaRenderContext): string {\n const keyRef = schema[\"x-map-key-ref\"];\n if (keyRef === undefined) {\n return \"string\";\n }\n\n if (ctx.rawSpec !== undefined) {\n const referenced = resolveOpenApiPointer(ctx.rawSpec, keyRef);\n if (referenced !== undefined) {\n return renderSchemaType(referenced, {\n ...ctx,\n depth: (ctx.depth ?? 0) + 1,\n });\n }\n }\n\n const refName = keyRef.split(\"/\").pop();\n if (refName !== undefined && ctx.components[refName] !== undefined) {\n return renderSchemaType(ctx.components[refName]!, {\n ...ctx,\n depth: (ctx.depth ?? 0) + 1,\n });\n }\n\n return \"string\";\n}\n\nfunction throwRecursiveError(ctx: SchemaRenderContext, refName: string): never {\n const stack = ctx.refStack ?? [];\n const cycle = [...stack, refName];\n throw new RecursiveRefError(\n ctx.sourceKey ?? \"unknown\",\n cycle,\n ctx.schemaPath ?? refName\n );\n}\n\nfunction childContext(\n ctx: SchemaRenderContext,\n segment: string\n): SchemaRenderContext {\n const basePath = ctx.schemaPath ?? \"schema\";\n return {\n ...ctx,\n schemaPath: `${basePath}.${segment}`,\n };\n}\n\nexport function renderSchemaType(\n schema: IRSchema,\n ctx: SchemaRenderContext\n): string {\n const depth = ctx.depth ?? 0;\n const maxDepth = ctx.maxDepth ?? DEFAULT_MAX_DEPTH;\n if (depth > maxDepth) {\n throw new RecursiveRefError(\n ctx.sourceKey ?? \"unknown\",\n ctx.refStack ?? [],\n `${ctx.schemaPath ?? \"schema\"} (max depth ${maxDepth} exceeded)`\n );\n }\n\n const nextCtx: SchemaRenderContext = {\n ...ctx,\n depth: depth + 1,\n };\n\n const knownRules = ctx.knownTypes ?? [];\n if (knownRules.length > 0) {\n const known = matchKnownType(schema, ctx.components, knownRules);\n if (known !== undefined) {\n if (\n ctx.knownTypeImports !== undefined &&\n !ctx.knownTypeImports.has(known.typeName)\n ) {\n ctx.knownTypeImports.set(known.typeName, known.importPath);\n }\n return withNullable(known.typeName, schema);\n }\n }\n\n if (schema.enum !== undefined && schema.enum.length > 0) {\n return withNullable(formatEnumUnion(schema.enum), schema);\n }\n\n if (schema.kind === \"ref\") {\n const refName = refNameFromSchema(schema);\n if (refName === undefined) {\n return \"unknown\";\n }\n\n const visited = ctx.visitedRefs ?? new Set<string>();\n const refStack = ctx.refStack ?? [];\n\n if (visited.has(refName)) {\n throwRecursiveError(ctx, refName);\n }\n\n const resolved = resolveRef(schema, ctx.components);\n const refCtx: SchemaRenderContext = {\n ...nextCtx,\n refStack: [...refStack, refName],\n visitedRefs: new Set([...visited, refName]),\n };\n return renderSchemaType(resolved, refCtx);\n }\n\n switch (schema.kind) {\n case \"string\":\n return withNullable(\"string\", schema);\n case \"number\":\n return withNullable(\"number\", schema);\n case \"boolean\":\n return withNullable(\"boolean\", schema);\n case \"null\":\n return \"null\";\n case \"unknown\":\n return \"unknown\";\n case \"array\": {\n const itemType =\n schema.items === undefined\n ? \"unknown\"\n : renderSchemaType(schema.items, childContext(nextCtx, \"[]\"));\n if (itemType === \"TiptapDocument\") {\n return withNullable(\"TiptapDocument\", schema);\n }\n return withNullable(\n `${itemType.includes(\" | \") ? `(${itemType})` : itemType}[]`,\n schema\n );\n }\n case \"object\": {\n if (schema.properties === undefined) {\n if (schema.additionalProperties === true) {\n return withNullable(\"Record<string, unknown>\", schema);\n }\n if (\n typeof schema.additionalProperties === \"object\" &&\n schema.additionalProperties !== null\n ) {\n const keyType =\n ctx.resolveMapKeyRefs !== false &&\n schema[\"x-map-key-ref\"] !== undefined\n ? getMapKeyType(schema, ctx)\n : \"string\";\n const valueType = renderSchemaType(\n schema.additionalProperties,\n childContext(nextCtx, \"value\")\n );\n return withNullable(`Record<${keyType}, ${valueType}>`, schema);\n }\n return withNullable(\"Record<string, unknown>\", schema);\n }\n\n const lines: Array<string> = [\"{\"];\n for (const [name, property] of Object.entries(schema.properties)) {\n const optional = property.required ? \"\" : \"?\";\n const type = renderSchemaType(\n property.schema,\n childContext(nextCtx, name)\n );\n lines.push(`${indent(depth + 1)}${name}${optional}: ${type};`);\n }\n lines.push(`${indent(depth)}}`);\n return withNullable(lines.join(\"\\n\"), schema);\n }\n case \"oneOf\":\n case \"anyOf\": {\n const variants = schema[schema.kind];\n if (variants === undefined || variants.length === 0) {\n return \"unknown\";\n }\n\n const renderedVariants = variants.map((variant) =>\n renderSchemaType(variant, nextCtx)\n );\n const specificVariants = renderedVariants.filter(\n (variant) => variant !== \"Record<string, unknown>\"\n );\n return withNullable(\n (specificVariants.length > 0\n ? specificVariants\n : renderedVariants\n ).join(\" | \"),\n schema\n );\n }\n case \"allOf\": {\n const parts = schema.allOf;\n if (parts === undefined || parts.length === 0) {\n return \"unknown\";\n }\n return withNullable(\n parts.map((part) => renderSchemaType(part, nextCtx)).join(\" & \"),\n schema\n );\n }\n default:\n return \"unknown\";\n }\n}\n\nexport { resolveRef } from \"./resolve-schema\";\n","import {\n buildBaseResponseInterface,\n isEnvelopeSchema,\n matchesEnvelopeShape,\n} from \"../../envelope-guard/index\";\nimport type { EnvelopeMode, EnvelopeShape } from \"../../envelope-guard/index\";\nimport type { QueryExtendsConfig } from \"../../config/types\";\nimport { DEFAULT_MAX_RENDER_DEPTH } from \"../../config/types\";\nimport type { JsonObject } from \"../../json/types\";\nimport type { KnownTypeRule } from \"../../plugins/known-types/index\";\nimport type { IROperation, IRQueryParam, IRSource } from \"../../parser/types\";\nimport type { TsconfigPathsConfig } from \"../../utils/tsconfig-paths\";\nimport { resolveAliasAwareImport } from \"../../utils/imports\";\nimport { renderSchemaType } from \"../schema-renderer\";\nimport type { SchemaRenderContext } from \"../schema-renderer\";\nimport { resolveObjectSchema } from \"../resolve-schema\";\nimport {\n getFunctionTypeName,\n getSuccessResponseSchema,\n hasMeaningfulRequestBody,\n} from \"../../utils/type-names\";\n\nexport interface TypesEmitterOptions {\n source: IRSource;\n envelopeMode: EnvelopeMode;\n sharedEnvelope?: EnvelopeShape;\n knownTypes?: Array<KnownTypeRule>;\n rawSpec?: JsonObject;\n sourceKey?: string;\n queryExtends?: QueryExtendsConfig;\n maxRenderDepth?: number;\n resolveMapKeyRefs?: boolean;\n unwrapResponseData?: boolean;\n typesDir: string;\n baseFile: string;\n tsconfigPaths?: TsconfigPathsConfig;\n}\n\nfunction createRenderContext(\n options: TypesEmitterOptions,\n schemaPath: string,\n knownTypeImports: Map<string, string | null>\n): SchemaRenderContext {\n const ctx: SchemaRenderContext = {\n components: options.source.components.schemas,\n knownTypeImports,\n knownTypes: options.knownTypes ?? [],\n maxDepth: options.maxRenderDepth ?? DEFAULT_MAX_RENDER_DEPTH,\n resolveMapKeyRefs: options.resolveMapKeyRefs !== false,\n schemaPath,\n };\n if (options.sourceKey !== undefined) {\n ctx.sourceKey = options.sourceKey;\n }\n if (options.rawSpec !== undefined) {\n ctx.rawSpec = options.rawSpec;\n }\n return ctx;\n}\n\nfunction formatImportLines(\n knownTypeImports: Map<string, string | null>\n): Array<string> {\n const lines: Array<string> = [];\n const byPath = new Map<string | null, Array<string>>();\n\n for (const [typeName, importPath] of knownTypeImports.entries()) {\n const existing = byPath.get(importPath) ?? [];\n existing.push(typeName);\n byPath.set(importPath, existing);\n }\n\n for (const [importPath, typeNames] of byPath.entries()) {\n if (importPath === null) {\n continue;\n }\n lines.push(`import type { ${typeNames.join(\", \")} } from \"${importPath}\";`);\n }\n\n return lines;\n}\n\nfunction renderParamsInterface(\n typeName: string,\n operation: IROperation,\n options: TypesEmitterOptions,\n knownTypeImports: Map<string, string | null>\n): string | undefined {\n if (operation.queryParams.length === 0) {\n return undefined;\n }\n\n const queryExtends = options.queryExtends;\n const pageName = queryExtends?.page ?? \"page\";\n const limitName = queryExtends?.limit ?? \"limit\";\n const sortByName = queryExtends?.sortBy ?? \"sortBy\";\n const sortOrderName = queryExtends?.sortOrder ?? \"sortOrder\";\n\n const hasPage = operation.queryParams.some(\n (param) => param.name === pageName\n );\n const hasLimit = operation.queryParams.some(\n (param) => param.name === limitName\n );\n const sortByParam = operation.queryParams.find(\n (param) => param.name === sortByName\n );\n const hasSortOrder = operation.queryParams.some(\n (param) => param.name === sortOrderName\n );\n\n const hasOffsetLimitQuery = hasPage && hasLimit;\n const hasSortParams = sortByParam !== undefined && hasSortOrder;\n\n const commonParamNames = new Set<string>(\n [\n hasOffsetLimitQuery ? pageName : undefined,\n hasOffsetLimitQuery ? limitName : undefined,\n hasSortParams ? sortByName : undefined,\n hasSortParams ? sortOrderName : undefined,\n ].filter((name): name is string => name !== undefined)\n );\n\n const nonCommonParams = operation.queryParams.filter(\n (param) => !commonParamNames.has(param.name)\n );\n\n const extendsParts: Array<string> = [];\n if (\n hasSortParams &&\n sortByParam !== undefined &&\n sortByParam.schema.enum !== undefined &&\n sortByParam.schema.enum.length > 0 &&\n queryExtends?.sortTypeName !== undefined\n ) {\n const sortOptions = [\n ...new Set(sortByParam.schema.enum.map((value) => JSON.stringify(value))),\n ].join(\" | \");\n extendsParts.push(`${queryExtends.sortTypeName}<${sortOptions}>`);\n if (queryExtends.sortImportPath !== undefined) {\n knownTypeImports.set(\n queryExtends.sortTypeName,\n queryExtends.sortImportPath\n );\n }\n }\n if (hasOffsetLimitQuery && queryExtends?.paginationTypeName !== undefined) {\n extendsParts.push(queryExtends.paginationTypeName);\n if (queryExtends.paginationImportPath !== undefined) {\n knownTypeImports.set(\n queryExtends.paginationTypeName,\n queryExtends.paginationImportPath\n );\n }\n }\n\n if (extendsParts.length > 0 && nonCommonParams.length === 0) {\n return `export type ${typeName}Params = ${extendsParts.join(\" & \")};`;\n }\n\n const lines: Array<string> = [];\n if (extendsParts.length > 0) {\n lines.push(\n `export interface ${typeName}Params extends ${extendsParts.join(\", \")} {`\n );\n } else {\n lines.push(`export interface ${typeName}Params {`);\n }\n\n for (const param of nonCommonParams) {\n appendQueryParam(param, lines, options, knownTypeImports, typeName);\n }\n\n lines.push(\"}\");\n return lines.join(\"\\n\");\n}\n\nfunction appendQueryParam(\n param: IRQueryParam,\n lines: Array<string>,\n options: TypesEmitterOptions,\n knownTypeImports: Map<string, string | null>,\n typeName: string\n): void {\n const optional = param.required ? \"\" : \"?\";\n const type = renderSchemaType(\n param.schema,\n createRenderContext(\n options,\n `${typeName}Params.${param.name}`,\n knownTypeImports\n )\n );\n lines.push(` ${param.name}${optional}: ${type};`);\n}\n\nfunction renderBodyInterface(\n typeName: string,\n operation: IROperation,\n options: TypesEmitterOptions,\n knownTypeImports: Map<string, string | null>\n): string | undefined {\n if (\n !hasMeaningfulRequestBody(operation) ||\n operation.requestBody === undefined\n ) {\n return undefined;\n }\n\n const bodyType = renderSchemaType(\n operation.requestBody.schema,\n createRenderContext(options, `${typeName}Body`, knownTypeImports)\n );\n if (bodyType.startsWith(\"{\")) {\n return `export interface ${typeName}Body ${bodyType}`;\n }\n return `export type ${typeName}Body = ${bodyType};`;\n}\n\nfunction resolveSuccessResponseSchema(\n schema: NonNullable<ReturnType<typeof getSuccessResponseSchema>>,\n components: IRSource[\"components\"][\"schemas\"]\n) {\n return resolveObjectSchema(schema, components) ?? schema;\n}\n\nfunction renderResponseType(\n typeName: string,\n operation: IROperation,\n options: TypesEmitterOptions,\n _envelopeMode: EnvelopeMode,\n knownTypeImports: Map<string, string | null>,\n baseImportPath: string\n): string {\n const schema = getSuccessResponseSchema(operation);\n if (schema === undefined) {\n return `export type ${typeName}Response = unknown;`;\n }\n\n const resolved = resolveSuccessResponseSchema(\n schema,\n options.source.components.schemas\n );\n const dataSchema =\n resolved.kind === \"object\" && resolved.properties?.data !== undefined\n ? resolved.properties.data.schema\n : undefined;\n const isSuccessEnvelope =\n resolved.kind === \"object\" &&\n resolved.properties?.success !== undefined &&\n isEnvelopeSchema(schema, options.source.components.schemas);\n if (options.unwrapResponseData === true && isSuccessEnvelope) {\n if (dataSchema === undefined) {\n return `export type ${typeName}Response = null;`;\n }\n const dataType = renderSchemaType(\n dataSchema,\n createRenderContext(options, `${typeName}Response.data`, knownTypeImports)\n );\n return `export type ${typeName}Response = ${dataType};`;\n }\n\n if (dataSchema !== undefined) {\n const usesBaseResponse =\n _envelopeMode === \"shared\" ||\n (_envelopeMode === \"mixed\" &&\n options.sharedEnvelope !== undefined &&\n matchesEnvelopeShape(\n schema,\n options.source.components.schemas,\n options.sharedEnvelope\n ));\n if (!usesBaseResponse) {\n const responseType = renderSchemaType(\n schema,\n createRenderContext(options, `${typeName}Response`, knownTypeImports)\n );\n return `export type ${typeName}Response = ${responseType};`;\n }\n\n const dataType = renderSchemaType(\n dataSchema,\n createRenderContext(options, `${typeName}Response.data`, knownTypeImports)\n );\n const responseType = renderSchemaType(\n schema,\n createRenderContext(options, `${typeName}Response`, knownTypeImports)\n );\n return `export type ${typeName}Response = import(\"${baseImportPath}\").BaseResponse<${dataType}> & Omit<${responseType}, \"data\">;`;\n }\n\n const responseType = renderSchemaType(\n schema,\n createRenderContext(options, `${typeName}Response`, knownTypeImports)\n );\n return `export type ${typeName}Response = ${responseType};`;\n}\n\nexport interface GeneratedTypeFile {\n relativePath: string;\n content: string;\n}\n\nexport function emitTypeFiles(\n options: TypesEmitterOptions\n): Array<GeneratedTypeFile> {\n const files: Array<GeneratedTypeFile> = [];\n\n for (const pathItem of options.source.paths) {\n for (const operation of pathItem.operations) {\n const typeName = getFunctionTypeName(\n pathItem.cleanPath,\n operation.method\n );\n const knownTypeImports = new Map<string, string | null>();\n\n const blocks: Array<string> = [\n \"// Auto-generated from OpenAPI spec\",\n `// Path: ${operation.method.toUpperCase()} ${pathItem.path}`,\n \"// DO NOT EDIT - This file is automatically generated\",\n \"\",\n ];\n\n const paramsBlock = renderParamsInterface(\n typeName,\n operation,\n options,\n knownTypeImports\n );\n if (paramsBlock !== undefined) {\n blocks.push(paramsBlock, \"\");\n }\n\n const bodyBlock = renderBodyInterface(\n typeName,\n operation,\n options,\n knownTypeImports\n );\n if (bodyBlock !== undefined) {\n blocks.push(bodyBlock, \"\");\n }\n\n const typeFile = `${options.typesDir}/${pathItem.cleanPath}/${operation.method.toUpperCase()}.d.ts`;\n const baseImportPath = resolveAliasAwareImport({\n fromAbsolutePath: typeFile,\n toAbsolutePath: options.baseFile\n .replace(/\\.d\\.ts$/, \"\")\n .replace(/\\.ts$/, \"\"),\n ...(options.tsconfigPaths === undefined\n ? {}\n : { tsconfigPaths: options.tsconfigPaths }),\n });\n\n blocks.push(\n renderResponseType(\n typeName,\n operation,\n options,\n options.envelopeMode,\n knownTypeImports,\n baseImportPath\n )\n );\n\n const importLines = formatImportLines(knownTypeImports);\n const content = [\n ...importLines,\n ...(importLines.length > 0 ? [\"\"] : []),\n ...blocks,\n ]\n .join(\"\\n\")\n .trimEnd();\n\n files.push({\n content: `${content}\\n`,\n relativePath: `${pathItem.cleanPath}/${operation.method.toUpperCase()}.d.ts`,\n });\n }\n }\n\n return files;\n}\n\nexport function emitBaseFile(sharedEnvelope: EnvelopeShape): string {\n const lines = [\n \"// Auto-generated from OpenAPI spec\",\n \"// DO NOT EDIT - This file is automatically generated\",\n \"\",\n buildBaseResponseInterface(sharedEnvelope),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n","import { bold, cyan, dim, red, yellow } from \"../color/index\";\nimport type {\n EnvelopeFieldDiff,\n EnvelopeShape,\n OperationEnvelope,\n} from \"./index\";\n\nexport function formatMixedEnvelopeError(\n sourceKey: string,\n groups: Map<string, Array<OperationEnvelope>>\n): string {\n const header = bold(\n red(`typeforge: mixed envelope shapes in source \"${sourceKey}\"`)\n );\n const lines = [header, \"\"];\n\n let index = 0;\n for (const [, operations] of groups.entries()) {\n index += 1;\n lines.push(\n bold(\n `Shape ${String.fromCharCode(64 + index)} — ${operations.length} operations`\n )\n );\n const sample = operations[0]?.shape.fields ?? [];\n for (const field of sample) {\n lines.push(` ${field.name}${field.required ? \"\" : \"?\"}: ${field.kind}`);\n }\n lines.push(\"\");\n for (const operation of operations.slice(0, 5)) {\n lines.push(dim(` ${operation.method} ${operation.path}`));\n }\n if (operations.length > 5) {\n lines.push(dim(` … and ${operations.length - 5} more`));\n }\n lines.push(\"\");\n }\n\n lines.push(bold(\"Fix:\"));\n lines.push(\" • Narrow pathPrefix or add ignorePaths in source.ts\");\n lines.push(\n cyan(` • typeforge generate --source ${sourceKey} --spec <path>`)\n );\n\n return lines.join(\"\\n\");\n}\n\nexport function formatDriftError(\n sourceKey: string,\n spec: EnvelopeShape,\n userSource: string,\n userBlock: string,\n diffs: Array<EnvelopeFieldDiff>,\n outliers: Array<OperationEnvelope> = []\n): string {\n const header = bold(\n red(`typeforge: base response mismatch in source \"${sourceKey}\"`)\n );\n const lines = [header, \"\"];\n\n lines.push(bold(\"Spec envelope:\"));\n for (const field of spec.fields) {\n lines.push(` ${field.name}${field.required ? \"\" : \"?\"}: ${field.kind}`);\n }\n lines.push(\"\");\n\n lines.push(bold(`Your ${userSource} BaseResponse:`));\n lines.push(userBlock);\n lines.push(\"\");\n\n lines.push(bold(\"Conflicts:\"));\n for (const diff of diffs) {\n if (diff.issue === \"missing\") {\n lines.push(\n yellow(` • ${diff.field}: present in spec, missing in your type`)\n );\n } else if (diff.issue === \"extra\") {\n lines.push(yellow(` • ${diff.field}: extra field in your type`));\n } else if (diff.issue === \"type-changed\") {\n lines.push(\n yellow(\n ` • ${diff.field}: spec is ${diff.spec?.kind}, your type is ${diff.user?.kind}`\n )\n );\n } else {\n lines.push(yellow(` • ${diff.field}: required/optional mismatch`));\n }\n }\n\n if (outliers.length > 0) {\n lines.push(\"\");\n lines.push(dim(\"Also not matching the spec envelope:\"));\n for (const outlier of outliers.slice(0, 3)) {\n lines.push(dim(` ${outlier.method} ${outlier.path}`));\n }\n }\n\n lines.push(\"\");\n lines.push(bold(\"Fix:\"));\n lines.push(\" • Update models.ts to match the spec, or\");\n lines.push(\n cyan(\n ` • typeforge generate --source ${sourceKey} --spec <path> --accept-base`\n )\n );\n\n return lines.join(\"\\n\");\n}\n","import { bold, cyan, dim, red, white, yellow } from \"./index\";\n\nexport interface DiagnosticSnippet {\n column: number;\n file: string;\n highlightEnd: number;\n highlightStart: number;\n label?: string;\n line: number;\n source: string;\n}\n\nexport interface DiagnosticOptions {\n code: string;\n help?: string;\n message: string;\n severity?: \"error\" | \"warning\";\n snippet?: DiagnosticSnippet;\n}\n\nfunction formatCaretLine(\n column: number,\n highlightStart: number,\n highlightEnd: number,\n label?: string\n): string {\n const caretPrefix = \" \".repeat(column + 1);\n const caretBody = `${\" \".repeat(Math.max(highlightEnd - highlightStart, 1))}|`;\n const caret = `${caretPrefix}:${caretBody}`;\n if (label === undefined) {\n return caret;\n }\n const labelPrefix = \" \".repeat(column + highlightEnd + 3);\n return `${caret}\\n${labelPrefix}\\`${dim(`-- ${label}`)}`;\n}\n\nfunction formatSnippet(snippet: DiagnosticSnippet): string {\n const header = dim(\n ` ,-[${snippet.file}:${snippet.line}:${snippet.column}]`\n );\n const source = white(\n `${String(snippet.line).padStart(4, \" \")} | ${snippet.source}`\n );\n const caret = formatCaretLine(\n 4 + \" | \".length + snippet.highlightStart,\n snippet.highlightStart,\n snippet.highlightEnd,\n snippet.label\n );\n const footer = dim(\" `----\");\n return [header, source, caret, footer].join(\"\\n\");\n}\n\nexport function formatDiagnostic(options: DiagnosticOptions): string {\n const severity = options.severity ?? \"error\";\n const icon = severity === \"error\" ? red(\"×\") : yellow(\"!\");\n const lines = [` ${icon} ${bold(`${options.code}`)}: ${options.message}`];\n\n if (options.snippet !== undefined) {\n lines.push(formatSnippet(options.snippet));\n }\n\n if (options.help !== undefined) {\n lines.push(` ${dim(\"help:\")} ${options.help}`);\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function formatHelpList(title: string, items: Array<string>): string {\n return [bold(title), ...items.map((item) => ` ${cyan(item)}`)].join(\"\\n\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { formatDiagnostic, formatHelpList } from \"../color/diagnostic\";\nimport { bold, dim } from \"../color/index\";\nimport type { JsonValue } from \"../json/types\";\nimport { parseJson, readJsonObject } from \"../json/types\";\n\nexport type SpecSource =\n | { kind: \"file\"; path: string }\n | { kind: \"env\"; varName: string }\n | { kind: \"local-override\"; path: string };\n\nexport async function loadSpec(source: SpecSource): Promise<JsonValue> {\n let filePath: string;\n\n switch (source.kind) {\n case \"file\": {\n filePath = resolve(source.path);\n break;\n }\n case \"local-override\": {\n filePath = resolve(source.path);\n break;\n }\n case \"env\": {\n const envValue = process.env[source.varName];\n if (envValue === undefined) {\n throw new Error(`Environment variable ${source.varName} is not set`);\n }\n filePath = resolve(envValue);\n break;\n }\n }\n\n const content = await readFile(filePath, \"utf8\");\n return parseJson(content);\n}\n\n/**\n * Resolution priority:\n * 1. --spec CLI flag\n * 2. OPENAPI_SPEC_<UPPER_KEY> env var\n * 3. source.ts `spec` property (project-relative path from config)\n * 4. typeforge.local.json (gitignored per-machine override)\n * 5. committed snapshot at snapshotPath\n *\n * Throws a human-readable error (no stack trace as first line) when nothing is found.\n */\nexport function resolveSpecSource(\n sourceKey: string,\n opts: {\n specFlag?: string;\n sourceConfigSpec?: string;\n localOverridePath?: string;\n snapshotPath?: string;\n }\n): SpecSource {\n // 1. --spec flag\n if (opts.specFlag !== undefined) {\n return { kind: \"file\", path: opts.specFlag };\n }\n\n // 2. Env var\n const envVarName = `OPENAPI_SPEC_${sourceKey.toUpperCase().replace(/-/g, \"_\")}`,\n envValue = process.env[envVarName];\n if (envValue !== undefined) {\n return { kind: \"env\", varName: envVarName };\n }\n\n // 3. source.ts spec property\n if (opts.sourceConfigSpec !== undefined) {\n return { kind: \"file\", path: opts.sourceConfigSpec };\n }\n\n // 4. Local override file\n const defaultLocalPath = \"./typeforge.local.json\";\n const legacyLocalPath = \"./openapi-codegen.local.json\";\n const localPath =\n opts.localOverridePath ??\n (existsSync(defaultLocalPath) || !existsSync(legacyLocalPath)\n ? defaultLocalPath\n : legacyLocalPath);\n if (existsSync(localPath)) {\n try {\n const localData = readJsonObject(readFileSync(localPath, \"utf8\")),\n specPath = localData[sourceKey];\n if (typeof specPath === \"string\") {\n return { kind: \"local-override\", path: specPath };\n }\n } catch {\n // Malformed local override — fall through\n }\n }\n\n // 5. Committed snapshot\n if (opts.snapshotPath !== undefined && existsSync(opts.snapshotPath)) {\n return { kind: \"file\", path: opts.snapshotPath };\n }\n\n // Nothing found — build a human-readable error\n throw new Error(buildNotFoundMessage(sourceKey, envVarName, opts, localPath));\n}\n\nfunction formatSnapshotNote(snapshotPath: string | undefined): string {\n if (snapshotPath === undefined) {\n return dim(\"not configured\");\n }\n if (existsSync(snapshotPath)) {\n return dim(`found at ${snapshotPath}`);\n }\n return dim(`not found at ${snapshotPath}`);\n}\n\nfunction buildNotFoundMessage(\n sourceKey: string,\n envVarName: string,\n opts: {\n specFlag?: string;\n sourceConfigSpec?: string;\n localOverridePath?: string;\n snapshotPath?: string;\n },\n localPath: string\n): string {\n const specFlagNote =\n opts.specFlag !== undefined ? opts.specFlag : dim(\"not provided\"),\n envNote = dim(\"not set\"),\n sourceConfigNote =\n opts.sourceConfigSpec !== undefined\n ? opts.sourceConfigSpec\n : dim(\"not set in source.ts\"),\n localExists = existsSync(localPath),\n localNote = localExists\n ? dim(`found at ${localPath} (no entry for \"${sourceKey}\")`)\n : dim(`not found at ${localPath}`),\n { snapshotPath } = opts;\n const snapshotNote = formatSnapshotNote(snapshotPath),\n tried = [\n ` --spec flag: ${specFlagNote}`,\n ` ${envVarName} env: ${envNote}`,\n ` source.ts spec: ${sourceConfigNote}`,\n ` local override: ${localNote}`,\n ` committed snapshot: ${snapshotNote}`,\n ].join(\"\\n\"),\n fixCommands = [\n `typeforge generate --source ${sourceKey} --spec ./path/to/swagger.json`,\n `export ${envVarName}=./path/to/swagger.json`,\n ];\n\n const diagnostic = formatDiagnostic({\n code: \"typeforge/spec-not-found\",\n help: \"Provide one of the resolution paths above, for example with --spec or an env var.\",\n message: `No OpenAPI spec found for source \"${sourceKey}\"`,\n severity: \"error\",\n });\n\n return [\n diagnostic,\n \"\",\n bold(\"Tried:\"),\n tried,\n \"\",\n formatHelpList(\"Fix:\", fixCommands),\n ].join(\"\\n\");\n}\n","import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nexport interface OutputFile {\n path: string;\n content: string;\n}\n\nexport async function writeOutputFiles(\n files: Array<OutputFile>,\n check = false\n): Promise<{ written: number; changed: Array<string> }> {\n const changed: Array<string> = [];\n\n for (const file of files) {\n await mkdir(dirname(file.path), { recursive: true });\n\n let existing: string | undefined;\n try {\n existing = await readFile(file.path, \"utf8\");\n } catch {\n existing = undefined;\n }\n\n if (existing === file.content) {\n continue;\n }\n\n changed.push(file.path);\n if (!check) {\n await writeFile(file.path, file.content, \"utf8\");\n }\n }\n\n return { changed, written: check ? 0 : changed.length };\n}\n\nexport async function clearGeneratedDir(\n generatedDir: string,\n preserve: Array<string> = []\n): Promise<void> {\n const preserveSet = new Set(\n preserve.map((entry) => join(generatedDir, entry))\n );\n\n try {\n await rm(generatedDir, { force: true, recursive: true });\n } catch {\n // Directory may not exist yet.\n }\n\n for (const file of preserveSet) {\n await mkdir(dirname(file), { recursive: true });\n }\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\n\nimport {\n detectHttpMode,\n hasQueryScopeFile,\n loadProjectConfig,\n loadSourceConfig,\n readModelsFile,\n} from \"../config/load\";\nimport type { SourceConfig } from \"../config/types\";\nimport { DEFAULT_ROUTE_ENUM_NAME } from \"../config/types\";\nimport { emitFunctionFiles } from \"../emitters/functions/index\";\nimport { emitRuntimeFile } from \"../emitters/runtime/index\";\nimport { emitRoutesFile, mergeRoutesFile } from \"../emitters/routes/index\";\nimport { emitBaseFile, emitTypeFiles } from \"../emitters/types/index\";\nimport type { TypesEmitterOptions } from \"../emitters/types/index\";\nimport {\n analyzeEnvelope,\n buildBaseResponseInterface,\n diffEnvelopeFields,\n getPrimaryEnvelopeShape,\n parseUserBaseResponse,\n} from \"../envelope-guard/index\";\nimport { formatDriftError } from \"../envelope-guard/diagnostic\";\nimport { loadKnownTypeRules } from \"../plugins/known-types/index\";\nimport { isJsonObject } from \"../json/types\";\nimport { loadSpec, resolveSpecSource } from \"../parser/loader\";\nimport { parseSpec } from \"../parser/index\";\nimport type { IRSource } from \"../parser/types\";\nimport { loadTsconfigPaths } from \"../utils/tsconfig-paths\";\nimport { writeOutputFiles } from \"../utils/output\";\nimport type { OutputFile } from \"../utils/output\";\n\nexport interface GenerateOptions {\n cwd?: string;\n sourceKey: string;\n specFlag?: string;\n check?: boolean;\n acceptBase?: boolean;\n}\n\nexport interface GenerateResult {\n sourceKey: string;\n files: number;\n changed: Array<string>;\n check: boolean;\n}\n\nexport interface GenerateContext {\n cwd: string;\n apiRoot: string;\n sourceKey: string;\n sourceConfig: SourceConfig;\n sourceDir: string;\n generatedDir: string;\n typesDir: string;\n functionsDir: string;\n routesFile: string;\n baseFile: string;\n snapshotPath: string;\n httpMode: \"singleton\" | \"injected\";\n hasQueryScope: boolean;\n}\n\nexport function buildGenerateContext(\n cwd: string,\n sourceKey: string\n): GenerateContext {\n const projectConfig = loadProjectConfig(cwd);\n const apiRoot = projectConfig.apiRoot ?? \"src/api\";\n const sourceConfig = loadSourceConfig(cwd, apiRoot, sourceKey);\n const sourceDir = resolve(cwd, apiRoot, sourceKey);\n const generatedDir = join(sourceDir, \"generated\");\n const functionsDir =\n sourceConfig.functionsDir === undefined\n ? join(generatedDir, \"functions\")\n : resolve(cwd, sourceConfig.functionsDir);\n const typesDir =\n sourceConfig.typesDir === undefined\n ? join(generatedDir, \"types\")\n : resolve(cwd, sourceConfig.typesDir);\n\n return {\n apiRoot,\n baseFile:\n sourceConfig.typesDir === undefined\n ? join(generatedDir, \"base.ts\")\n : join(dirname(typesDir), \"base.d.ts\"),\n cwd,\n functionsDir,\n generatedDir,\n hasQueryScope:\n sourceConfig.tanstackQuery === true && hasQueryScopeFile(cwd, apiRoot),\n httpMode: detectHttpMode(cwd, apiRoot),\n routesFile: join(generatedDir, \"routes.ts\"),\n snapshotPath: join(sourceDir, \"spec.json\"),\n sourceConfig,\n sourceDir,\n sourceKey,\n typesDir,\n };\n}\n\nfunction validateEnvelope(\n context: GenerateContext,\n source: IRSource,\n acceptBase: boolean\n): { mode: ReturnType<typeof analyzeEnvelope>[\"mode\"]; error?: string } {\n const analysis = analyzeEnvelope(source);\n\n if (analysis.mode !== \"shared\" || analysis.shared === undefined) {\n return { mode: analysis.mode };\n }\n\n const modelsContent = readModelsFile(context.cwd, context.apiRoot);\n if (modelsContent === undefined) {\n return { mode: analysis.mode };\n }\n\n const userBase = parseUserBaseResponse(modelsContent);\n if (userBase === undefined) {\n return { mode: analysis.mode };\n }\n\n const diffs = diffEnvelopeFields(analysis.shared, userBase);\n if (diffs.length === 0) {\n return { mode: analysis.mode };\n }\n\n if (acceptBase) {\n return { mode: analysis.mode };\n }\n\n const userBlock = userBase.fields\n .map(\n (field) => ` ${field.name}${field.required ? \"\" : \"?\"}: ${field.kind};`\n )\n .join(\"\\n\");\n\n return {\n error: formatDriftError(\n context.sourceKey,\n analysis.shared,\n userBase.sourcePath,\n userBlock,\n diffs\n ),\n mode: analysis.mode,\n };\n}\n\nfunction patchModelsBaseResponse(\n cwd: string,\n apiRoot: string,\n newInterface: string\n): void {\n const modelsPath = resolve(cwd, apiRoot, \"models.ts\");\n if (!existsSync(modelsPath)) {\n return;\n }\n\n const content = readFileSync(modelsPath, \"utf8\");\n const patched = content.replace(\n /export\\s+interface\\s+BaseResponse\\s*<[^>]*>\\s*\\{[\\s\\S]*?\\}/,\n newInterface\n );\n writeFileSync(modelsPath, patched, \"utf8\");\n}\n\nexport async function generateForSource(\n options: GenerateOptions\n): Promise<GenerateResult> {\n const cwd = options.cwd ?? process.cwd();\n const context = buildGenerateContext(cwd, options.sourceKey);\n const specResolveOptions: {\n snapshotPath: string;\n specFlag?: string;\n sourceConfigSpec?: string;\n } = {\n snapshotPath: context.snapshotPath,\n };\n if (options.specFlag !== undefined) {\n specResolveOptions.specFlag = options.specFlag;\n }\n if (context.sourceConfig.spec !== undefined) {\n specResolveOptions.sourceConfigSpec = context.sourceConfig.spec;\n }\n const specSource = resolveSpecSource(options.sourceKey, specResolveOptions);\n const rawSpec = await loadSpec(specSource);\n\n const parseOptions: {\n ignorePaths?: Array<string>;\n pathPrefix?: string;\n } = {};\n if (context.sourceConfig.ignorePaths !== undefined) {\n parseOptions.ignorePaths = context.sourceConfig.ignorePaths;\n }\n if (context.sourceConfig.pathPrefix !== undefined) {\n parseOptions.pathPrefix = context.sourceConfig.pathPrefix;\n }\n const source = parseSpec(rawSpec, parseOptions);\n source.key = options.sourceKey;\n\n const envelopeCheck = validateEnvelope(\n context,\n source,\n options.acceptBase === true\n );\n if (envelopeCheck.error !== undefined) {\n throw new Error(envelopeCheck.error);\n }\n\n const analysis = analyzeEnvelope(source);\n const outputFiles: Array<OutputFile> = [];\n\n const primaryEnvelope = getPrimaryEnvelopeShape(analysis);\n if (primaryEnvelope !== undefined) {\n outputFiles.push({\n content: emitBaseFile(primaryEnvelope),\n path: context.baseFile,\n });\n\n if (options.acceptBase === true) {\n patchModelsBaseResponse(\n cwd,\n context.apiRoot,\n buildBaseResponseInterface(primaryEnvelope)\n );\n }\n }\n\n const typeEmitterOptions: TypesEmitterOptions = {\n baseFile: context.baseFile,\n envelopeMode: analysis.mode,\n knownTypes: loadKnownTypeRules(cwd, context.apiRoot),\n source,\n sourceKey: options.sourceKey,\n typesDir: context.typesDir,\n };\n if (context.sourceConfig.resolveMapKeyRefs !== undefined) {\n typeEmitterOptions.resolveMapKeyRefs =\n context.sourceConfig.resolveMapKeyRefs;\n }\n if (context.sourceConfig.unwrapResponseData !== undefined) {\n typeEmitterOptions.unwrapResponseData =\n context.sourceConfig.unwrapResponseData;\n }\n if (primaryEnvelope !== undefined) {\n typeEmitterOptions.sharedEnvelope = primaryEnvelope;\n }\n const typesTsconfigPaths = loadTsconfigPaths(context.typesDir);\n if (typesTsconfigPaths !== undefined) {\n typeEmitterOptions.tsconfigPaths = typesTsconfigPaths;\n }\n if (context.sourceConfig.maxRenderDepth !== undefined) {\n typeEmitterOptions.maxRenderDepth = context.sourceConfig.maxRenderDepth;\n }\n if (context.sourceConfig.queryExtends !== undefined) {\n typeEmitterOptions.queryExtends = context.sourceConfig.queryExtends;\n }\n if (isJsonObject(rawSpec)) {\n typeEmitterOptions.rawSpec = rawSpec;\n }\n\n const typeFiles = emitTypeFiles(typeEmitterOptions);\n for (const file of typeFiles) {\n outputFiles.push({\n content: file.content,\n path: join(context.typesDir, file.relativePath),\n });\n }\n\n const routeEnumName =\n context.sourceConfig.routeEnumName ?? DEFAULT_ROUTE_ENUM_NAME;\n const routesOptions: {\n paths: typeof source.paths;\n routeEnumName: string;\n stripApiPrefix?: boolean;\n } = {\n paths: source.paths,\n routeEnumName,\n };\n if (context.sourceConfig.stripApiPrefix === true) {\n routesOptions.stripApiPrefix = true;\n }\n const routesContent = emitRoutesFile(routesOptions);\n\n let finalRoutes = routesContent;\n if (\n context.sourceConfig.generationMode === \"merge\" &&\n existsSync(context.routesFile)\n ) {\n finalRoutes = mergeRoutesFile(\n readFileSync(context.routesFile, \"utf8\"),\n routesContent,\n routeEnumName,\n context.sourceConfig.pathPrefix\n );\n }\n\n outputFiles.push({\n content: finalRoutes,\n path: context.routesFile,\n });\n\n outputFiles.push({\n content: emitRuntimeFile({\n hasQueryScope: context.hasQueryScope,\n httpMode: context.httpMode,\n }),\n path: join(context.generatedDir, \"runtime.ts\"),\n });\n\n const tsconfigPaths = loadTsconfigPaths(context.functionsDir);\n const functionEmitterOptions: Parameters<typeof emitFunctionFiles>[0] = {\n functionsDir: context.functionsDir,\n generatedDir: context.generatedDir,\n hasQueryScope: context.hasQueryScope,\n httpMode: context.httpMode,\n paths: source.paths,\n routeEnumName,\n typesDir: context.typesDir,\n };\n if (context.sourceConfig.importBase !== undefined) {\n functionEmitterOptions.importBase = context.sourceConfig.importBase;\n } else if (tsconfigPaths !== undefined) {\n functionEmitterOptions.tsconfigPaths = tsconfigPaths;\n }\n const functionFiles = emitFunctionFiles(functionEmitterOptions);\n\n for (const file of functionFiles) {\n outputFiles.push({\n content: file.content,\n path: join(context.functionsDir, file.relativePath),\n });\n }\n\n const result = await writeOutputFiles(outputFiles, options.check === true);\n\n return {\n changed: result.changed,\n check: options.check === true,\n files: outputFiles.length,\n sourceKey: options.sourceKey,\n };\n}\n","import { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nimport { loadProjectConfig } from \"../config/load\";\nimport type { TypeforgeConfig } from \"../config/types\";\nimport { DEFAULT_API_ROOT } from \"../config/types\";\n\nexport type HttpClient = \"axios\" | \"fetch\" | \"custom\";\nexport type ProjectLayout = \"monolith\" | \"packages\";\n\nexport interface InitOptions {\n cwd?: string;\n sourceKey: string;\n client: HttpClient;\n layout?: ProjectLayout;\n}\n\nconst AXIOS_HTTP_TEMPLATE = `import axiosBase from \"axios\";\nimport { createAxiosAdapter } from \"@openmirai/typeforge/adapters/axios\";\n\nconst axios = axiosBase.create({\n baseURL: process.env.NEXT_PUBLIC_API_URL,\n});\n\naxios.interceptors.request.use(\n async (config) => {\n // Add auth headers, tracing, or Content-Type defaults here.\n return config;\n },\n (error) => Promise.reject(error),\n);\n\naxios.interceptors.response.use(\n (response) => response,\n (error) => Promise.reject(error),\n);\n\nexport const httpFetch = createAxiosAdapter(axios);\nexport { axios };\nexport type { HTTPFetch, HTTPFetchConfig } from \"@openmirai/typeforge/adapters/axios\";\n`;\n\nconst FETCH_HTTP_TEMPLATE = `import { createFetchAdapter } from \"@openmirai/typeforge/adapters/fetch\";\n\nexport const httpFetch = createFetchAdapter({\n baseURL: process.env.NEXT_PUBLIC_API_URL,\n});\n\nexport type { HTTPFetch, HTTPFetchConfig } from \"@openmirai/typeforge/adapters/fetch\";\n`;\n\nconst CUSTOM_HTTP_TEMPLATE = `import type { HTTPFetch, HTTPFetchConfig } from \"@openmirai/typeforge/http\";\n\nexport type { HTTPFetch, HTTPFetchConfig };\n\nexport const httpFetch: HTTPFetch = {\n delete: async <TResponse>(\n _route: string,\n _config?: HTTPFetchConfig\n ): Promise<{ data: TResponse }> => {\n throw new Error(\"Implement httpFetch.delete\");\n },\n get: async <TResponse>(\n _route: string,\n _config?: HTTPFetchConfig\n ): Promise<{ data: TResponse }> => {\n throw new Error(\"Implement httpFetch.get\");\n },\n patch: async <TResponse, TBody = unknown>(\n _route: string,\n _body: TBody,\n _config?: HTTPFetchConfig\n ): Promise<{ data: TResponse }> => {\n throw new Error(\"Implement httpFetch.patch\");\n },\n post: async <TResponse, TBody = unknown>(\n _route: string,\n _body: TBody,\n _config?: HTTPFetchConfig\n ): Promise<{ data: TResponse }> => {\n throw new Error(\"Implement httpFetch.post\");\n },\n put: async <TResponse, TBody = unknown>(\n _route: string,\n _body: TBody,\n _config?: HTTPFetchConfig\n ): Promise<{ data: TResponse }> => {\n throw new Error(\"Implement httpFetch.put\");\n },\n};\n`;\n\nconst SOURCE_TEMPLATE = `import { defineSourceConfig } from \"@openmirai/typeforge\";\n\nexport default defineSourceConfig({\n // Path to the OpenAPI spec file, relative to the project root.\n // Set this so \\`typeforge generate --source <key>\\` (or --all) works\n // without a per-invocation --spec flag.\n // spec: \"./specs/acme.json\",\n pathPrefix: \"/api/acme/v3\",\n stripApiPrefix: true,\n routeEnumName: \"RouteTargets\",\n generationMode: \"authoritative\",\n naming: \"path\",\n ignorePaths: [],\n maxRenderDepth: 50,\n resolveMapKeyRefs: true,\n queryExtends: {\n page: \"page\",\n limit: \"limit\",\n sortBy: \"sortBy\",\n sortOrder: \"sortOrder\",\n paginationTypeName: \"OffsetLimitQuery\",\n paginationImportPath: \"./pagination\",\n sortTypeName: \"SortParams\",\n sortImportPath: \"./pagination\",\n },\n});\n`;\n\nconst KNOWN_TYPES_TEMPLATE = `/** Map OpenAPI object shapes to your own TypeScript types by property pattern. */\nexport const knownTypes = [\n // {\n // name: \"BlobAsset\",\n // typeName: \"BlobAsset\",\n // importPath: \"./blob/types\",\n // exactProperties: [\"id\", \"url\", \"file\"],\n // },\n // {\n // name: \"TiptapNode\",\n // typeName: \"TiptapNode\",\n // importPath: \"./tiptap/types\",\n // requireProperties: [\"type\"],\n // excludeProperties: [\"courseCount\"],\n // },\n];\n`;\n\nfunction defaultApiRoot(layout: ProjectLayout): string {\n return layout === \"packages\" ? \"packages/utils/src/api\" : \"src/api\";\n}\n\nfunction writeIfMissing(path: string, content: string): \"created\" | \"skipped\" {\n if (existsSync(path)) {\n return \"skipped\";\n }\n mkdirSync(join(path, \"..\"), { recursive: true });\n writeFileSync(path, content, \"utf8\");\n return \"created\";\n}\n\nexport function initProject(options: InitOptions): {\n created: Array<string>;\n skipped: Array<string>;\n} {\n const cwd = options.cwd ?? process.cwd();\n const layout = options.layout ?? \"monolith\";\n const configPath = resolve(cwd, \"typeforge.json\");\n const legacyConfigPath = resolve(cwd, \"openapi-codegen.json\");\n const projectConfig = loadProjectConfig(cwd);\n const apiRoot =\n existsSync(configPath) || existsSync(legacyConfigPath)\n ? (projectConfig.apiRoot ?? DEFAULT_API_ROOT)\n : defaultApiRoot(layout);\n const apiRootPath = resolve(cwd, apiRoot);\n const sourceDir = join(apiRootPath, options.sourceKey);\n\n let httpTemplate = CUSTOM_HTTP_TEMPLATE;\n if (options.client === \"axios\") {\n httpTemplate = AXIOS_HTTP_TEMPLATE;\n } else if (options.client === \"fetch\") {\n httpTemplate = FETCH_HTTP_TEMPLATE;\n }\n\n const created: Array<string> = [];\n const skipped: Array<string> = [];\n\n const httpPath = join(apiRootPath, \"http.ts\");\n const httpResult = writeIfMissing(httpPath, httpTemplate);\n if (httpResult === \"created\") {\n created.push(httpPath);\n } else {\n skipped.push(httpPath);\n }\n\n const sourcePath = join(sourceDir, \"source.ts\");\n const sourceResult = writeIfMissing(sourcePath, SOURCE_TEMPLATE);\n if (sourceResult === \"created\") {\n created.push(sourcePath);\n } else {\n skipped.push(sourcePath);\n }\n\n const knownTypesPath = join(apiRootPath, \"known-types.ts\");\n const knownTypesResult = writeIfMissing(knownTypesPath, KNOWN_TYPES_TEMPLATE);\n if (knownTypesResult === \"created\") {\n created.push(knownTypesPath);\n } else {\n skipped.push(knownTypesPath);\n }\n\n const configWritePath = resolve(cwd, \"typeforge.json\");\n if (!existsSync(configWritePath) && !existsSync(legacyConfigPath)) {\n const config: TypeforgeConfig = { apiRoot };\n writeFileSync(\n configWritePath,\n `${JSON.stringify(config, null, 2)}\\n`,\n \"utf8\"\n );\n created.push(configWritePath);\n }\n\n mkdirSync(join(sourceDir, \"generated\"), { recursive: true });\n\n return { created, skipped };\n}\n"],"mappings":";;;;;AAcA,SAAgB,gBAAgB,OAA0C;CACxE,OACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU;AAErB;AAEA,SAAgB,YAAY,OAAoC;CAC9D,IACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,WAEjB,OAAO;CAGT,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,MAAM,WAAW;CAGhC,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,WAAW;CAG/C,OAAO;AACT;AAEA,SAAgB,aAAa,OAAqC;CAChE,OACE,YAAY,KAAK,KACjB,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK;AAExB;AAEA,SAAgB,YAAY,OA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AU,KAAK,WAAW,gBAAgB,IAChD,cAAc,WAAA,YACf,eAAe,MAAM;CAC3B,MAAM,cAAc,QAAQ,KAAK,OAAO;CACxC,MAAM,YAAY,KAAK,aAAa,QAAQ,SAAS;CAErD,IAAI,eAAe;CACnB,IAAI,QAAQ,WAAW,SACrB,eAAe;MACV,IAAI,QAAQ,WAAW,SAC5B,eAAe;CAGjB,MAAM,UAAyB,CAAC;CAChC,MAAM,UAAyB,CAAC;CAEhC,MAAM,WAAW,KAAK,aAAa,SAAS;CAE5C,IADmB,eAAe,UAAU,YAC/B,MAAM,WACjB,QAAQ,KAAK,QAAQ;MAErB,QAAQ,KAAK,QAAQ;CAGvB,MAAM,aAAa,KAAK,WAAW,WAAW;CAE9C,IADqB,eAAe,YAAY,eACjC,MAAM,WACnB,QAAQ,KAAK,UAAU;MAEvB,QAAQ,KAAK,UAAU;CAGzB,MAAM,iBAAiB,KAAK,aAAa,gBAAgB;CAEzD,IADyB,eAAe,gBAAgB,oBACrC,MAAM,WACvB,QAAQ,KAAK,cAAc;MAE3B,QAAQ,KAAK,cAAc;CAG7B,MAAM,kBAAkB,QAAQ,KAAK,gBAAgB;CACrD,IAAI,CAAC,WAAW,eAAe,KAAK,CAAC,WAAW,gBAAgB,GAAG;EAEjE,cACE,iBACA,GAAG,KAAK,UAAU,EAHc,QAGT,GAAG,MAAM,CAAC,EAAE,KACnC,MACF;EACA,QAAQ,KAAK,eAAe;CAC9B;CAEA,UAAU,KAAK,WAAW,WAAW,GAAG,EAAE,WAAW,KAAK,CAAC;CAE3D,OAAO;EAAE;EAAS;CAAQ;AAC5B"}
@@ -0,0 +1,33 @@
1
+ //#region src/routes/types.d.ts
2
+ /** Map of route keys to path-param objects, or undefined for static routes. */
3
+ interface RouteParamsMap {
4
+ [routeKey: string]: undefined | {
5
+ [param: string]: string | number;
6
+ };
7
+ }
8
+ type RouteKeyFromParams<T> = keyof T & string;
9
+ type RouteParamsFor<T, K extends RouteKeyFromParams<T>> = T[K];
10
+ type RouteSearchParams = Record<string, string | number | boolean>;
11
+ type RouteHandlers<T> = { [K in RouteKeyFromParams<T>]: T[K] extends undefined ? string : (params: Extract<T[K], object>, searchParams?: RouteSearchParams) => string; };
12
+ type BuildRouteFn<T> = <K extends RouteKeyFromParams<T>>(key: K, ...params: T[K] extends undefined ? [] : [Extract<T[K], object>]) => string;
13
+ /** @deprecated Use RouteHandlers instead. */
14
+ type RouteBuilderFn<P> = P extends undefined ? () => string : (params: P) => string;
15
+ /** @deprecated Use RouteHandlers instead. */
16
+ type RouteRegistry<T> = { [K in RouteKeyFromParams<T>]: RouteBuilderFn<T[K]>; };
17
+ //#endregion
18
+ //#region src/routes/build.d.ts
19
+ interface RouteParamsShape {
20
+ [routeKey: string]: undefined | object;
21
+ }
22
+ /** Mirrors FE getDynamicRoute, with RouteParams typing and encodeURIComponent. */
23
+ declare function createRouteHandlers<T extends RouteParamsShape>(targets: Record<RouteKeyFromParams<T>, string>): RouteHandlers<T>;
24
+ declare function buildRouteFromHandlers<T extends RouteParamsShape>(routes: RouteHandlers<T>): BuildRouteFn<T>;
25
+ /** @deprecated Use createRouteHandlers + buildRouteFromHandlers instead. */
26
+ declare function buildRouteFromRegistry<T extends RouteParamsShape>(routes: RouteHandlers<T>): BuildRouteFn<T>;
27
+ //#endregion
28
+ //#region src/routes/search-params.d.ts
29
+ type SearchParamValue = string | number | boolean;
30
+ declare function appendSearchParams(baseUrl: string, params?: Record<string, SearchParamValue | null | undefined>): string;
31
+ //#endregion
32
+ export { type BuildRouteFn, type RouteBuilderFn, type RouteHandlers, type RouteKeyFromParams, type RouteParamsFor, type RouteParamsMap, type RouteParamsShape, type RouteRegistry, type RouteSearchParams, type SearchParamValue, appendSearchParams, buildRouteFromHandlers, buildRouteFromRegistry, createRouteHandlers };
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/routes/types.ts","../../src/routes/build.ts","../../src/routes/search-params.ts"],"mappings":";;UACiB;GACd;KAAkC;;;KAGzB,mBAAmB,WAAW;KAE9B,eAAe,GAAG,UAAU,mBAAmB,MAAM,EAAE;KAEvD,oBAAoB;KAEpB,cAAc,QACvB,KAAK,mBAAmB,KAAK,EAAE,iCAG1B,QAAQ,QAAQ,EAAE,aAClB,eAAe;KAIX,aAAa,MAAM,UAAU,mBAAmB,IAC1D,KAAK,MACF,QAAQ,EAAE,6BAA6B,QAAQ,EAAE;;KAI1C,eAAe,KAAK,sCAE3B,QAAQ;;KAGD,cAAc,QACvB,KAAK,mBAAmB,KAAK,eAAe,EAAE;;;UC5BvC;GACP;;;iBAMa,oBAAoB,UAAU,kBAC5C,SAAS,OAAO,mBAAmB,cAClC,cAAc;iBA2BD,uBAAuB,UAAU,kBAC/C,QAAQ,cAAc,KACrB,aAAa;;iBAgBA,uBAAuB,UAAU,kBAC/C,QAAQ,cAAc,KACrB,aAAa;;;KC5DJ;iBAEI,mBACd,iBACA,SAAS,eAAe"}
@@ -0,0 +1,38 @@
1
+ //#region src/routes/search-params.ts
2
+ function appendSearchParams(baseUrl, params) {
3
+ if (params === void 0 || Object.keys(params).length === 0) return baseUrl;
4
+ const [path, existingQuery] = baseUrl.split("?");
5
+ const searchParams = new URLSearchParams(existingQuery ?? "");
6
+ for (const [key, value] of Object.entries(params)) if (value !== null && value !== void 0) searchParams.set(key, String(value));
7
+ const queryString = searchParams.toString();
8
+ return queryString.length > 0 ? `${path}?${queryString}` : path ?? baseUrl;
9
+ }
10
+ //#endregion
11
+ //#region src/routes/build.ts
12
+ /** Mirrors FE getDynamicRoute, with RouteParams typing and encodeURIComponent. */
13
+ function createRouteHandlers(targets) {
14
+ return Object.fromEntries(Object.entries(targets).map(([key, value]) => {
15
+ if (!/:[^/]+/.test(value)) return [key, value];
16
+ return [key, (params, searchParams) => {
17
+ let result = value;
18
+ for (const [paramKey, paramValue] of Object.entries(params)) result = result.replaceAll(`:${paramKey}`, encodeURIComponent(String(paramValue)));
19
+ return appendSearchParams(result, searchParams);
20
+ }];
21
+ }));
22
+ }
23
+ function buildRouteFromHandlers(routes) {
24
+ const buildRoute = ((key, ...params) => {
25
+ const route = routes[key];
26
+ if (typeof route === "function") return route(params[0]);
27
+ return route;
28
+ });
29
+ return buildRoute;
30
+ }
31
+ /** @deprecated Use createRouteHandlers + buildRouteFromHandlers instead. */
32
+ function buildRouteFromRegistry(routes) {
33
+ return buildRouteFromHandlers(routes);
34
+ }
35
+ //#endregion
36
+ export { appendSearchParams, buildRouteFromHandlers, buildRouteFromRegistry, createRouteHandlers };
37
+
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/routes/search-params.ts","../../src/routes/build.ts"],"sourcesContent":["export type SearchParamValue = string | number | boolean;\n\nexport function appendSearchParams(\n baseUrl: string,\n params?: Record<string, SearchParamValue | null | undefined>\n): string {\n if (params === undefined || Object.keys(params).length === 0) {\n return baseUrl;\n }\n\n const [path, existingQuery] = baseUrl.split(\"?\");\n const searchParams = new URLSearchParams(existingQuery ?? \"\");\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== null && value !== undefined) {\n searchParams.set(key, String(value));\n }\n }\n\n const queryString = searchParams.toString();\n return queryString.length > 0 ? `${path}?${queryString}` : (path ?? baseUrl);\n}\n","import { appendSearchParams } from \"./search-params\";\nimport type { SearchParamValue } from \"./search-params\";\nimport type { BuildRouteFn, RouteHandlers, RouteKeyFromParams } from \"./types\";\n\ninterface RouteParamsShape {\n [routeKey: string]: undefined | object;\n}\n\nexport type { RouteParamsShape };\n\n/** Mirrors FE getDynamicRoute, with RouteParams typing and encodeURIComponent. */\nexport function createRouteHandlers<T extends RouteParamsShape>(\n targets: Record<RouteKeyFromParams<T>, string>\n): RouteHandlers<T> {\n return Object.fromEntries(\n Object.entries(targets).map(([key, value]) => {\n if (!/:[^/]+/.test(value)) {\n return [key, value];\n }\n\n return [\n key,\n (\n params: Extract<T[typeof key], object>,\n searchParams?: Record<string, SearchParamValue>\n ) => {\n let result = value;\n for (const [paramKey, paramValue] of Object.entries(params)) {\n result = result.replaceAll(\n `:${paramKey}`,\n encodeURIComponent(String(paramValue))\n );\n }\n return appendSearchParams(result, searchParams);\n },\n ];\n })\n ) as RouteHandlers<T>;\n}\n\nexport function buildRouteFromHandlers<T extends RouteParamsShape>(\n routes: RouteHandlers<T>\n): BuildRouteFn<T> {\n const buildRoute = (<K extends RouteKeyFromParams<T>>(\n key: K,\n ...params: T[K] extends undefined ? [] : [Extract<T[K], object>]\n ): string => {\n const route = routes[key];\n if (typeof route === \"function\") {\n return route(params[0] as Extract<T[K], object>);\n }\n return route;\n }) as BuildRouteFn<T>;\n\n return buildRoute;\n}\n\n/** @deprecated Use createRouteHandlers + buildRouteFromHandlers instead. */\nexport function buildRouteFromRegistry<T extends RouteParamsShape>(\n routes: RouteHandlers<T>\n): BuildRouteFn<T> {\n return buildRouteFromHandlers(routes);\n}\n"],"mappings":";AAEA,SAAgB,mBACd,SACA,QACQ;CACR,IAAI,WAAW,KAAA,KAAa,OAAO,KAAK,MAAM,CAAC,CAAC,WAAW,GACzD,OAAO;CAGT,MAAM,CAAC,MAAM,iBAAiB,QAAQ,MAAM,GAAG;CAC/C,MAAM,eAAe,IAAI,gBAAgB,iBAAiB,EAAE;CAE5D,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,aAAa,IAAI,KAAK,OAAO,KAAK,CAAC;CAIvC,MAAM,cAAc,aAAa,SAAS;CAC1C,OAAO,YAAY,SAAS,IAAI,GAAG,KAAK,GAAG,gBAAiB,QAAQ;AACtE;;;;ACVA,SAAgB,oBACd,SACkB;CAClB,OAAO,OAAO,YACZ,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;EAC5C,IAAI,CAAC,SAAS,KAAK,KAAK,GACtB,OAAO,CAAC,KAAK,KAAK;EAGpB,OAAO,CACL,MAEE,QACA,iBACG;GACH,IAAI,SAAS;GACb,KAAK,MAAM,CAAC,UAAU,eAAe,OAAO,QAAQ,MAAM,GACxD,SAAS,OAAO,WACd,IAAI,YACJ,mBAAmB,OAAO,UAAU,CAAC,CACvC;GAEF,OAAO,mBAAmB,QAAQ,YAAY;EAChD,CACF;CACF,CAAC,CACH;AACF;AAEA,SAAgB,uBACd,QACiB;CACjB,MAAM,eACJ,KACA,GAAG,WACQ;EACX,MAAM,QAAQ,OAAO;EACrB,IAAI,OAAO,UAAU,YACnB,OAAO,MAAM,OAAO,EAA2B;EAEjD,OAAO;CACT;CAEA,OAAO;AACT;;AAGA,SAAgB,uBACd,QACiB;CACjB,OAAO,uBAAuB,MAAM;AACtC"}
@@ -0,0 +1,11 @@
1
+ //#region src/http/validate.d.ts
2
+ type ResponseValidator<T> = (value: unknown) => T;
3
+ //#endregion
4
+ //#region src/validation/zod.d.ts
5
+ interface ZodLikeSchema<T> {
6
+ parse(value: unknown): T;
7
+ }
8
+ declare function createZodValidator<T>(schema: ZodLikeSchema<T>): ResponseValidator<T>;
9
+ //#endregion
10
+ export { type ResponseValidator, ZodLikeSchema, createZodValidator };
11
+ //# sourceMappingURL=zod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.d.ts","names":[],"sources":["../../src/http/validate.ts","../../src/validation/zod.ts"],"mappings":";KAAY,kBAAkB,MAAM,mBAAmB;;;UCEtC,cAAc;EAC7B,MAAM,iBAAiB;;iBAGT,mBAAmB,GACjC,QAAQ,cAAc,KACrB,kBAAkB"}
@@ -0,0 +1,8 @@
1
+ //#region src/validation/zod.ts
2
+ function createZodValidator(schema) {
3
+ return (value) => schema.parse(value);
4
+ }
5
+ //#endregion
6
+ export { createZodValidator };
7
+
8
+ //# sourceMappingURL=zod.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zod.js","names":[],"sources":["../../src/validation/zod.ts"],"sourcesContent":["import type { ResponseValidator } from \"../http/validate\";\n\nexport interface ZodLikeSchema<T> {\n parse(value: unknown): T;\n}\n\nexport function createZodValidator<T>(\n schema: ZodLikeSchema<T>\n): ResponseValidator<T> {\n return (value: unknown) => schema.parse(value);\n}\n\nexport type { ResponseValidator } from \"../http/validate\";\n"],"mappings":";AAMA,SAAgB,mBACd,QACsB;CACtB,QAAQ,UAAmB,OAAO,MAAM,KAAK;AAC/C"}