orval 8.13.0 → 8.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-yIkhToq8.mjs","names":["validateSpec","isNullish","fs","nodePath","path","pkg.name","pkg.version","version","fs"],"sources":["../package.json","../src/client.ts","../src/api.ts","../src/import-open-api.ts","../src/import-specs.ts","../src/formatters/prettier.ts","../src/utils/execute-hook.ts","../src/utils/package-json.ts","../src/utils/tsconfig.ts","../src/utils/options.ts","../src/utils/watcher.ts","../src/reusable-schemas.ts","../src/write-zod-specs.ts","../src/write-specs.ts","../src/generate-spec.ts","../src/utils/config.ts"],"sourcesContent":["","import angular from '@orval/angular';\nimport axios from '@orval/axios';\nimport type {\n AngularOptions,\n ClientFileBuilder,\n ClientGeneratorsBuilder,\n ClientMockGeneratorBuilder,\n ContextSpec,\n GeneratorClientFooter,\n GeneratorClientHeader,\n GeneratorClientImports,\n GeneratorClients,\n GeneratorClientTitle,\n GeneratorOperations,\n GeneratorOptions,\n GeneratorVerbOptions,\n GeneratorVerbsOptions,\n NormalizedOutputOptions,\n OutputClientFunc,\n} from '@orval/core';\nimport {\n asyncReduce,\n generateDependencyImports,\n getBaseUrlRuntimeImports,\n isFunction,\n logWarning,\n OutputClient,\n OutputMockType,\n pascal,\n} from '@orval/core';\nimport effect from '@orval/effect';\nimport fetchClient from '@orval/fetch';\nimport hono from '@orval/hono';\nimport mcp from '@orval/mcp';\nimport * as mock from '@orval/mock';\nimport query from '@orval/query';\nimport solidStart from '@orval/solid-start';\nimport swr from '@orval/swr';\nimport zod from '@orval/zod';\n\nconst DEFAULT_CLIENT = OutputClient.AXIOS;\n\nconst getGeneratorClient = (\n outputClient: OutputClient | OutputClientFunc,\n output: NormalizedOutputOptions,\n) => {\n const angularBuilder = angular() as (\n options?: AngularOptions,\n ) => ClientGeneratorsBuilder;\n const GENERATOR_CLIENT: GeneratorClients = {\n axios: axios({ type: 'axios' })(),\n 'axios-functions': axios({ type: 'axios-functions' })(),\n angular: angularBuilder(output.override.angular),\n 'angular-query': query({ output, type: 'angular-query' })(),\n 'react-query': query({ output, type: 'react-query' })(),\n 'solid-start': solidStart()(),\n 'solid-query': query({ output, type: 'solid-query' })(),\n 'svelte-query': query({ output, type: 'svelte-query' })(),\n 'vue-query': query({ output, type: 'vue-query' })(),\n swr: swr()(),\n zod: zod()(),\n effect: effect()(),\n hono: hono()(),\n fetch: fetchClient()(),\n mcp: mcp()(),\n };\n\n const generator = isFunction(outputClient)\n ? outputClient(GENERATOR_CLIENT)\n : GENERATOR_CLIENT[outputClient];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- defensive guard for custom OutputClientFunc returning unexpected values\n if (!generator) {\n throw new Error(\n `Unknown output client provided to getGeneratorClient: ${String(outputClient)}`,\n );\n }\n\n return generator;\n};\n\nexport const generateClientImports: GeneratorClientImports = ({\n client,\n implementation,\n imports,\n projectName,\n hasSchemaDir,\n isAllowSyntheticDefaultImports,\n hasGlobalMutator,\n hasTagsMutator,\n hasParamsSerializerOptions,\n packageJson,\n output,\n}) => {\n const { dependencies } = getGeneratorClient(client, output);\n return generateDependencyImports(\n implementation,\n dependencies\n ? [\n ...dependencies(\n hasGlobalMutator,\n hasParamsSerializerOptions,\n packageJson,\n output.httpClient,\n hasTagsMutator,\n output.override,\n ),\n ...imports,\n ]\n : (imports as Parameters<typeof generateDependencyImports>[1]),\n projectName,\n hasSchemaDir,\n isAllowSyntheticDefaultImports,\n );\n};\n\nexport const generateClientHeader: GeneratorClientHeader = ({\n outputClient = DEFAULT_CLIENT,\n isRequestOptions,\n isGlobalMutator,\n isMutator,\n provideIn,\n hasAwaitedType,\n titles,\n output,\n verbOptions,\n tag,\n isDefaultTagBucket,\n clientImplementation,\n}) => {\n const { header } = getGeneratorClient(outputClient, output);\n\n return {\n implementation: header\n ? header({\n title: titles.implementation,\n isRequestOptions,\n isGlobalMutator,\n isMutator,\n provideIn,\n hasAwaitedType,\n output,\n verbOptions,\n tag,\n isDefaultTagBucket,\n clientImplementation,\n })\n : '',\n implementationMock: `export const ${titles.implementationMock} = () => [\\n`,\n };\n};\n\nexport const generateClientFooter: GeneratorClientFooter = ({\n outputClient,\n operationNames,\n hasMutator,\n hasAwaitedType,\n titles,\n output,\n}) => {\n const { footer } = getGeneratorClient(outputClient, output);\n\n if (!footer) {\n return {\n implementation: '',\n implementationMock: `\\n]\\n`,\n };\n }\n\n let implementation: string;\n try {\n if (isFunction(outputClient)) {\n implementation = (\n footer as unknown as (operationNames: string[]) => string\n )(operationNames);\n // being here means that the previous call worked\n logWarning(\n '⚠️ Passing an array of strings for operations names to the footer function is deprecated and will be removed in a future major release. Please pass them in an object instead: { operationNames: string[] }.',\n );\n } else {\n implementation = footer({\n operationNames,\n title: titles.implementation,\n hasMutator,\n hasAwaitedType,\n });\n }\n } catch {\n implementation = footer({\n operationNames,\n title: titles.implementation,\n hasMutator,\n hasAwaitedType,\n });\n }\n\n return {\n implementation,\n implementationMock: `]\\n`,\n };\n};\n\nexport const generateClientTitle: GeneratorClientTitle = ({\n outputClient = DEFAULT_CLIENT,\n title,\n customTitleFunc,\n output,\n}) => {\n const { title: generatorTitle } = getGeneratorClient(outputClient, output);\n\n if (!generatorTitle) {\n return {\n implementation: '',\n implementationMock: `get${pascal(title)}Mock`,\n };\n }\n\n if (customTitleFunc) {\n const customTitle = customTitleFunc(title);\n return {\n implementation: generatorTitle(customTitle),\n implementationMock: `get${pascal(customTitle)}Mock`,\n };\n }\n return {\n implementation: generatorTitle(title),\n implementationMock: `get${pascal(title)}Mock`,\n };\n};\n\n/**\n * Invokes the underlying mock generator (msw, faker, or a user-provided\n * ClientMockBuilder) for a single generator entry. Returns the standard\n * `ClientMockGeneratorBuilder` shape (function/handler/handlerName +\n * imports) regardless of which generator handled it.\n */\nconst invokeMockGenerator = (\n verbOption: GeneratorVerbOptions,\n options: GeneratorOptions,\n entry: NonNullable<NormalizedOutputOptions['mock']['generators'][number]>,\n): ClientMockGeneratorBuilder => {\n if (isFunction(entry)) {\n return entry(verbOption, {\n ...options,\n mock: entry,\n });\n }\n return mock.generateMock(verbOption, {\n ...options,\n mock: entry,\n });\n};\n\nexport const generateOperations = (\n outputClient: OutputClient | OutputClientFunc = DEFAULT_CLIENT,\n verbsOptions: GeneratorVerbsOptions,\n options: GeneratorOptions,\n output: NormalizedOutputOptions,\n): Promise<GeneratorOperations> => {\n const baseUrlImports = getBaseUrlRuntimeImports(output.baseUrl);\n\n return asyncReduce(\n verbsOptions,\n async (acc, verbOption) => {\n const { client: generatorClient } = getGeneratorClient(\n outputClient,\n output,\n );\n const client = await generatorClient(\n verbOption,\n options,\n outputClient,\n output,\n );\n\n if (!client.implementation) {\n return acc;\n }\n\n // Run every configured mock generator for this operation. Each entry\n // contributes its own GeneratorMockOutputFull so writers can split the\n // results across per-type output files (e.g. `.msw.ts` + `.faker.ts`).\n // Function-form entries (ClientMockBuilder) inherit the historical\n // `msw` file extension and are treated as msw outputs for downstream\n // bookkeeping.\n const mockOutputs = output.mock.generators\n .filter((entry) => {\n // A faker entry with `operationResponses: false` opts out of the\n // per-operation `get<Op>ResponseMock` factories. The consolidated\n // schemas file (when `schemas: true`) is emitted separately and is\n // unaffected by this filter.\n if (\n !isFunction(entry) &&\n entry.type === OutputMockType.FAKER &&\n entry.operationResponses === false\n ) {\n return false;\n }\n return true;\n })\n .map((entry) => {\n const generated = invokeMockGenerator(verbOption, options, entry);\n return {\n type: isFunction(entry) ? OutputMockType.MSW : entry.type,\n implementation: generated.implementation,\n imports: generated.imports,\n };\n });\n\n const hasImplementation = client.implementation.trim().length > 0;\n const preferredOperationKey = verbOption.operationName;\n const baseOperationKey = verbOption.operationId\n ? `${verbOption.operationId}::${verbOption.operationName}`\n : verbOption.operationName;\n let operationKey = Object.hasOwn(acc, preferredOperationKey)\n ? baseOperationKey\n : preferredOperationKey;\n let collisionIndex = 1;\n\n while (Object.hasOwn(acc, operationKey)) {\n collisionIndex += 1;\n operationKey = `${baseOperationKey}::${collisionIndex}`;\n }\n\n acc[operationKey] = {\n implementation: hasImplementation\n ? (client.docComment ?? verbOption.doc) + client.implementation\n : client.implementation,\n imports: [...baseUrlImports, ...client.imports],\n mockOutputs,\n tags: verbOption.tags,\n mutator: verbOption.mutator,\n clientMutators: client.mutators,\n formData: verbOption.formData,\n formUrlEncoded: verbOption.formUrlEncoded,\n paramsSerializer: verbOption.paramsSerializer,\n paramsFilter: verbOption.paramsFilter,\n operationName: verbOption.operationName,\n fetchReviver: verbOption.fetchReviver,\n };\n\n return acc;\n },\n {} as GeneratorOperations,\n );\n};\n\nexport const generateExtraFiles = (\n outputClient: OutputClient | OutputClientFunc = DEFAULT_CLIENT,\n verbsOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n): Promise<ClientFileBuilder[]> => {\n const { extraFiles: generateExtraFiles } = getGeneratorClient(\n outputClient,\n output,\n );\n\n if (!generateExtraFiles) {\n return Promise.resolve([]);\n }\n\n return generateExtraFiles(verbsOptions, output, context);\n};\n","import {\n asyncReduce,\n type ContextSpec,\n generateVerbsOptions,\n type GeneratorApiBuilder,\n type GeneratorApiOperations,\n type GeneratorSchema,\n getFullRoute,\n getRoute,\n GetterPropType,\n isReference,\n type NormalizedInputOptions,\n type NormalizedOutputOptions,\n type OpenApiPathItemObject,\n resolveRef,\n} from '@orval/core';\nimport { generateMockImports } from '@orval/mock';\n\nimport {\n generateClientFooter,\n generateClientHeader,\n generateClientImports,\n generateClientTitle,\n generateExtraFiles,\n generateOperations,\n} from './client';\n\nexport async function getApiBuilder({\n input,\n output,\n context,\n}: {\n input: NormalizedInputOptions;\n output: NormalizedOutputOptions;\n context: ContextSpec;\n}): Promise<GeneratorApiBuilder> {\n const api = await asyncReduce(\n Object.entries(context.spec.paths ?? {}),\n async (acc, [pathRoute, verbs]) => {\n if (!verbs) {\n return acc;\n }\n\n const route = getRoute(pathRoute);\n\n let resolvedVerbs: OpenApiPathItemObject = verbs;\n\n if (isReference(verbs)) {\n const { schema }: { schema: OpenApiPathItemObject } = resolveRef(\n verbs,\n context,\n );\n\n resolvedVerbs = schema;\n }\n\n let verbsOptions = await generateVerbsOptions({\n verbs: resolvedVerbs,\n input,\n output,\n route,\n pathRoute,\n context,\n });\n\n // GitHub #564 check if we want to exclude deprecated operations\n if (output.override.useDeprecatedOperations === false) {\n verbsOptions = verbsOptions.filter((verb) => {\n return !verb.deprecated;\n });\n }\n\n const schemas: GeneratorSchema[] = [];\n for (const {\n queryParams,\n headers,\n body,\n response,\n props,\n } of verbsOptions) {\n schemas.push(\n ...props.flatMap((param) =>\n param.type === GetterPropType.NAMED_PATH_PARAMS ? param.schema : [],\n ),\n );\n if (queryParams) {\n schemas.push(queryParams.schema, ...queryParams.deps);\n }\n if (headers) {\n schemas.push(headers.schema, ...headers.deps);\n }\n\n schemas.push(...body.schemas, ...response.schemas);\n }\n\n const fullRoute = getFullRoute(\n route,\n resolvedVerbs.servers ?? context.spec.servers,\n output.baseUrl,\n );\n if (!output.target) {\n throw new Error('Output does not have a target');\n }\n const pathOperations = await generateOperations(\n output.client,\n verbsOptions,\n {\n route: fullRoute,\n pathRoute,\n override: output.override,\n context,\n output: output.target,\n },\n output,\n );\n\n for (const verbOption of verbsOptions) {\n acc.verbOptions[verbOption.operationId] = verbOption;\n }\n acc.schemas.push(...schemas);\n acc.operations = { ...acc.operations, ...pathOperations };\n\n return acc;\n },\n {\n operations: {},\n verbOptions: {},\n schemas: [],\n } as GeneratorApiOperations,\n );\n\n const extraFiles = await generateExtraFiles(\n output.client,\n api.verbOptions,\n output,\n context,\n );\n\n return {\n operations: api.operations,\n schemas: api.schemas,\n verbOptions: api.verbOptions,\n title: generateClientTitle,\n header: generateClientHeader,\n footer: generateClientFooter,\n imports: generateClientImports,\n importsMock: generateMockImports,\n extraFiles,\n };\n}\n","import {\n collectReferencedComponents,\n type ContextSpec,\n generateComponentDefinition,\n generateParameterDefinition,\n generateSchemasDefinition,\n type ImportOpenApi,\n type InputOptions,\n type NormalizedOutputOptions,\n type OpenApiComponentsObject,\n type OpenApiDocument,\n type WriteSpecBuilder,\n} from '@orval/core';\nimport { pick } from 'remeda';\n\nimport { getApiBuilder } from './api';\n\nfunction filterSpecComponents(\n spec: OpenApiDocument,\n input: InputOptions,\n): OpenApiDocument {\n const filters = input.filters;\n if (!filters?.tags || filters.schemas) return spec;\n\n const referenced = collectReferencedComponents(\n spec,\n filters.tags,\n filters.mode,\n );\n\n return {\n ...spec,\n components: {\n ...spec.components,\n schemas: pick(spec.components?.schemas ?? {}, referenced.schemas),\n responses: pick(spec.components?.responses ?? {}, referenced.responses),\n parameters: pick(\n spec.components?.parameters ?? {},\n referenced.parameters,\n ),\n requestBodies: pick(\n spec.components?.requestBodies ?? {},\n referenced.requestBodies,\n ),\n },\n };\n}\n\nexport async function importOpenApi({\n spec,\n input,\n output,\n target,\n workspace,\n projectName,\n}: ImportOpenApi): Promise<WriteSpecBuilder> {\n // The transformer has already been applied (pre-validation) in `resolveSpec`.\n const filteredSpec = filterSpecComponents(spec, input);\n\n const schemas = getApiSchemas({\n input,\n output,\n target,\n workspace,\n spec: filteredSpec,\n });\n\n const api = await getApiBuilder({\n input,\n output,\n context: {\n projectName,\n target,\n workspace,\n spec: filteredSpec,\n output,\n } satisfies ContextSpec,\n });\n\n return {\n ...api,\n schemas: [...schemas, ...api.schemas],\n target,\n // a valid spec will have info\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n info: filteredSpec.info!,\n spec: filteredSpec,\n };\n}\n\ninterface GetApiSchemasOptions {\n input: InputOptions;\n output: NormalizedOutputOptions;\n workspace: string;\n target: string;\n spec: OpenApiDocument;\n}\n\nfunction getApiSchemas({\n input,\n output,\n target,\n workspace,\n spec,\n}: GetApiSchemasOptions) {\n const context: ContextSpec = {\n target,\n workspace,\n spec,\n output,\n };\n\n const schemaDefinition = generateSchemasDefinition(\n spec.components?.schemas,\n context,\n output.override.components.schemas.suffix,\n input.filters,\n );\n\n const responseDefinition = generateComponentDefinition(\n spec.components?.responses,\n context,\n output.override.components.responses.suffix,\n );\n\n const swaggerResponseDefinition = generateComponentDefinition(\n 'responses' in spec\n ? (spec as { responses?: OpenApiComponentsObject['responses'] }).responses\n : undefined,\n context,\n '',\n );\n\n const bodyDefinition = generateComponentDefinition(\n spec.components?.requestBodies,\n context,\n output.override.components.requestBodies.suffix,\n );\n\n const parameters = generateParameterDefinition(\n spec.components?.parameters,\n context,\n output.override.components.parameters.suffix,\n );\n\n const schemas = [\n ...schemaDefinition,\n ...responseDefinition,\n ...swaggerResponseDefinition,\n ...bodyDefinition,\n ...parameters,\n ];\n\n return schemas;\n}\n","import {\n dynamicImport,\n isObject,\n isString,\n logWarning,\n type NormalizedOptions,\n type OpenApiDocument,\n type OverrideInput,\n type WriteSpecBuilder,\n} from '@orval/core';\nimport { bundle } from '@scalar/json-magic/bundle';\nimport {\n fetchUrls,\n parseJson,\n parseYaml,\n readFiles,\n} from '@scalar/json-magic/bundle/plugins/node';\nimport { upgrade, validate as validateSpec } from '@scalar/openapi-parser';\nimport { isNullish } from 'remeda';\n\nimport { importOpenApi } from './import-open-api';\n\ninterface ResolveSpecOptions {\n parserOptions?: {\n headers?: {\n domains: string[];\n headers: Record<string, string>;\n }[];\n };\n transformer?: OverrideInput['transformer'];\n workspace: string;\n unsafeDisableValidation?: boolean;\n}\n\nasync function resolveSpec(\n input: string | Record<string, unknown>,\n {\n parserOptions,\n transformer,\n workspace,\n unsafeDisableValidation = false,\n }: ResolveSpecOptions,\n): Promise<OpenApiDocument> {\n const data = await bundle(input, {\n plugins: [\n readFiles(),\n fetchUrls({\n headers: parserOptions?.headers,\n }),\n parseJson(),\n parseYaml(),\n ],\n treeShake: false,\n });\n const dereferencedData = dereferenceExternalRef(\n data as Record<string, unknown>,\n );\n\n // Apply user-provided transformer before validation so users can repair\n // malformed specs in-place. The transformer is typed against\n // `OpenApiDocument`, but we pass the raw bundled object — repairing a spec\n // necessarily means it does not yet conform to the type at call time.\n const transformedData = transformer\n ? await applyInputTransformer(dereferencedData, transformer, workspace)\n : dereferencedData;\n\n if (unsafeDisableValidation) {\n logWarning(\n `🚨 OpenAPI spec validation is disabled.\\n` +\n ` Code generation with invalid specs is not guaranteed to work and may break in minor updates.\\n` +\n ` Bug reports with validation disabled will not be accepted.`,\n );\n } else {\n validateComponentKeys(transformedData);\n\n const { valid, errors } = await validateSpec(transformedData);\n if (!valid) {\n throw new Error(\n `OpenAPI spec validation failed:\\n${JSON.stringify(errors, undefined, 2)}`,\n );\n }\n }\n\n const { specification } = upgrade(transformedData);\n\n // upgrade() returns @scalar/openapi-types/3.1 Document (openapi: string);\n // OpenApiDocument uses the legacy OpenAPIV3_1 namespace (openapi version literals).\n return specification as OpenApiDocument;\n}\n\nasync function applyInputTransformer(\n data: Record<string, unknown>,\n transformer: NonNullable<OverrideInput['transformer']>,\n workspace: string,\n): Promise<Record<string, unknown>> {\n const transformerFn = await dynamicImport(transformer, workspace);\n const result: unknown = await transformerFn(\n data as unknown as OpenApiDocument,\n );\n if (!isObject(result)) {\n const source = isString(transformer)\n ? transformer\n : transformerFn.name || '<inline function>';\n throw new Error(\n `input.override.transformer must return an OpenAPI document object; ` +\n `got ${result === undefined ? 'undefined' : typeof result} from ${source}. ` +\n `Ensure your transformer returns the (possibly modified) spec.`,\n );\n }\n return result;\n}\n\nexport async function importSpecs(\n workspace: string,\n options: NormalizedOptions,\n projectName?: string,\n): Promise<WriteSpecBuilder> {\n const { input, output } = options;\n\n const spec = await resolveSpec(input.target, {\n parserOptions: input.parserOptions,\n transformer: input.override.transformer,\n workspace,\n unsafeDisableValidation: input.unsafeDisableValidation,\n });\n\n return importOpenApi({\n spec,\n input,\n output,\n target: isString(input.target) ? input.target : workspace,\n workspace,\n projectName,\n });\n}\n\nconst COMPONENT_KEY_PATTERN = /^[a-zA-Z0-9.\\-_]+$/;\n\nconst COMPONENT_SECTIONS = [\n 'schemas',\n 'responses',\n 'parameters',\n 'examples',\n 'requestBodies',\n 'headers',\n 'securitySchemes',\n 'links',\n 'callbacks',\n 'pathItems', // OAS 3.1.0+\n] as const;\n\n/**\n * Validate that all component keys conform to the OAS regex: ^[a-zA-Z0-9.\\-_]+$\n * @see https://spec.openapis.org/oas/v3.0.3.html#fixed-fields-5\n * @see https://spec.openapis.org/oas/v3.1.0#fixed-fields-5\n */\nexport function validateComponentKeys(data: Record<string, unknown>): void {\n const components = data.components;\n if (!isObject(components)) return;\n\n const invalidKeys: string[] = [];\n\n for (const section of COMPONENT_SECTIONS) {\n const sectionObj = components[section];\n if (!isObject(sectionObj)) continue;\n\n for (const key of Object.keys(sectionObj)) {\n if (!COMPONENT_KEY_PATTERN.test(key)) {\n invalidKeys.push(`components.${section}.${key}`);\n }\n }\n }\n\n if (invalidKeys.length > 0) {\n throw new Error(\n `Invalid component key${invalidKeys.length > 1 ? 's' : ''} found. ` +\n `OpenAPI component keys must match the pattern ${COMPONENT_KEY_PATTERN} ` +\n `(non-ASCII characters are not allowed per the spec).\\n` +\n ` See: https://spec.openapis.org/oas/v3.0.3.html#components-object\\n` +\n ` Invalid keys:\\n` +\n invalidKeys.map((k) => ` - ${k}`).join('\\n'),\n );\n }\n}\n\n/**\n * The plugins from `@scalar/json-magic` does not dereference $ref.\n * Instead it fetches them and puts them under x-ext, and changes the $ref to point to #x-ext/<name>.\n * This function:\n * 1. Merges external schemas into main spec's components.schemas (with collision handling)\n * 2. Replaces x-ext refs with standard component refs or inlined content\n */\nexport function dereferenceExternalRef(\n data: Record<string, unknown>,\n): Record<string, unknown> {\n const extensions = (data['x-ext'] ?? {}) as Record<string, unknown>;\n\n // Step 1: Merge external schemas into main spec with collision handling\n const schemaNameMappings = mergeExternalSchemas(data, extensions);\n\n // Step 2: Replace all x-ext refs throughout the document\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(data)) {\n if (key !== 'x-ext') {\n result[key] = replaceXExtRefs(value, extensions, schemaNameMappings);\n }\n }\n\n return result;\n}\n\n/**\n * Merge external document schemas into main spec's components.schemas\n * Returns mapping of original schema names to final names (with suffixes for collisions)\n */\nfunction mergeExternalSchemas(\n data: Record<string, unknown>,\n extensions: Record<string, unknown>,\n): Record<string, Record<string, string>> {\n const schemaNameMappings: Record<string, Record<string, string>> = {};\n\n if (Object.keys(extensions).length === 0) return schemaNameMappings;\n\n data.components ??= {};\n const mainComponents = data.components as Record<string, unknown>;\n mainComponents.schemas ??= {};\n const mainSchemas = mainComponents.schemas as Record<string, unknown>;\n\n // Merge schemas from each external doc\n // Collision handling:\n // - If schema already exists in main spec, add x-ext key as suffix (e.g., User -> User_external1)\n // - x-ext refs in main spec get replaced by actual schema from external doc\n for (const [extKey, extDoc] of Object.entries(extensions)) {\n schemaNameMappings[extKey] = {};\n\n if (isObject(extDoc) && 'components' in extDoc) {\n const extComponents = extDoc.components as Record<string, unknown>;\n if (isObject(extComponents) && 'schemas' in extComponents) {\n const extSchemas = extComponents.schemas as Record<string, unknown>;\n for (const [schemaName, schema] of Object.entries(extSchemas)) {\n // Check if main schema is just an x-ext ref - if so, replace it without suffix\n const existingSchema = mainSchemas[schemaName];\n const isXExtRef =\n isObject(existingSchema) &&\n '$ref' in existingSchema &&\n isString(existingSchema.$ref) &&\n existingSchema.$ref.startsWith('#/x-ext/');\n\n let finalSchemaName = schemaName;\n\n if (schemaName in mainSchemas && !isXExtRef) {\n // Collision: add suffix to external schema\n const suffix = extKey.replaceAll(/[^a-zA-Z0-9]/g, '_');\n finalSchemaName = `${schemaName}_${suffix}`;\n schemaNameMappings[extKey][schemaName] = finalSchemaName;\n } else {\n // No collision or replacing x-ext ref\n schemaNameMappings[extKey][schemaName] = schemaName;\n }\n\n mainSchemas[finalSchemaName] = scrubUnwantedKeys(schema);\n }\n }\n }\n }\n\n // Apply internal ref updates to all schemas from external docs\n for (const [extKey, mapping] of Object.entries(schemaNameMappings)) {\n for (const [, finalName] of Object.entries(mapping)) {\n const schema = mainSchemas[finalName];\n if (schema) {\n mainSchemas[finalName] = updateInternalRefs(\n schema,\n extKey,\n schemaNameMappings,\n ) as Record<string, unknown>;\n }\n }\n }\n\n return schemaNameMappings;\n}\n\n/**\n * Remove unwanted keys like $schema and $id from objects\n */\nfunction scrubUnwantedKeys(obj: unknown): unknown {\n const UNWANTED_KEYS = new Set(['$schema', '$id']);\n\n if (obj === null || obj === undefined) return obj;\n if (Array.isArray(obj)) return obj.map((x) => scrubUnwantedKeys(x));\n if (isObject(obj)) {\n const rec = obj;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(rec)) {\n if (UNWANTED_KEYS.has(k)) continue;\n out[k] = scrubUnwantedKeys(v);\n }\n return out;\n }\n return obj;\n}\n\n/**\n * Update internal refs within an external schema to use suffixed names\n */\nfunction updateInternalRefs(\n obj: unknown,\n extKey: string,\n schemaNameMappings: Record<string, Record<string, string>>,\n): unknown {\n if (obj === null || obj === undefined) return obj;\n\n if (Array.isArray(obj)) {\n return obj.map((element) =>\n updateInternalRefs(element, extKey, schemaNameMappings),\n );\n }\n\n if (isObject(obj)) {\n const record = obj;\n\n // Check if this is a $ref to #/components/schemas/...\n if ('$ref' in record && isString(record.$ref)) {\n const refValue = record.$ref;\n if (refValue.startsWith('#/components/schemas/')) {\n const schemaName = refValue.replace('#/components/schemas/', '');\n // If this schema was mapped to a suffixed name, update the ref\n const mappedName = schemaNameMappings[extKey][schemaName];\n if (mappedName) {\n return {\n $ref: `#/components/schemas/${mappedName}`,\n };\n }\n }\n }\n\n // Recursively process all properties\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = updateInternalRefs(value, extKey, schemaNameMappings);\n }\n return result;\n }\n\n return obj;\n}\n\n/**\n * Decode a single JSON Pointer reference token taken from an x-ext `$ref`.\n *\n * The token carries two layers of encoding: it sits in a URI fragment, so it\n * may be percent-encoded (e.g. `%7B` for `{` in templated paths), and it is a\n * JSON Pointer token, so `~1`/`~0` stand for `/`/`~` (RFC 6901). Percent-\n * encoding is the outer layer and is removed first; a malformed sequence is\n * left as-is rather than throwing. Without this, tokens such as `~1pets`\n * never match the real `/pets` key and the external `$ref` fails to resolve.\n */\nfunction decodeRefToken(token: string): string {\n let decoded = token;\n try {\n decoded = decodeURIComponent(token);\n } catch {\n // Malformed percent-encoding — fall back to the raw token.\n }\n return decoded.replaceAll('~1', '/').replaceAll('~0', '~');\n}\n\n/**\n * Replace x-ext refs with standard component refs, or inline the content.\n * `inliningRefs` tracks the inline chain to break cycles in recursive\n * external schemas that aren't under `components.schemas` (#1642).\n */\nfunction replaceXExtRefs(\n obj: unknown,\n extensions: Record<string, unknown>,\n schemaNameMappings: Record<string, Record<string, string>>,\n inliningRefs = new Set<string>(),\n): unknown {\n if (isNullish(obj)) return obj;\n\n if (Array.isArray(obj)) {\n return obj.map((element) =>\n replaceXExtRefs(element, extensions, schemaNameMappings, inliningRefs),\n );\n }\n\n if (isObject(obj)) {\n const record = obj;\n\n // Check if this object is a $ref to x-ext\n if ('$ref' in record && isString(record.$ref)) {\n const refValue = record.$ref;\n if (refValue.startsWith('#/x-ext/')) {\n // Parse the x-ext ref\n const pathStr = refValue.replace('#/x-ext/', '');\n const parts = pathStr.split('/');\n const extKey = parts.shift();\n\n if (extKey) {\n // Check if this is a ref to components/schemas - if so, replace with standard ref\n if (\n parts.length >= 3 &&\n parts[0] === 'components' &&\n parts[1] === 'schemas'\n ) {\n const schemaName = parts.slice(2).join('/');\n // Use the mapped name (which may include suffix for collisions)\n const finalName =\n schemaNameMappings[extKey][schemaName] || schemaName;\n return { $ref: `#/components/schemas/${finalName}` };\n }\n\n // Otherwise inline the content; break cycles with `{}`.\n if (inliningRefs.has(refValue)) {\n logWarning(\n `Detected a circular external $ref while inlining \"${refValue}\". ` +\n `Replacing with an empty schema to avoid infinite recursion. ` +\n `Move the schema under \"components.schemas\" in its source file ` +\n `or pre-bundle the spec to keep the recursion intact.`,\n );\n return {};\n }\n\n const extDoc = extensions[extKey];\n let refObj: unknown = extDoc;\n for (const rawPart of parts) {\n const p = decodeRefToken(rawPart);\n if (\n refObj &&\n (isObject(refObj) || Array.isArray(refObj)) &&\n p in (refObj as Record<string, unknown>)\n ) {\n refObj = (refObj as Record<string, unknown>)[p];\n } else {\n refObj = undefined;\n break;\n }\n }\n\n if (refObj) {\n const cleaned = scrubUnwantedKeys(refObj);\n const nextInlining = new Set(inliningRefs);\n nextInlining.add(refValue);\n return replaceXExtRefs(\n cleaned,\n extensions,\n schemaNameMappings,\n nextInlining,\n );\n }\n }\n }\n }\n\n // Recursively process all properties\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = replaceXExtRefs(\n value,\n extensions,\n schemaNameMappings,\n inliningRefs,\n );\n }\n return result;\n }\n\n return obj;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { logWarning } from '@orval/core';\nimport { execa } from 'execa';\n\n/**\n * Format files with prettier.\n * Tries the programmatic API first (project dependency),\n * then falls back to the globally installed CLI.\n */\nexport async function formatWithPrettier(\n paths: string[],\n projectTitle?: string,\n): Promise<void> {\n const prettier = await tryImportPrettier();\n\n if (prettier) {\n const filePaths = [...new Set(await collectFilePaths(paths))];\n if (filePaths.length === 0) {\n return;\n }\n\n const config = (await prettier.resolveConfig(filePaths[0])) ?? {};\n await Promise.all(\n filePaths.map(async (filePath) => {\n try {\n const content = await fs.readFile(filePath, 'utf8');\n const formatted = await prettier.format(content, {\n ...config,\n // options.filepath can be specified for Prettier to infer the parser from the file extension\n filepath: filePath,\n });\n await fs.writeFile(filePath, formatted);\n } catch (error) {\n if (isMissingFileError(error)) {\n return;\n }\n\n if (error instanceof Error) {\n // prettier currently doesn't export UndefinedParserError, so having to do it the crude way\n if (error.name === 'UndefinedParserError') {\n // skip files with unsupported parsers\n // https://prettier.io/docs/options#parser\n } else {\n logWarning(\n `⚠️ ${projectTitle ? `${projectTitle} - ` : ''}Failed to format file ${filePath}: ${error.toString()}`,\n );\n }\n } else {\n logWarning(\n `⚠️ ${projectTitle ? `${projectTitle} - ` : ''}Failed to format file ${filePath}: unknown error`,\n );\n }\n }\n }),\n );\n\n return;\n }\n\n // fallback to globally installed prettier\n try {\n await execa('prettier', ['--write', ...paths]);\n } catch {\n logWarning(\n `⚠️ ${projectTitle ? `${projectTitle} - ` : ''}prettier not found. Install it as a project dependency or globally.`,\n );\n }\n}\n\nfunction isMissingFileError(error: unknown): error is NodeJS.ErrnoException {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n error.code === 'ENOENT'\n );\n}\n\n/**\n * Try to import prettier from the project's dependencies.\n * Returns undefined if prettier is not installed.\n */\nasync function tryImportPrettier() {\n try {\n return await import('prettier');\n } catch {\n return;\n }\n}\n\n/**\n * Recursively collect absolute file paths from a mix of files and directories.\n */\nasync function collectFilePaths(paths: string[]): Promise<string[]> {\n const results: string[] = [];\n\n for (const p of paths) {\n const absolute = path.resolve(p);\n try {\n const stat = await fs.stat(absolute);\n if (stat.isFile()) {\n results.push(absolute);\n } else if (stat.isDirectory()) {\n const entries = await fs.readdir(absolute);\n const subPaths = entries.map((entry) => path.join(absolute, entry));\n const subFiles = await collectFilePaths(subPaths);\n results.push(...subFiles);\n }\n } catch {\n // Skip paths that don't exist or can't be accessed\n }\n }\n\n return results;\n}\n","import { styleText } from 'node:util';\n\nimport {\n type Hook,\n type HookOption,\n isFunction,\n isObject,\n isString,\n log,\n logError,\n type NormalizedHookCommand,\n} from '@orval/core';\nimport { execa } from 'execa';\nimport { parseArgsStringToArgv } from 'string-argv';\n\nexport const executeHook = async (\n name: Hook,\n commands: NormalizedHookCommand = [],\n args: string[] = [],\n) => {\n log(styleText('white', `Running ${name} hook...`));\n\n for (const command of commands) {\n try {\n if (isString(command)) {\n await executeCommand(command, args);\n } else if (isFunction(command)) {\n await command(args);\n } else if (isObject(command)) {\n await executeObjectCommand(command as HookOption, args);\n }\n } catch (error) {\n logError(error, `Failed to run ${name} hook`);\n }\n }\n};\n\nasync function executeCommand(command: string, args: string[]) {\n const [cmd, ..._args] = [...parseArgsStringToArgv(command), ...args];\n\n await execa(cmd, _args);\n}\n\nasync function executeObjectCommand(command: HookOption, args: string[]) {\n if (command.injectGeneratedDirsAndFiles === false) {\n args = [];\n }\n\n if (isString(command.command)) {\n await executeCommand(command.command, args);\n } else if (isFunction(command.command)) {\n await command.command();\n }\n}\n","import { styleText } from 'node:util';\n\nimport {\n dynamicImport,\n isObject,\n isString,\n logVerbose,\n logWarning,\n type PackageJson,\n resolveInstalledVersions,\n} from '@orval/core';\nimport { findUp, findUpMultiple } from 'find-up';\nimport fs from 'fs-extra';\nimport yaml from 'js-yaml';\n\nimport { normalizePath } from './options';\n\ntype CatalogData = Pick<PackageJson, 'catalog' | 'catalogs'>;\n\nexport const loadPackageJson = async (\n packageJson?: string,\n workspace = process.cwd(),\n): Promise<PackageJson | undefined> => {\n if (!packageJson) {\n const pkgPath = await findUp(['package.json'], { cwd: workspace });\n if (pkgPath) {\n const pkg = await dynamicImport<unknown>(pkgPath, workspace);\n\n if (isPackageJson(pkg)) {\n return resolveAndAttachVersions(\n await maybeReplaceCatalog(pkg, workspace),\n workspace,\n pkgPath,\n );\n } else {\n throw new Error('Invalid package.json file');\n }\n }\n return;\n }\n\n const normalizedPath = normalizePath(packageJson, workspace);\n if (fs.existsSync(normalizedPath)) {\n const pkg = await dynamicImport<unknown>(normalizedPath);\n\n if (isPackageJson(pkg)) {\n return resolveAndAttachVersions(\n await maybeReplaceCatalog(pkg, workspace),\n workspace,\n normalizedPath,\n );\n } else {\n throw new Error(`Invalid package.json file: ${normalizedPath}`);\n }\n }\n return;\n};\n\nconst isPackageJson = (obj: unknown): obj is PackageJson => isObject(obj);\n\nconst resolvedCache = new Map<string, Record<string, string>>();\n\n/** @internal visible for testing */\nexport const _resetResolvedCache = () => {\n resolvedCache.clear();\n};\n\nconst resolveAndAttachVersions = (\n pkg: PackageJson,\n workspace: string,\n cacheKey: string,\n): PackageJson => {\n const cached = resolvedCache.get(cacheKey);\n if (cached) {\n pkg.resolvedVersions = cached;\n return pkg;\n }\n\n const resolved = resolveInstalledVersions(pkg, workspace);\n if (Object.keys(resolved).length > 0) {\n pkg.resolvedVersions = resolved;\n resolvedCache.set(cacheKey, resolved);\n for (const [name, version] of Object.entries(resolved)) {\n logVerbose(\n styleText(\n 'dim',\n `Detected ${styleText('white', name)} v${styleText('white', version)}`,\n ),\n );\n }\n }\n return pkg;\n};\n\nconst hasCatalogReferences = (pkg: PackageJson): boolean => {\n return [\n ...Object.entries(pkg.dependencies ?? {}),\n ...Object.entries(pkg.devDependencies ?? {}),\n ...Object.entries(pkg.peerDependencies ?? {}),\n ].some(([, value]) => isString(value) && value.startsWith('catalog:'));\n};\n\nconst loadPnpmWorkspaceCatalog = async (\n workspace: string,\n): Promise<CatalogData | undefined> => {\n const filePath = await findUp('pnpm-workspace.yaml', { cwd: workspace });\n if (!filePath) return undefined;\n try {\n const file = await fs.readFile(filePath, 'utf8');\n const data = yaml.load(file) as Record<string, unknown> | undefined;\n if (!data?.catalog && !data?.catalogs) return undefined;\n return {\n catalog: data.catalog as CatalogData['catalog'],\n catalogs: data.catalogs as CatalogData['catalogs'],\n };\n } catch {\n return undefined;\n }\n};\n\nconst loadPackageJsonCatalog = async (\n workspace: string,\n): Promise<CatalogData | undefined> => {\n const filePaths = await findUpMultiple('package.json', { cwd: workspace });\n\n for (const filePath of filePaths) {\n try {\n const pkg = (await fs.readJson(filePath)) as Record<string, unknown>;\n if (pkg.catalog || pkg.catalogs) {\n return {\n catalog: pkg.catalog as CatalogData['catalog'],\n catalogs: pkg.catalogs as CatalogData['catalogs'],\n };\n }\n } catch {\n // Continue to next file\n }\n }\n return undefined;\n};\n\nconst loadYarnrcCatalog = async (\n workspace: string,\n): Promise<CatalogData | undefined> => {\n const filePath = await findUp('.yarnrc.yml', { cwd: workspace });\n if (!filePath) return undefined;\n try {\n const file = await fs.readFile(filePath, 'utf8');\n const data = yaml.load(file) as Record<string, unknown> | undefined;\n if (!data?.catalog && !data?.catalogs) return undefined;\n return {\n catalog: data.catalog as CatalogData['catalog'],\n catalogs: data.catalogs as CatalogData['catalogs'],\n };\n } catch {\n return undefined;\n }\n};\n\nconst maybeReplaceCatalog = async (\n pkg: PackageJson,\n workspace: string,\n): Promise<PackageJson> => {\n if (!hasCatalogReferences(pkg)) {\n return pkg;\n }\n\n const catalogData =\n (await loadPnpmWorkspaceCatalog(workspace)) ??\n (await loadPackageJsonCatalog(workspace)) ??\n (await loadYarnrcCatalog(workspace));\n\n if (!catalogData) {\n logWarning(\n '⚠️ package.json contains catalog: references, but no catalog source was found (checked: pnpm-workspace.yaml, package.json, .yarnrc.yml).',\n );\n return pkg;\n }\n\n performSubstitution(pkg.dependencies, catalogData);\n performSubstitution(pkg.devDependencies, catalogData);\n performSubstitution(pkg.peerDependencies, catalogData);\n\n return pkg;\n};\n\nconst performSubstitution = (\n dependencies: Record<string, string> | undefined,\n catalogData: CatalogData,\n) => {\n if (!dependencies) return;\n for (const [packageName, version] of Object.entries(dependencies)) {\n if (version === 'catalog:' || version === 'catalog:default') {\n if (!catalogData.catalog) {\n logWarning(\n `⚠️ catalog: substitution for the package '${packageName}' failed as there is no default catalog.`,\n );\n continue;\n }\n const sub = catalogData.catalog[packageName];\n if (!sub) {\n logWarning(\n `⚠️ catalog: substitution for the package '${packageName}' failed as there is no matching package in the default catalog.`,\n );\n continue;\n }\n dependencies[packageName] = sub;\n } else if (version.startsWith('catalog:')) {\n const catalogName = version.slice('catalog:'.length);\n const catalog = catalogData.catalogs?.[catalogName];\n if (!catalog) {\n logWarning(\n `⚠️ '${version}' substitution for the package '${packageName}' failed as there is no matching catalog named '${catalogName}'. (available named catalogs are: ${Object.keys(catalogData.catalogs ?? {}).join(', ')})`,\n );\n continue;\n }\n const sub = catalog[packageName];\n if (!sub) {\n logWarning(\n `⚠️ '${version}' substitution for the package '${packageName}' failed as there is no package in the catalog named '${catalogName}'. (packages in the catalog are: ${Object.keys(catalog).join(', ')})`,\n );\n continue;\n }\n dependencies[packageName] = sub;\n }\n }\n};\n","import { isNullish, isObject, isString, type Tsconfig } from '@orval/core';\nimport { findUp } from 'find-up';\nimport fs from 'fs-extra';\nimport {\n parseTsconfig,\n type TsConfigJson,\n type TsConfigJsonResolved,\n} from 'get-tsconfig';\n\nimport { normalizePath } from './options';\n\ntype LowercaseString<T extends string> = T extends `${infer First}${infer Rest}`\n ? `${Lowercase<First>}${LowercaseString<Rest>}`\n : T;\n\nconst convertTarget = (config: TsConfigJsonResolved): Tsconfig => {\n if (!config.compilerOptions?.target) {\n return {\n baseUrl: config.compilerOptions?.baseUrl,\n ...config,\n } as Tsconfig;\n }\n const lowercaseTarget =\n config.compilerOptions.target.toLowerCase() as LowercaseString<TsConfigJson.CompilerOptions.Target>;\n return {\n baseUrl: config.compilerOptions.baseUrl,\n ...config,\n compilerOptions: { ...config.compilerOptions, target: lowercaseTarget },\n };\n};\n\nexport const loadTsconfig = async (\n tsconfig?: Tsconfig | string,\n workspace = process.cwd(),\n): Promise<Tsconfig | undefined> => {\n if (isNullish(tsconfig)) {\n const configPath = await findUp(['tsconfig.json', 'jsconfig.json'], {\n cwd: workspace,\n });\n if (configPath) {\n const config = parseTsconfig(configPath);\n return convertTarget(config);\n }\n return;\n }\n\n if (isString(tsconfig)) {\n const normalizedPath = normalizePath(tsconfig, workspace);\n if (fs.existsSync(normalizedPath)) {\n const config = parseTsconfig(normalizedPath);\n return convertTarget(config);\n }\n return;\n }\n\n if (isObject(tsconfig)) {\n return tsconfig;\n }\n return;\n};\n","import { access } from 'node:fs/promises';\nimport nodePath from 'node:path';\nimport { styleText } from 'node:util';\n\nimport {\n type ConfigExternal,\n type EffectOptions,\n FormDataArrayHandling,\n type GlobalMockOptions,\n type GlobalOptions,\n type HonoOptions,\n type Hook,\n type HookFunction,\n type HookOption,\n type HooksOptions,\n type InputOptions,\n type InputTransformerFn,\n isBoolean,\n isFunction,\n isNullish,\n isObject,\n isString,\n isUrl,\n type JsDocOptions,\n logWarning,\n type McpOptions,\n type McpServerOptions,\n type Mutator,\n NamingConvention,\n type NormalizedEffectOptions,\n type NormalizedFactoryMethodsOptions,\n type NormalizedHonoOptions,\n type NormalizedHookOptions,\n type NormalizedJsDocOptions,\n type NormalizedMcpOptions,\n type NormalizedMcpServerOptions,\n type NormalizedMocksConfig,\n type NormalizedMutator,\n type NormalizedOperationOptions,\n type NormalizedOptions,\n type NormalizedOverrideOutput,\n type NormalizedQueryOptions,\n type NormalizedSchemaOptions,\n type OperationOptions,\n type OptionsExport,\n OutputClient,\n OutputHttpClient,\n OutputMockType,\n OutputMode,\n type OverrideOutput,\n PropertySortOrder,\n type QueryOptions,\n RefComponentSuffix,\n type SchemaOptions,\n} from '@orval/core';\nimport { getDefaultMockOptionsForType } from '@orval/mock';\n\nimport pkg from '../../package.json';\nimport { loadPackageJson } from './package-json';\nimport { loadTsconfig } from './tsconfig';\n\nconst INPUT_TARGET_FETCH_TIMEOUT_MS = 10_000;\n/**\n * Type helper to make it easier to use orval.config.ts\n * accepts a direct {@link ConfigExternal} object.\n */\nexport function defineConfig(options: ConfigExternal): ConfigExternal {\n return options;\n}\n\n/**\n * Type helper to make it easier to write input transformers.\n * accepts a direct {@link InputTransformerFn} function.\n */\nexport function defineTransformer(\n transformer: InputTransformerFn,\n): InputTransformerFn {\n return transformer;\n}\n\nfunction createFormData(\n workspace: string,\n formData: OverrideOutput['formData'],\n): NormalizedOverrideOutput['formData'] {\n const defaultArrayHandling = FormDataArrayHandling.SERIALIZE;\n if (formData === undefined)\n return { disabled: false, arrayHandling: defaultArrayHandling };\n if (isBoolean(formData))\n return { disabled: !formData, arrayHandling: defaultArrayHandling };\n if (isString(formData))\n return {\n disabled: false,\n mutator: normalizeMutator(workspace, formData),\n arrayHandling: defaultArrayHandling,\n };\n if ('mutator' in formData || 'arrayHandling' in formData)\n return {\n disabled: false,\n mutator: normalizeMutator(workspace, formData.mutator),\n arrayHandling: formData.arrayHandling ?? defaultArrayHandling,\n };\n return {\n disabled: false,\n mutator: normalizeMutator(workspace, formData),\n arrayHandling: defaultArrayHandling,\n };\n}\n\nfunction normalizeSchemasOption(\n schemas: string | SchemaOptions | false | undefined,\n workspace: string,\n): string | NormalizedSchemaOptions | undefined {\n if (!schemas) {\n return undefined;\n }\n\n if (isString(schemas)) {\n return normalizePath(schemas, workspace);\n }\n\n return {\n path: normalizePath(schemas.path, workspace),\n type: schemas.type,\n };\n}\n\nfunction normalizeEffectOptions(\n effect?: EffectOptions,\n): NormalizedEffectOptions {\n return {\n strict: {\n param: effect?.strict?.param ?? false,\n query: effect?.strict?.query ?? false,\n header: effect?.strict?.header ?? false,\n body: effect?.strict?.body ?? false,\n response: effect?.strict?.response ?? false,\n },\n generate: {\n param: effect?.generate?.param ?? true,\n query: effect?.generate?.query ?? true,\n header: effect?.generate?.header ?? true,\n body: effect?.generate?.body ?? true,\n response: effect?.generate?.response ?? true,\n },\n generateEachHttpStatus: effect?.generateEachHttpStatus ?? false,\n useBrandedTypes: effect?.useBrandedTypes ?? false,\n };\n}\n\nexport async function normalizeOptions(\n optionsExport: OptionsExport,\n workspace = process.cwd(),\n globalOptions: GlobalOptions = {},\n): Promise<NormalizedOptions> {\n const options = await (isFunction(optionsExport)\n ? optionsExport()\n : optionsExport);\n\n if (!options.input) {\n throw new Error(styleText('red', `Config requires an input.`));\n }\n\n if (!options.output) {\n throw new Error(styleText('red', `Config requires an output.`));\n }\n\n const inputOptions: InputOptions =\n isString(options.input) || Array.isArray(options.input)\n ? { target: options.input }\n : options.input;\n\n const outputOptions = isString(options.output)\n ? { target: options.output }\n : options.output;\n\n const outputWorkspace = normalizePath(\n outputOptions.workspace ?? '',\n workspace,\n );\n\n const { clean, client, httpClient, mode } = globalOptions;\n\n const tsconfig = await loadTsconfig(\n outputOptions.tsconfig ?? globalOptions.tsconfig,\n workspace,\n );\n\n const packageJson = await loadPackageJson(\n outputOptions.packageJson ?? globalOptions.packageJson,\n workspace,\n );\n\n // Normalize the `mock` option into a canonical `NormalizedMocksConfig`\n // so the rest of the pipeline can iterate `generators` uniformly without\n // branching on the input shape (boolean shorthand, function form, or\n // object form).\n const mocksOption = outputOptions.mock ?? globalOptions.mock;\n let mocks: NormalizedMocksConfig = {\n indexMockFiles: false,\n generators: [],\n };\n if (isBoolean(mocksOption) && mocksOption) {\n // `mock: true` shorthand emits both an MSW handler file and a faker\n // factory file using default options for each.\n mocks = {\n indexMockFiles: false,\n generators: [\n getDefaultMockOptionsForType(OutputMockType.MSW),\n getDefaultMockOptionsForType(OutputMockType.FAKER),\n ],\n };\n } else if (isFunction(mocksOption)) {\n // Function form treats the entire mocks option as a single\n // ClientMockBuilder. Wrap it in the array so writers can still iterate.\n mocks = { indexMockFiles: false, generators: [mocksOption] };\n } else if (mocksOption && typeof mocksOption === 'object') {\n if (!Array.isArray(mocksOption.generators)) {\n throw new TypeError(\n 'mock.generators must be an array of generator entries (e.g. [{ type: \"msw\" }]).',\n );\n }\n mocks = {\n indexMockFiles: mocksOption.indexMockFiles ?? false,\n generators: mocksOption.generators.map((m) =>\n isFunction(m)\n ? m\n : ({\n ...getDefaultMockOptionsForType(m.type),\n ...m,\n } as GlobalMockOptions),\n ),\n };\n }\n\n const seenMockTypes = new Set<string>();\n for (const entry of mocks.generators) {\n if (isFunction(entry)) continue;\n if (seenMockTypes.has(entry.type)) {\n throw new Error(\n `Duplicate mock generator type \"${entry.type}\". Each type can only appear once in mock.generators.`,\n );\n }\n seenMockTypes.add(entry.type);\n }\n\n const defaultFileExtension = '.ts';\n\n // Reusable Zod schemas land in `*.zod.ts` files by default so they sit\n // alongside any existing TypeScript types without a name collision. We\n // expose this as a separate `schemaFileExtension` field (not by flipping\n // the global `fileExtension`) so that non-schema writers (mode writers,\n // mock writers, the workspace barrel) keep their own extensions and don't\n // start emitting `*.zod.ts` for unrelated artifacts. A user-set\n // `output.fileExtension` overrides this default at the call site.\n const isZodSchemasOutput =\n !!outputOptions.schemas &&\n ((!isString(outputOptions.schemas) &&\n outputOptions.schemas.type === 'zod') ||\n (isString(outputOptions.schemas) &&\n (outputOptions.client ?? client) === 'zod' &&\n outputOptions.override?.zod?.generateReusableSchemas === true));\n const defaultSchemaFileExtension = isZodSchemasOutput\n ? '.zod.ts'\n : defaultFileExtension;\n\n const factoryMethodsConfig = outputOptions.factoryMethods;\n let factoryMethods: NormalizedFactoryMethodsOptions | undefined = undefined;\n\n if (factoryMethodsConfig) {\n factoryMethods = {\n functionNamePrefix: factoryMethodsConfig.functionNamePrefix ?? 'create',\n mode: factoryMethodsConfig.mode ?? 'split',\n outputDirectory: factoryMethodsConfig.outputDirectory\n ? normalizePath(factoryMethodsConfig.outputDirectory, outputWorkspace)\n : outputOptions.schemas\n ? normalizePath(\n isString(outputOptions.schemas)\n ? outputOptions.schemas\n : outputOptions.schemas.path,\n outputWorkspace,\n )\n : normalizePath(outputWorkspace, outputWorkspace),\n includeOptionalProperty:\n factoryMethodsConfig.includeOptionalProperty ?? true,\n };\n }\n\n // `useQuery` / `useMutation` defaults are applied per-verb in\n // `query-generator.ts` so we can tell \"unset\" from \"explicit true\" (#2376).\n const globalQueryOptions: NormalizedQueryOptions = {\n signal: true,\n shouldExportMutatorHooks: true,\n shouldExportHttpClient: true,\n shouldExportQueryKey: true,\n shouldFilterQueryKey: false,\n shouldSplitQueryKey: false,\n ...normalizeQueryOptions(outputOptions.override?.query, workspace),\n };\n\n const normalizedOptions: NormalizedOptions = {\n input: {\n target: globalOptions.input\n ? Array.isArray(globalOptions.input)\n ? await resolveFirstValidTarget(\n globalOptions.input,\n process.cwd(),\n inputOptions.parserOptions,\n )\n : normalizePathOrUrl(globalOptions.input, process.cwd())\n : Array.isArray(inputOptions.target)\n ? await resolveFirstValidTarget(\n inputOptions.target,\n workspace,\n inputOptions.parserOptions,\n )\n : normalizePathOrUrl(inputOptions.target, workspace),\n override: {\n transformer: normalizePath(\n inputOptions.override?.transformer,\n workspace,\n ),\n },\n unsafeDisableValidation: inputOptions.unsafeDisableValidation ?? false,\n filters: inputOptions.filters,\n parserOptions: inputOptions.parserOptions,\n },\n output: {\n target: globalOptions.output\n ? normalizePath(globalOptions.output, process.cwd())\n : normalizePath(outputOptions.target, outputWorkspace),\n schemas: normalizeSchemasOption(outputOptions.schemas, outputWorkspace),\n operationSchemas: outputOptions.operationSchemas\n ? normalizePath(outputOptions.operationSchemas, outputWorkspace)\n : undefined,\n namingConvention:\n outputOptions.namingConvention ?? NamingConvention.CAMEL_CASE,\n fileExtension: outputOptions.fileExtension ?? defaultFileExtension,\n schemaFileExtension:\n outputOptions.schemaFileExtension ??\n outputOptions.fileExtension ??\n defaultSchemaFileExtension,\n workspace: outputOptions.workspace ? outputWorkspace : undefined,\n client: outputOptions.client ?? client ?? OutputClient.AXIOS_FUNCTIONS,\n httpClient:\n outputOptions.httpClient ??\n httpClient ??\n // Auto-detect: use Angular HttpClient for angular-query by default\n ((outputOptions.client ?? client) === OutputClient.ANGULAR_QUERY\n ? OutputHttpClient.ANGULAR\n : OutputHttpClient.FETCH),\n mode: normalizeOutputMode(outputOptions.mode ?? mode),\n mock: mocks,\n clean: outputOptions.clean ?? clean ?? false,\n docs: outputOptions.docs ?? false,\n formatter: outputOptions.formatter ?? globalOptions.formatter,\n tsconfig,\n packageJson,\n headers: outputOptions.headers ?? false,\n indexFiles: outputOptions.indexFiles ?? true,\n baseUrl: outputOptions.baseUrl,\n unionAddMissingProperties:\n outputOptions.unionAddMissingProperties ?? false,\n factoryMethods,\n override: {\n ...outputOptions.override,\n mock: {\n arrayMin: outputOptions.override?.mock?.arrayMin ?? 1,\n arrayMax: outputOptions.override?.mock?.arrayMax ?? 10,\n stringMin: outputOptions.override?.mock?.stringMin ?? 10,\n stringMax: outputOptions.override?.mock?.stringMax ?? 20,\n fractionDigits: outputOptions.override?.mock?.fractionDigits ?? 2,\n ...outputOptions.override?.mock,\n },\n operations: normalizeOperationsAndTags(\n outputOptions.override?.operations ?? {},\n outputWorkspace,\n {\n query: globalQueryOptions,\n },\n ),\n tags: normalizeOperationsAndTags(\n outputOptions.override?.tags ?? {},\n outputWorkspace,\n {\n query: globalQueryOptions,\n },\n ),\n mutator: normalizeMutator(\n outputWorkspace,\n outputOptions.override?.mutator,\n ),\n formData: createFormData(\n outputWorkspace,\n outputOptions.override?.formData,\n ),\n formUrlEncoded:\n (isBoolean(outputOptions.override?.formUrlEncoded)\n ? outputOptions.override.formUrlEncoded\n : normalizeMutator(\n outputWorkspace,\n outputOptions.override?.formUrlEncoded,\n )) ?? true,\n paramsSerializer: normalizeMutator(\n outputWorkspace,\n outputOptions.override?.paramsSerializer,\n ),\n paramsFilter: normalizeMutator(\n outputWorkspace,\n outputOptions.override?.paramsFilter,\n ),\n header:\n outputOptions.override?.header === false\n ? false\n : isFunction(outputOptions.override?.header)\n ? outputOptions.override.header\n : getDefaultFilesHeader,\n requestOptions: outputOptions.override?.requestOptions ?? true,\n namingConvention: outputOptions.override?.namingConvention ?? {},\n components: {\n schemas: {\n suffix: RefComponentSuffix.schemas,\n itemSuffix:\n outputOptions.override?.components?.schemas?.itemSuffix ?? 'Item',\n ...outputOptions.override?.components?.schemas,\n },\n responses: {\n suffix: RefComponentSuffix.responses,\n ...outputOptions.override?.components?.responses,\n },\n parameters: {\n suffix: RefComponentSuffix.parameters,\n ...outputOptions.override?.components?.parameters,\n },\n requestBodies: {\n suffix: RefComponentSuffix.requestBodies,\n ...outputOptions.override?.components?.requestBodies,\n },\n },\n hono: normalizeHonoOptions(outputOptions.override?.hono, workspace),\n mcp: normalizeMcpOptions(outputOptions.override?.mcp, workspace),\n jsDoc: normalizeJSDocOptions(outputOptions.override?.jsDoc),\n query: globalQueryOptions,\n zod: {\n strict: {\n param: outputOptions.override?.zod?.strict?.param ?? false,\n query: outputOptions.override?.zod?.strict?.query ?? false,\n header: outputOptions.override?.zod?.strict?.header ?? false,\n body: outputOptions.override?.zod?.strict?.body ?? false,\n response: outputOptions.override?.zod?.strict?.response ?? false,\n },\n generate: {\n param: outputOptions.override?.zod?.generate?.param ?? true,\n query: outputOptions.override?.zod?.generate?.query ?? true,\n header: outputOptions.override?.zod?.generate?.header ?? true,\n body: outputOptions.override?.zod?.generate?.body ?? true,\n response: outputOptions.override?.zod?.generate?.response ?? true,\n },\n coerce: {\n param: outputOptions.override?.zod?.coerce?.param ?? false,\n query: outputOptions.override?.zod?.coerce?.query ?? false,\n header: outputOptions.override?.zod?.coerce?.header ?? false,\n body: outputOptions.override?.zod?.coerce?.body ?? false,\n response: outputOptions.override?.zod?.coerce?.response ?? false,\n },\n preprocess: {\n ...(outputOptions.override?.zod?.preprocess?.param\n ? {\n param: normalizeMutator(\n workspace,\n outputOptions.override.zod.preprocess.param,\n ),\n }\n : {}),\n ...(outputOptions.override?.zod?.preprocess?.query\n ? {\n query: normalizeMutator(\n workspace,\n outputOptions.override.zod.preprocess.query,\n ),\n }\n : {}),\n ...(outputOptions.override?.zod?.preprocess?.header\n ? {\n header: normalizeMutator(\n workspace,\n outputOptions.override.zod.preprocess.header,\n ),\n }\n : {}),\n ...(outputOptions.override?.zod?.preprocess?.body\n ? {\n body: normalizeMutator(\n workspace,\n outputOptions.override.zod.preprocess.body,\n ),\n }\n : {}),\n ...(outputOptions.override?.zod?.preprocess?.response\n ? {\n response: normalizeMutator(\n workspace,\n outputOptions.override.zod.preprocess.response,\n ),\n }\n : {}),\n },\n ...(outputOptions.override?.zod?.params\n ? {\n params: normalizeMutator(\n workspace,\n outputOptions.override.zod.params,\n ),\n }\n : {}),\n generateEachHttpStatus:\n outputOptions.override?.zod?.generateEachHttpStatus ?? false,\n useBrandedTypes:\n outputOptions.override?.zod?.useBrandedTypes ?? false,\n generateReusableSchemas:\n outputOptions.override?.zod?.generateReusableSchemas ?? false,\n generateMeta: outputOptions.override?.zod?.generateMeta ?? false,\n dateTimeOptions: outputOptions.override?.zod?.dateTimeOptions ?? {\n offset: true,\n },\n timeOptions: outputOptions.override?.zod?.timeOptions ?? {},\n },\n effect: normalizeEffectOptions(outputOptions.override?.effect),\n swr: {\n generateErrorTypes: false,\n ...outputOptions.override?.swr,\n },\n angular: {\n provideIn: outputOptions.override?.angular?.provideIn ?? 'root',\n client:\n outputOptions.override?.angular?.retrievalClient ??\n outputOptions.override?.angular?.client ??\n 'httpClient',\n runtimeValidation:\n outputOptions.override?.angular?.runtimeValidation ?? false,\n ...(outputOptions.override?.angular?.httpResource\n ? { httpResource: outputOptions.override.angular.httpResource }\n : {}),\n },\n fetch: {\n includeHttpResponseReturnType:\n outputOptions.override?.fetch?.includeHttpResponseReturnType ??\n true,\n forceSuccessResponse:\n outputOptions.override?.fetch?.forceSuccessResponse ?? false,\n runtimeValidation:\n outputOptions.override?.fetch?.runtimeValidation ?? false,\n useRuntimeFetcher:\n outputOptions.override?.fetch?.useRuntimeFetcher ?? false,\n ...outputOptions.override?.fetch,\n ...(outputOptions.override?.fetch?.jsonReviver\n ? {\n jsonReviver: normalizeMutator(\n outputWorkspace,\n outputOptions.override.fetch.jsonReviver,\n ),\n }\n : {}),\n },\n useDates: outputOptions.override?.useDates ?? false,\n useDeprecatedOperations:\n outputOptions.override?.useDeprecatedOperations ?? true,\n enumGenerationType:\n outputOptions.override?.enumGenerationType ?? 'const',\n suppressReadonlyModifier:\n outputOptions.override?.suppressReadonlyModifier ?? false,\n preserveReadonlyRequestBodies:\n outputOptions.override?.preserveReadonlyRequestBodies ?? 'strip',\n splitByContentType: outputOptions.override?.splitByContentType ?? false,\n aliasCombinedTypes: outputOptions.override?.aliasCombinedTypes ?? false,\n },\n allParamsOptional: outputOptions.allParamsOptional ?? false,\n urlEncodeParameters: outputOptions.urlEncodeParameters ?? false,\n optionsParamRequired: outputOptions.optionsParamRequired ?? false,\n propertySortOrder:\n outputOptions.propertySortOrder ?? PropertySortOrder.SPECIFICATION,\n },\n hooks: options.hooks ? normalizeHooks(options.hooks) : {},\n };\n\n if (!normalizedOptions.input.target) {\n throw new Error(styleText('red', `Config requires an input target.`));\n }\n\n if (!normalizedOptions.output.target && !normalizedOptions.output.schemas) {\n throw new Error(\n styleText('red', `Config requires an output target or schemas.`),\n );\n }\n\n // `paramsFilter` is only consumed by the Angular generator. That runs for\n // the `angular` client (regardless of `httpClient`, which stays at its\n // `fetch` default there) and for `angular-query` when it resolves to the\n // Angular HttpClient. For any other client the mutator would be imported\n // but never called, so fail fast instead of emitting a dead import.\n const usesAngularGenerator =\n normalizedOptions.output.client === OutputClient.ANGULAR ||\n (normalizedOptions.output.client === OutputClient.ANGULAR_QUERY &&\n normalizedOptions.output.httpClient === OutputHttpClient.ANGULAR);\n if (normalizedOptions.output.override.paramsFilter && !usesAngularGenerator) {\n throw new Error(\n styleText(\n 'red',\n `\\`override.paramsFilter\\` is only supported by the Angular generator (the \\`angular\\` client, or \\`angular-query\\` with \\`httpClient: 'angular'\\`). It has no effect for other clients — use \\`override.paramsSerializer\\` instead.`,\n ),\n );\n }\n if (!usesAngularGenerator) {\n const offendingOperation = Object.entries(\n normalizedOptions.output.override.operations,\n ).find(([, opOverride]) => opOverride?.paramsFilter)?.[0];\n if (offendingOperation) {\n throw new Error(\n styleText(\n 'red',\n `\\`override.operations[\"${offendingOperation}\"].paramsFilter\\` is only supported by the Angular generator (the \\`angular\\` client, or \\`angular-query\\` with \\`httpClient: 'angular'\\`). It has no effect for other clients — use \\`override.paramsSerializer\\` instead.`,\n ),\n );\n }\n const offendingTag = Object.entries(\n normalizedOptions.output.override.tags,\n ).find(([, tagOverride]) => tagOverride?.paramsFilter)?.[0];\n if (offendingTag) {\n throw new Error(\n styleText(\n 'red',\n `\\`override.tags[\"${offendingTag}\"].paramsFilter\\` is only supported by the Angular generator (the \\`angular\\` client, or \\`angular-query\\` with \\`httpClient: 'angular'\\`). It has no effect for other clients — use \\`override.paramsSerializer\\` instead.`,\n ),\n );\n }\n }\n\n if (\n normalizedOptions.output.httpClient === OutputHttpClient.FETCH &&\n normalizedOptions.output.optionsParamRequired &&\n normalizedOptions.output.override.requestOptions !== false\n ) {\n logWarning(\n `⚠️ With \\`httpClient: 'fetch'\\`, \\`optionsParamRequired: true\\` cannot make the generated \\`options\\` parameter required. The fetch \\`options\\` parameter remains optional with type \\`RequestInit\\` (\\`optionsParamRequired\\` may still affect other generated parameters). Set \\`httpClient: 'axios'\\` to make the \\`options\\` parameter required.`,\n );\n }\n\n return normalizedOptions;\n}\n\nfunction normalizeMutator(\n workspace: string,\n mutator?: Mutator,\n): NormalizedMutator | undefined {\n if (isObject(mutator)) {\n const m = mutator as Exclude<Mutator, string>;\n if (!m.path) {\n throw new Error(styleText('red', `Mutator requires a path.`));\n }\n\n return {\n path: nodePath.resolve(workspace, m.path),\n name: m.name,\n default: m.default ?? !m.name,\n alias: m.alias,\n external: m.external,\n extension: m.extension,\n };\n }\n\n if (isString(mutator)) {\n return {\n path: nodePath.resolve(workspace, mutator),\n default: true,\n };\n }\n\n return undefined;\n}\n\nasync function resolveFirstValidTarget(\n targets: string[],\n workspace: string,\n parserOptions?: InputOptions['parserOptions'],\n): Promise<string> {\n for (const target of targets) {\n if (isUrl(target)) {\n try {\n const headers = getHeadersForUrl(target, parserOptions?.headers);\n const headResponse = await fetchWithTimeout(target, {\n method: 'HEAD',\n headers,\n });\n\n if (headResponse.ok) {\n return target;\n }\n\n if (headResponse.status === 405 || headResponse.status === 501) {\n const getResponse = await fetchWithTimeout(target, {\n method: 'GET',\n headers,\n });\n\n if (getResponse.ok) {\n return target;\n }\n }\n } catch {\n continue;\n }\n\n continue;\n }\n\n const resolvedTarget = normalizePath(target, workspace);\n\n try {\n await access(resolvedTarget);\n return resolvedTarget;\n } catch {\n continue;\n }\n }\n\n throw new Error(\n styleText(\n 'red',\n `None of the input targets could be resolved:\\n${targets.map((target) => ` - ${target}`).join('\\n')}`,\n ),\n );\n}\n\nfunction getHeadersForUrl(\n url: string,\n headersConfig?: NonNullable<InputOptions['parserOptions']>['headers'],\n): Record<string, string> {\n if (!headersConfig) return {};\n\n const { hostname } = new URL(url);\n const matchedHeaders: Record<string, string> = {};\n\n for (const headerEntry of headersConfig) {\n if (\n headerEntry.domains.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`),\n )\n ) {\n Object.assign(matchedHeaders, headerEntry.headers);\n }\n }\n\n return matchedHeaders;\n}\n\nasync function fetchWithTimeout(\n target: string,\n init: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => {\n controller.abort();\n }, INPUT_TARGET_FETCH_TIMEOUT_MS);\n\n try {\n return await fetch(target, {\n ...init,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\nfunction normalizePathOrUrl<T>(path: T, workspace: string) {\n if (isString(path) && !isUrl(path)) {\n return normalizePath(path, workspace);\n }\n\n return path;\n}\n\nexport function normalizePath<T>(path: T, workspace: string) {\n if (!isString(path)) {\n return path;\n }\n return nodePath.resolve(workspace, path);\n}\n\nfunction normalizeOperationsAndTags(\n operationsOrTags: Record<string, OperationOptions>,\n workspace: string,\n global: {\n query: NormalizedQueryOptions;\n },\n): Record<string, NormalizedOperationOptions> {\n return Object.fromEntries(\n Object.entries(operationsOrTags).map(\n ([\n key,\n {\n transformer,\n mutator,\n formData,\n formUrlEncoded,\n paramsSerializer,\n paramsFilter,\n query,\n angular,\n zod,\n effect,\n ...rest\n },\n ]) => {\n return [\n key,\n {\n ...rest,\n ...(angular\n ? {\n angular: {\n provideIn: angular.provideIn ?? 'root',\n client:\n angular.retrievalClient ?? angular.client ?? 'httpClient',\n runtimeValidation: angular.runtimeValidation ?? false,\n ...(angular.httpResource\n ? { httpResource: angular.httpResource }\n : {}),\n },\n }\n : {}),\n ...(query\n ? {\n query: normalizeQueryOptions(query, workspace, global.query),\n }\n : {}),\n ...(zod\n ? {\n zod: {\n strict: {\n param: zod.strict?.param ?? false,\n query: zod.strict?.query ?? false,\n header: zod.strict?.header ?? false,\n body: zod.strict?.body ?? false,\n response: zod.strict?.response ?? false,\n },\n generate: {\n param: zod.generate?.param ?? true,\n query: zod.generate?.query ?? true,\n header: zod.generate?.header ?? true,\n body: zod.generate?.body ?? true,\n response: zod.generate?.response ?? true,\n },\n coerce: {\n param: zod.coerce?.param ?? false,\n query: zod.coerce?.query ?? false,\n header: zod.coerce?.header ?? false,\n body: zod.coerce?.body ?? false,\n response: zod.coerce?.response ?? false,\n },\n preprocess: {\n ...(zod.preprocess?.param\n ? {\n param: normalizeMutator(\n workspace,\n zod.preprocess.param,\n ),\n }\n : {}),\n ...(zod.preprocess?.query\n ? {\n query: normalizeMutator(\n workspace,\n zod.preprocess.query,\n ),\n }\n : {}),\n ...(zod.preprocess?.header\n ? {\n header: normalizeMutator(\n workspace,\n zod.preprocess.header,\n ),\n }\n : {}),\n ...(zod.preprocess?.body\n ? {\n body: normalizeMutator(\n workspace,\n zod.preprocess.body,\n ),\n }\n : {}),\n ...(zod.preprocess?.response\n ? {\n response: normalizeMutator(\n workspace,\n zod.preprocess.response,\n ),\n }\n : {}),\n },\n ...(zod.params\n ? {\n params: normalizeMutator(workspace, zod.params),\n }\n : {}),\n generateEachHttpStatus: zod.generateEachHttpStatus ?? false,\n useBrandedTypes: zod.useBrandedTypes ?? false,\n generateReusableSchemas:\n zod.generateReusableSchemas ?? false,\n generateMeta: zod.generateMeta ?? false,\n dateTimeOptions: zod.dateTimeOptions ?? { offset: true },\n timeOptions: zod.timeOptions ?? {},\n },\n }\n : {}),\n ...(effect ? { effect: normalizeEffectOptions(effect) } : {}),\n ...(transformer\n ? { transformer: normalizePath(transformer, workspace) }\n : {}),\n ...(mutator\n ? { mutator: normalizeMutator(workspace, mutator) }\n : {}),\n ...(formData === undefined\n ? {}\n : { formData: createFormData(workspace, formData) }),\n ...(formUrlEncoded\n ? {\n formUrlEncoded: isBoolean(formUrlEncoded)\n ? formUrlEncoded\n : normalizeMutator(workspace, formUrlEncoded),\n }\n : {}),\n ...(paramsSerializer\n ? {\n paramsSerializer: normalizeMutator(\n workspace,\n paramsSerializer,\n ),\n }\n : {}),\n ...(paramsFilter\n ? {\n paramsFilter: normalizeMutator(workspace, paramsFilter),\n }\n : {}),\n },\n ];\n },\n ),\n );\n}\n\nfunction normalizeOutputMode(mode?: OutputMode): OutputMode {\n if (!mode) {\n return OutputMode.SINGLE;\n }\n\n if (!Object.values(OutputMode).includes(mode)) {\n logWarning(`⚠️ Unknown provided mode => ${mode}`);\n return OutputMode.SINGLE;\n }\n\n return mode;\n}\n\nfunction normalizeHooks(hooks: HooksOptions): NormalizedHookOptions {\n const keys = Object.keys(hooks) as unknown as Hook[];\n\n const result: NormalizedHookOptions = {};\n for (const key of keys) {\n if (isString(hooks[key])) {\n result[key] = [hooks[key]] as string[];\n } else if (Array.isArray(hooks[key])) {\n result[key] = hooks[key] as string[];\n } else if (isFunction(hooks[key])) {\n result[key] = [hooks[key]] as HookFunction[];\n } else if (isObject(hooks[key])) {\n result[key] = [hooks[key]] as HookOption[];\n }\n }\n return result;\n}\n\nfunction normalizeHonoOptions(\n hono: HonoOptions = {},\n workspace: string,\n): NormalizedHonoOptions {\n return {\n ...(hono.handlers\n ? { handlers: nodePath.resolve(workspace, hono.handlers) }\n : {}),\n compositeRoute: hono.compositeRoute\n ? nodePath.resolve(workspace, hono.compositeRoute)\n : '',\n validator: hono.validator ?? true,\n validatorOutputPath: hono.validatorOutputPath\n ? nodePath.resolve(workspace, hono.validatorOutputPath)\n : '',\n };\n}\n\nfunction normalizeMcpServerOptions(\n server: McpServerOptions,\n workspace: string,\n): NormalizedMcpServerOptions {\n return {\n path: nodePath.resolve(workspace, server.path),\n name: server.name,\n default: server.default ?? !server.name,\n };\n}\n\nfunction normalizeMcpOptions(\n mcp: McpOptions = {},\n workspace: string,\n): NormalizedMcpOptions {\n return {\n ...(mcp.server\n ? { server: normalizeMcpServerOptions(mcp.server, workspace) }\n : {}),\n };\n}\n\nfunction normalizeJSDocOptions(\n jsdoc: JsDocOptions = {},\n): NormalizedJsDocOptions {\n return {\n ...jsdoc,\n };\n}\n\nfunction normalizeQueryOptions(\n queryOptions: QueryOptions = {},\n outputWorkspace: string,\n globalOptions: NormalizedQueryOptions = {},\n): NormalizedQueryOptions {\n if (queryOptions.options) {\n logWarning(\n '⚠️ Using query options is deprecated and will be removed in a future major release. Please use queryOptions or mutationOptions instead.',\n );\n }\n\n return {\n ...(isNullish(queryOptions.usePrefetch)\n ? {}\n : { usePrefetch: queryOptions.usePrefetch }),\n ...(isNullish(queryOptions.useInvalidate)\n ? {}\n : { useInvalidate: queryOptions.useInvalidate }),\n ...(isNullish(queryOptions.useSetQueryData)\n ? {}\n : { useSetQueryData: queryOptions.useSetQueryData }),\n ...(isNullish(queryOptions.useGetQueryData)\n ? {}\n : { useGetQueryData: queryOptions.useGetQueryData }),\n ...(isNullish(queryOptions.useQuery)\n ? {}\n : { useQuery: queryOptions.useQuery }),\n ...(isNullish(queryOptions.useSuspenseQuery)\n ? {}\n : { useSuspenseQuery: queryOptions.useSuspenseQuery }),\n ...(isNullish(queryOptions.useMutation)\n ? {}\n : { useMutation: queryOptions.useMutation }),\n ...(isNullish(queryOptions.useInfinite)\n ? {}\n : { useInfinite: queryOptions.useInfinite }),\n ...(isNullish(queryOptions.useSuspenseInfiniteQuery)\n ? {}\n : { useSuspenseInfiniteQuery: queryOptions.useSuspenseInfiniteQuery }),\n ...(queryOptions.useInfiniteQueryParam\n ? { useInfiniteQueryParam: queryOptions.useInfiniteQueryParam }\n : {}),\n ...(queryOptions.options ? { options: queryOptions.options } : {}),\n ...(globalOptions.queryKey\n ? {\n queryKey: globalOptions.queryKey,\n }\n : {}),\n ...(queryOptions.queryKey\n ? {\n queryKey: normalizeMutator(outputWorkspace, queryOptions.queryKey),\n }\n : {}),\n ...(globalOptions.queryOptions\n ? {\n queryOptions: globalOptions.queryOptions,\n }\n : {}),\n ...(queryOptions.queryOptions\n ? {\n queryOptions: normalizeMutator(\n outputWorkspace,\n queryOptions.queryOptions,\n ),\n }\n : {}),\n ...(globalOptions.mutationOptions\n ? {\n mutationOptions: globalOptions.mutationOptions,\n }\n : {}),\n ...(queryOptions.mutationOptions\n ? {\n mutationOptions: normalizeMutator(\n outputWorkspace,\n queryOptions.mutationOptions,\n ),\n }\n : {}),\n ...(isNullish(globalOptions.shouldExportQueryKey)\n ? {}\n : {\n shouldExportQueryKey: globalOptions.shouldExportQueryKey,\n }),\n ...(isNullish(queryOptions.shouldExportQueryKey)\n ? {}\n : { shouldExportQueryKey: queryOptions.shouldExportQueryKey }),\n ...(isNullish(globalOptions.shouldFilterQueryKey)\n ? {}\n : {\n shouldFilterQueryKey: globalOptions.shouldFilterQueryKey,\n }),\n ...(isNullish(queryOptions.shouldFilterQueryKey)\n ? {}\n : { shouldFilterQueryKey: queryOptions.shouldFilterQueryKey }),\n ...(isNullish(globalOptions.shouldExportHttpClient)\n ? {}\n : {\n shouldExportHttpClient: globalOptions.shouldExportHttpClient,\n }),\n ...(isNullish(queryOptions.shouldExportHttpClient)\n ? {}\n : { shouldExportHttpClient: queryOptions.shouldExportHttpClient }),\n ...(isNullish(globalOptions.shouldExportMutatorHooks)\n ? {}\n : {\n shouldExportMutatorHooks: globalOptions.shouldExportMutatorHooks,\n }),\n ...(isNullish(queryOptions.shouldExportMutatorHooks)\n ? {}\n : { shouldExportMutatorHooks: queryOptions.shouldExportMutatorHooks }),\n ...(isNullish(globalOptions.shouldSplitQueryKey)\n ? {}\n : {\n shouldSplitQueryKey: globalOptions.shouldSplitQueryKey,\n }),\n ...(isNullish(queryOptions.shouldSplitQueryKey)\n ? {}\n : { shouldSplitQueryKey: queryOptions.shouldSplitQueryKey }),\n ...(isNullish(globalOptions.signal)\n ? {}\n : {\n signal: globalOptions.signal,\n }),\n ...(isNullish(globalOptions.useOperationIdAsQueryKey)\n ? {}\n : {\n useOperationIdAsQueryKey: globalOptions.useOperationIdAsQueryKey,\n }),\n ...(isNullish(queryOptions.useOperationIdAsQueryKey)\n ? {}\n : { useOperationIdAsQueryKey: queryOptions.useOperationIdAsQueryKey }),\n ...(isNullish(globalOptions.signal)\n ? {}\n : {\n signal: globalOptions.signal,\n }),\n ...(isNullish(queryOptions.signal) ? {} : { signal: queryOptions.signal }),\n ...(isNullish(globalOptions.version)\n ? {}\n : {\n version: globalOptions.version,\n }),\n ...(isNullish(queryOptions.version)\n ? {}\n : { version: queryOptions.version }),\n ...(queryOptions.mutationInvalidates\n ? { mutationInvalidates: queryOptions.mutationInvalidates }\n : {}),\n ...(isNullish(globalOptions.runtimeValidation)\n ? {}\n : {\n runtimeValidation: globalOptions.runtimeValidation,\n }),\n ...(isNullish(queryOptions.runtimeValidation)\n ? {}\n : { runtimeValidation: queryOptions.runtimeValidation }),\n };\n}\n\nexport function getDefaultFilesHeader({\n title,\n description,\n version,\n}: {\n title?: string;\n description?: string;\n version?: string;\n} = {}) {\n return [\n `Generated by ${pkg.name} v${pkg.version} 🍺`,\n `Do not edit manually.`,\n ...(title ? [title] : []),\n ...(description ? [description] : []),\n ...(version ? [`OpenAPI spec version: ${version}`] : []),\n ];\n}\n","import { isBoolean, log, logError } from '@orval/core';\n\n/**\n * Start a file watcher and invoke an async callback on file changes.\n *\n * If `watchOptions` is falsy the watcher is not started. Supported shapes:\n * - boolean: when true the `defaultTarget` is watched\n * - string: a single path to watch\n * - string[]: an array of paths to watch\n *\n * @param watchOptions - false to disable watching, or a path/paths to watch\n * @param watchFn - async callback executed on change events\n * @param defaultTarget - path(s) to watch when `watchOptions` is `true` (default: '.')\n * @returns Resolves once the watcher has been started (or immediately if disabled)\n *\n * @example\n * await startWatcher(true, async () => { await buildProject(); }, 'src');\n */\nexport async function startWatcher(\n watchOptions: boolean | string | string[],\n watchFn: () => Promise<void>,\n defaultTarget: string | string[] = '.',\n) {\n if (!watchOptions) return;\n const { watch } = await import('chokidar');\n\n const ignored = ['**/{.git,node_modules}/**'];\n\n const watchPaths = isBoolean(watchOptions) ? defaultTarget : watchOptions;\n\n log(\n `Watching for changes in ${\n Array.isArray(watchPaths)\n ? watchPaths.map((v) => '\"' + v + '\"').join(' | ')\n : '\"' + watchPaths + '\"'\n }`,\n );\n\n const watcher = watch(watchPaths, {\n ignorePermissionErrors: true,\n ignored,\n });\n watcher.on('ready', () => {\n log('Initial scan complete. Watching for changes...');\n watcher.on('all', (type, file) => {\n log(`Change detected: ${type} ${file}`);\n\n watchFn().catch((error: unknown) => {\n logError(error);\n });\n });\n });\n}\n","import type { ContextSpec, GeneratorMutator, ZodCoerceType } from '@orval/core';\nimport { getRefInfo } from '@orval/core';\nimport {\n generateZodValidationSchemaDefinition,\n parseZodValidationSchemaDefinition,\n} from '@orval/zod';\nimport type { OpenAPIV3_1 } from '@scalar/openapi-types';\n\n/**\n * Resolve the export identifier for a `#/components/schemas/X` ref. We reuse\n * `@orval/core`'s `getRefInfo(...).name` (`pascal` + sanitize + component\n * suffix) so reusable zod schema exports match the operation wrappers and the\n * TS model types exactly. `namingConvention` deliberately does NOT influence\n * the identifier — it governs file names only, consistent with the rest of\n * orval. The same call powers the generator's `namedRef` emission, so the\n * definition name and every reference stay in sync.\n */\nexport const resolveSchemaName = (ref: string, context: ContextSpec): string =>\n getRefInfo(ref, context).name;\n\n/**\n * Resolve names for a set of refs, throwing on conflicts (two distinct refs\n * collapsing to the same identifier). The mapping is the single source of\n * truth for cross-schema references — the generator, the orchestrator's graph,\n * and the sentinel rewriter all consult it.\n */\nexport const resolveSchemaNames = (\n refs: readonly string[],\n context: ContextSpec,\n): Map<string, string> => {\n const resolved = new Map<string, string>();\n const reverse = new Map<string, string>();\n\n for (const ref of refs) {\n const name = resolveSchemaName(ref, context);\n const previous = reverse.get(name);\n if (previous !== undefined && previous !== ref) {\n throw new Error(\n `[orval/zod] generateReusableSchemas: refs ${previous} and ${ref} ` +\n `both resolve to the export name \"${name}\". ` +\n `Rename one in the OpenAPI source.`,\n );\n }\n resolved.set(ref, name);\n reverse.set(name, ref);\n }\n\n return resolved;\n};\n\nconst COMPONENT_SCHEMAS_PREFIX = '#/components/schemas/';\n\nconst isComponentSchemaRef = (ref: unknown): ref is string =>\n typeof ref === 'string' && ref.startsWith(COMPONENT_SCHEMAS_PREFIX);\n\n/**\n * Walk a value (object or array) and accumulate every component-schema `$ref`\n * found anywhere in the subtree. Pure spec traversal — does NOT invoke the\n * Zod generator.\n */\nconst collectRefsInValue = (value: unknown, refs: Set<string>): void => {\n if (value === null || typeof value !== 'object') {\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n collectRefsInValue(item, refs);\n }\n return;\n }\n const record = value as Record<string, unknown>;\n if (isComponentSchemaRef(record.$ref)) {\n refs.add(record.$ref);\n }\n for (const key of Object.keys(record)) {\n if (key === '$ref') continue; // already added; don't descend into the string\n collectRefsInValue(record[key], refs);\n }\n};\n\n/**\n * Returns the set of component-schema refs reachable from `spec.paths`,\n * following refs transitively through `spec.components.schemas`.\n */\nexport const collectReachableComponentRefs = (\n spec: OpenAPIV3_1.Document,\n): Set<string> => {\n const reachable = new Set<string>();\n const queue: string[] = [];\n\n const initial = new Set<string>();\n collectRefsInValue(spec.paths, initial);\n for (const ref of initial) {\n reachable.add(ref);\n queue.push(ref);\n }\n\n const componentSchemas = spec.components?.schemas ?? {};\n // Index-based queue iteration (not `shift()`) so the BFS is O(n) rather than\n // O(n²). The queue is append-only — we never need to reclaim the head slot.\n for (const currentRef of queue) {\n const schemaName = currentRef.slice(COMPONENT_SCHEMAS_PREFIX.length);\n const targetSchema = componentSchemas[schemaName];\n if (!targetSchema) continue;\n\n const innerRefs = new Set<string>();\n collectRefsInValue(targetSchema, innerRefs);\n for (const innerRef of innerRefs) {\n if (!reachable.has(innerRef)) {\n reachable.add(innerRef);\n queue.push(innerRef);\n }\n }\n }\n\n return reachable;\n};\n\nexport interface ReusableSchemaEntry {\n ref: string;\n name: string;\n zod: string;\n consts: string;\n usedRefs: Set<string>;\n /**\n * True when this schema references itself directly or transitively (its node\n * sits in a cycle: an SCC of size > 1, or a self-loop). Such a schema is\n * emitted as a recursive `const` that reads its own binding inside its\n * initializer, so the writer must give it an explicit type annotation\n * (`const X: zod.ZodType<X>`) to avoid TS7022. Set by\n * {@link rewriteReusableSchemas}; `undefined`/`false` for acyclic schemas.\n */\n isRecursive?: boolean;\n}\n\nexport interface GenerateReusableSchemaSetOptions {\n strict: boolean;\n isZodV4: boolean;\n coerce?: boolean | ZodCoerceType[];\n /** Emit `.meta({ id, ... })` on each schema (zod v4). See `ZodOptions.generateMeta`. */\n generateMeta?: boolean;\n /**\n * When set, the user's `override.zod.params` mutator is invoked for every\n * leaf validator inside each emitted component schema with a `'schema'`\n * location and an empty `operationId` (component schemas are shared across\n * operations). Consumers can branch on `ctx.location === 'schema'` to vary\n * the injected params for shared definitions.\n */\n paramsMutator?: GeneratorMutator;\n}\n\n/**\n * For each component-schema ref, run the Zod generator + parser with\n * `useReusableSchemas: true`. The resulting `zod` strings contain\n * `__REF_<name>__` sentinels at every site that references another schema;\n * the SCC step (Task 10) decides whether each sentinel becomes a direct\n * identifier or a `z.lazy(() => Name)` wrapper.\n */\nexport const generateReusableSchemaSet = (\n refs: readonly string[],\n context: ContextSpec,\n options: GenerateReusableSchemaSetOptions,\n): ReusableSchemaEntry[] => {\n const componentSchemas = context.spec.components?.schemas ?? {};\n\n // Map convention-applied export name → source ref, so when a generated\n // schema references another component schema via its `usedRefs` name we\n // can find which `$ref` to add to the work queue.\n const nameToRef = new Map<string, string>();\n for (const schemaName of Object.keys(componentSchemas)) {\n const ref = `#/components/schemas/${schemaName}`;\n nameToRef.set(resolveSchemaName(ref, context), ref);\n }\n\n // Expand to the transitive closure of component-schema refs reachable from\n // the initial roots. Without this, a generated schema could emit a sentinel\n // for a ref that's not in our entries → the rewriter would render a bare\n // identifier with no corresponding `export const`. Iterate until stable.\n const queue = [...refs];\n const seen = new Set<string>(refs);\n const entries: ReusableSchemaEntry[] = [];\n\n for (const ref of queue) {\n const schemaName = ref.slice('#/components/schemas/'.length);\n const schema = componentSchemas[schemaName];\n if (!schema) continue;\n\n const name = resolveSchemaName(ref, context);\n\n const definition = generateZodValidationSchemaDefinition(\n schema,\n context,\n name,\n options.strict,\n options.isZodV4,\n {\n required: true,\n useReusableSchemas: true,\n emitMeta: options.generateMeta,\n },\n );\n\n const parsed = parseZodValidationSchemaDefinition(\n definition,\n context,\n options.coerce ?? false,\n options.strict,\n options.isZodV4,\n undefined,\n options.paramsMutator\n ? {\n mutator: options.paramsMutator,\n operationId: '',\n location: 'schema',\n schemaName: name,\n }\n : undefined,\n );\n\n entries.push({\n ref,\n name,\n zod: parsed.zod,\n consts: parsed.consts,\n usedRefs: parsed.usedRefs,\n });\n\n for (const usedName of parsed.usedRefs) {\n const usedRef = nameToRef.get(usedName);\n if (usedRef !== undefined && !seen.has(usedRef)) {\n seen.add(usedRef);\n queue.push(usedRef);\n }\n }\n }\n\n return entries;\n};\n\ntype Graph = ReadonlyMap<string, ReadonlySet<string>>;\n\nconst edgeKey = (from: string, to: string): string => `${from}->${to}`;\n\n/**\n * Tarjan's SCC. Returns SCCs as arrays of node ids, in reverse topological\n * order (deepest SCC first). Self-loops form their own size-1 SCC; non-cyclic\n * nodes are size-1 SCCs without a self-loop.\n */\ninterface TarjanResult {\n /**\n * SCCs in reverse topological order (deepest first). Within an SCC the\n * nodes are in REVERSE DFS finish order — emit in this order and every\n * non-lazy edge points to an already-emitted node, avoiding TDZ.\n */\n sccs: string[][];\n /** Back-edges discovered during DFS, keyed as \"from->to\". Plus self-loops. */\n lazyEdges: Set<string>;\n}\n\nconst tarjan = (graph: Graph): TarjanResult => {\n let index = 0;\n const stack: string[] = [];\n const onStack = new Set<string>();\n const indices = new Map<string, number>();\n const lowlinks = new Map<string, number>();\n const sccs: string[][] = [];\n const lazyEdges = new Set<string>();\n\n const strongconnect = (v: string): void => {\n indices.set(v, index);\n lowlinks.set(v, index);\n index += 1;\n stack.push(v);\n onStack.add(v);\n\n const neighbors = graph.get(v) ?? new Set<string>();\n for (const w of neighbors) {\n if (v === w) {\n // Self-loop: always lazy.\n lazyEdges.add(edgeKey(v, w));\n continue;\n }\n if (!indices.has(w)) {\n strongconnect(w);\n lowlinks.set(v, Math.min(lowlinks.get(v) ?? -1, lowlinks.get(w) ?? -1));\n } else if (onStack.has(w)) {\n // Back-edge: w is an ancestor in the DFS tree. v and w belong to\n // the same SCC and the edge v→w closes a cycle — emit it lazy so\n // the runtime initializer doesn't read w in its TDZ.\n lazyEdges.add(edgeKey(v, w));\n lowlinks.set(v, Math.min(lowlinks.get(v) ?? -1, indices.get(w) ?? -1));\n }\n }\n\n if (lowlinks.get(v) === indices.get(v)) {\n const scc: string[] = [];\n let w: string | undefined;\n do {\n w = stack.pop();\n if (w === undefined) break;\n onStack.delete(w);\n scc.push(w);\n } while (w !== v);\n sccs.push(scc);\n }\n };\n\n for (const node of graph.keys()) {\n if (!indices.has(node)) {\n strongconnect(node);\n }\n }\n\n return { sccs, lazyEdges };\n};\n\n/**\n * Returns the set of lazy-emission edge keys (\"from->to\") for `graph`. Back-edges\n * (edges from a node to an ancestor in the DFS tree) and self-loops are lazy.\n * Cross-SCC edges and tree/forward edges within an SCC are not lazy.\n */\nexport const computeLazyEdges = (graph: Graph): Set<string> =>\n tarjan(graph).lazyEdges;\n\nconst SENTINEL_PATTERN = /__REF_([A-Za-z_$][A-Za-z0-9_$]*)__/g;\n\n/**\n * Replace every `__REF_<name>__` sentinel with the bare identifier. Use this\n * for schemas that sit at the top of the dependency graph (operation params,\n * bodies, responses) — they can never participate in a cycle with the\n * component schemas they reference, so every ref is a direct (non-lazy) one.\n */\nexport const rewriteSentinelsToDirect = (zod: string): string =>\n zod.replaceAll(SENTINEL_PATTERN, (_match, refName: string) => refName);\n\n/**\n * Replace every `__REF_<name>__` sentinel with either the bare identifier or\n * `zod.lazy(() => <name>)` based on whether the edge closes a cycle, then\n * reorder entries so that every non-lazy reference is emitted AFTER its\n * target. This avoids TDZ errors at module load.\n *\n * Entries that sit in a cycle (SCC of size > 1, or a self-loop) are flagged\n * `isRecursive`. Their generated `const` reads its own binding inside the\n * initializer (through the `zod.lazy` wrapper), which TypeScript rejects with\n * TS7022 (\"'X' implicitly has type 'any' ... referenced directly or indirectly\n * in its own initializer\") unless the `const` carries an explicit type\n * annotation. The writer (`write-zod-specs`) supplies that annotation —\n * `const X: zod.ZodType<X>` — backed by a generated TS type, which both\n * silences TS7022 and preserves full `z.infer` typing through the recursion.\n *\n * Both the lazy classification and the emit order come from a single Tarjan\n * run, guaranteeing they agree: a non-lazy edge u→v means v is visited (and\n * popped) before u in DFS, so v appears earlier in the SCC array → emitted\n * before u → safe.\n */\nexport const rewriteReusableSchemas = (\n entries: readonly ReusableSchemaEntry[],\n): ReusableSchemaEntry[] => {\n const graph = new Map<string, Set<string>>(\n entries.map((e) => [e.name, new Set(e.usedRefs)] as const),\n );\n // Ensure all referenced names exist as nodes (even if no entry — guards against\n // forgotten roots; the renderer will still emit valid code, just with a dangling\n // ref the user can debug).\n for (const e of entries) {\n for (const ref of e.usedRefs) {\n if (!graph.has(ref)) graph.set(ref, new Set());\n }\n }\n\n const { sccs, lazyEdges } = tarjan(graph);\n\n // A node is recursive iff it sits in a cycle: either an SCC with more than\n // one member (mutual recursion), or a single-node SCC that has a self-loop.\n const recursiveNames = new Set<string>();\n for (const scc of sccs) {\n if (scc.length > 1) {\n for (const name of scc) recursiveNames.add(name);\n } else if (lazyEdges.has(edgeKey(scc[0], scc[0]))) {\n recursiveNames.add(scc[0]);\n }\n }\n\n const rewritten = new Map(\n entries.map((entry) => {\n const newZod = entry.zod.replaceAll(\n SENTINEL_PATTERN,\n (_match, refName: string) => {\n const isLazy = lazyEdges.has(edgeKey(entry.name, refName));\n return isLazy ? `zod.lazy(() => ${refName})` : refName;\n },\n );\n return [\n entry.name,\n { ...entry, zod: newZod, isRecursive: recursiveNames.has(entry.name) },\n ] as const;\n }),\n );\n\n // Tarjan returns SCCs in reverse topological order (deepest first) and\n // within each SCC the nodes are popped in REVERSE DFS-finish order — i.e.\n // descendants first, SCC root last. That's exactly the order we want to\n // emit: every non-lazy edge points to an already-emitted node.\n const out: ReusableSchemaEntry[] = [];\n for (const scc of sccs) {\n for (const name of scc) {\n const entry = rewritten.get(name);\n if (entry !== undefined) out.push(entry);\n }\n }\n return out;\n};\n","import path from 'node:path';\n\nimport {\n type ContextSpec,\n conventionName,\n type GeneratorMutator,\n getRefInfo,\n isComponentRef,\n type NamingConvention,\n type NormalizedOutputOptions,\n type OpenApiParameterObject,\n type OpenApiReferenceObject,\n type OpenApiRequestBodyObject,\n type OpenApiSchemaObject,\n pascal,\n resolveValue,\n type ZodCoerceType,\n} from '@orval/core';\nimport {\n dereference,\n generateFormDataZodSchema,\n generateZodValidationSchemaDefinition,\n isZodVersionV4,\n parseZodValidationSchemaDefinition,\n type ZodValidationSchemaDefinition,\n} from '@orval/zod';\nimport fs from 'fs-extra';\n\nimport {\n generateReusableSchemaSet,\n resolveSchemaName,\n resolveSchemaNames,\n type ReusableSchemaEntry,\n rewriteReusableSchemas,\n rewriteSentinelsToDirect,\n} from './reusable-schemas';\n\ninterface ZodSchemaFileEntry {\n schemaName: string;\n consts: string;\n zodExpression: string;\n /** Pre-rendered `import { x } from './x'` lines for reusable-schema refs. */\n importStatements?: string[];\n}\n\ntype ZodSchemaFileToWrite = ZodSchemaFileEntry & {\n filePath: string;\n};\n\ninterface WriteZodOutputOptions {\n namingConvention: NamingConvention;\n indexFiles: boolean;\n packageJson?: NormalizedOutputOptions['packageJson'];\n override: {\n zod: {\n strict: {\n body: boolean;\n };\n generate: {\n param: boolean;\n query: boolean;\n header: boolean;\n body: boolean;\n response: boolean;\n };\n coerce: {\n body: boolean | ZodCoerceType[];\n };\n generateReusableSchemas?: boolean;\n generateMeta?: boolean;\n };\n };\n}\n\ninterface WriteZodSchemasInput {\n spec: ContextSpec['spec'];\n target: string;\n schemas: {\n name: string;\n schema?: OpenApiSchemaObject | OpenApiReferenceObject;\n }[];\n}\n\ninterface WriteZodVerbResponseType {\n value: string;\n isRef?: boolean;\n originalSchema?: OpenApiSchemaObject;\n}\n\ninterface WriteZodSchemasFromVerbsEntry {\n operationName: string;\n originalOperation: {\n requestBody?: OpenApiRequestBodyObject | OpenApiReferenceObject;\n parameters?: (OpenApiParameterObject | OpenApiReferenceObject)[];\n };\n response: {\n types: {\n success: WriteZodVerbResponseType[];\n errors: WriteZodVerbResponseType[];\n };\n };\n override?: {\n zod: {\n generate: WriteZodOutputOptions['override']['zod']['generate'];\n };\n };\n}\n\ntype WriteZodSchemasFromVerbsInput = Record<\n string,\n WriteZodSchemasFromVerbsEntry\n>;\n\ninterface WriteZodSchemasFromVerbsContext {\n output: {\n override: {\n useDates?: NormalizedOutputOptions['override']['useDates'];\n zod: Pick<\n NormalizedOutputOptions['override']['zod'],\n 'dateTimeOptions' | 'timeOptions'\n >;\n };\n };\n spec: ContextSpec['spec'];\n target: string;\n workspace: string;\n}\n\n/**\n * Render the `import { ... } from '...'` line for a resolved\n * `GeneratorMutator`. Mirrors the format produced by\n * `generateMutatorImports` in `@orval/core` but inlined to avoid pulling in\n * its full surface area for a single statement.\n */\nfunction buildMutatorImportStatement(mutator: GeneratorMutator): string {\n const importClause = mutator.default ? mutator.name : `{ ${mutator.name} }`;\n return `import ${importClause} from '${mutator.path}';`;\n}\n\n/**\n * Whole-word substring check for a resolved mutator alias inside generated\n * code. Plain `String.includes` would false-positive when the user names the\n * mutator something like `min` against `.min(1)`.\n */\nfunction bodyReferencesMutator(\n body: string,\n mutator: GeneratorMutator,\n): boolean {\n return new RegExp(String.raw`\\b${mutator.name}\\b`).test(body);\n}\n\nfunction generateZodSchemaFileContent(\n header: string,\n schemas: ZodSchemaFileEntry[],\n // Omit the `import { z as zod }` line when the content is concatenated into a\n // file that already imports zod (e.g. inline single-mode output, where the\n // zod client already emits `import * as zod from 'zod'`).\n includeZodImport = true,\n): string {\n // Group the zod import with any reusable-schema imports (deduped across the\n // usually-single entries written to this file), then separate that block\n // from the schema content with a single blank line.\n const refImports = [\n ...new Set(schemas.flatMap((s) => s.importStatements ?? [])),\n ].toSorted();\n const importBlock = [\n ...(includeZodImport ? [`import { z as zod } from 'zod';`] : []),\n ...refImports,\n ].join('\\n');\n\n const schemaContent = schemas\n .map(({ schemaName, consts, zodExpression }) => {\n const schemaConsts = consts ? `${consts}\\n` : '';\n\n return `${schemaConsts}export const ${schemaName} = ${zodExpression}\n\nexport type ${schemaName} = zod.input<typeof ${schemaName}>;\nexport type ${schemaName}Output = zod.output<typeof ${schemaName}>;`;\n })\n .join('\\n\\n');\n\n const separator = importBlock ? `${importBlock}\\n\\n` : '';\n return `${header}${separator}${schemaContent}\\n`;\n}\n\n/**\n * Render a single reusable-schema entry's exports (`const` + companion type\n * aliases), shared by the inline single-file and per-file reusable writers.\n *\n * Acyclic schemas keep the original form, deriving the public type from the\n * schema (`zod.input<typeof X>`). Recursive schemas can't: the `const` reads\n * its own binding inside its initializer, so TypeScript can't infer it and a\n * bare `zod.input<typeof X>` would itself be circular. We instead generate the\n * recursive TS type with orval's own model generator (`resolveValue`, the same\n * path that produces `export type X` in the model output, so names line up via\n * `getRefInfo`) and pin the schema to it: `const X: zod.ZodType<X>`. That\n * annotation breaks the self-inference cycle AND preserves full `z.infer`\n * typing through the recursion (instead of collapsing recursive positions to\n * `unknown`).\n */\n/**\n * One sibling import the recursive TS type body needs. `name` is the export\n * name in the sibling file (also the basis for the filename); `alias`, when\n * set, is the local binding in this file — emitted as\n * `import { name as alias } from ...`. The aliasing path is triggered by\n * `generateInterface`'s self-name disambiguation (`<X>Bis`); recursive\n * component bodies don't exercise it today but the writer carries `alias`\n * through so any future producer Just Works.\n */\ninterface ExtraImport {\n name: string;\n alias?: string;\n}\n\ninterface RenderedReusableSchemaEntry {\n content: string;\n /**\n * Imports this entry needs that are NOT already captured in `entry.usedRefs`.\n * Recursive entries render a TypeScript type body via the model generator;\n * names the type body references (e.g. an `AssetRelationType` used as a\n * `Record<>` key from `propertyNames`) won't appear in `usedRefs` because\n * the zod runtime collapses them (record keys become `zod.string()`). The\n * split-mode writer merges these into its per-file import list so the\n * emitted TS type compiles. Empty for acyclic entries.\n */\n extraImports: ExtraImport[];\n}\n\nfunction renderReusableSchemaEntry(\n entry: ReusableSchemaEntry,\n context: ContextSpec,\n): RenderedReusableSchemaEntry {\n const consts = entry.consts ? `${entry.consts}\\n\\n` : '';\n\n if (entry.isRecursive) {\n // Resolve the lookup key through `getRefInfo` (the same util every other\n // ref consumer uses) rather than slicing the prefix off `entry.ref` by\n // hand: it guards the `#/components/schemas/` prefix via `isComponentRef`\n // and decodes JSON Pointer escapes (`~1`→`/`, `~0`→`~`) before indexing\n // `components.schemas`. `originalName` is the decoded final segment, which\n // matches the raw `components.schemas` key.\n const rawName = isComponentRef(entry.ref)\n ? getRefInfo(entry.ref, context).originalName\n : undefined;\n const schema = rawName\n ? (context.spec.components?.schemas?.[rawName] as\n | OpenApiSchemaObject\n | OpenApiReferenceObject\n | undefined)\n : undefined;\n const resolved = schema\n ? resolveValue({ schema, name: entry.name, context })\n : undefined;\n const typeBody = resolved ? resolved.value : 'unknown';\n // Dedupe by local binding name (`alias ?? name`). When `resolveValue`\n // surfaces the same component twice — e.g. once aliased, once not —\n // collapsing on the binding key keeps both the file's import list and the\n // generated TS body internally consistent.\n const seen = new Set<string>();\n const extraImports: ExtraImport[] = [];\n for (const imp of resolved?.imports ?? []) {\n if (!imp.name || imp.name === entry.name) continue;\n const bindingKey = imp.alias ?? imp.name;\n if (seen.has(bindingKey)) continue;\n seen.add(bindingKey);\n extraImports.push({\n name: imp.name,\n ...(imp.alias ? { alias: imp.alias } : {}),\n });\n }\n\n return {\n content:\n `${consts}export type ${entry.name} = ${typeBody};\\n\\n` +\n `export const ${entry.name}: zod.ZodType<${entry.name}> = ${entry.zod};\\n\\n` +\n `export type ${entry.name}Output = zod.output<typeof ${entry.name}>;`,\n extraImports,\n };\n }\n\n return {\n content:\n `${consts}export const ${entry.name} = ${entry.zod};\\n\\n` +\n `export type ${entry.name} = zod.input<typeof ${entry.name}>;\\n` +\n `export type ${entry.name}Output = zod.output<typeof ${entry.name}>;`,\n extraImports: [],\n };\n}\n\nconst isValidSchemaIdentifier = (name: string) =>\n /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);\n\n/**\n * Build the sibling-file `import { … } from './…'` block for one reusable\n * schema file. Two sources feed in:\n * - `usedRefs` — names from the zod runtime expression. Sourced from the\n * sentinel parser, so always unaliased.\n * - `extraImports` — names the recursive TS body needs that the zod runtime\n * collapsed (`propertyNames` $refs, etc.). May carry `alias`.\n * Keyed by export name (`name`) so an aliased `extraImports` entry overrides\n * a bare `usedRefs` entry — the recursive TS body uses the local binding, so\n * the aliased form has to win for the file to compile. Self-refs and\n * non-component identifiers are filtered out.\n *\n * Exported for unit-test coverage of the alias-propagation path; no\n * `resolveValue` producer surfaces aliases here today, so the integration\n * tests can't exercise it.\n */\nexport function buildSiblingImports({\n usedRefs,\n extraImports,\n entryName,\n componentNames,\n namingConvention,\n importExt,\n}: {\n usedRefs: Iterable<string>;\n extraImports: readonly ExtraImport[];\n entryName: string;\n componentNames: ReadonlySet<string>;\n namingConvention: NamingConvention;\n importExt: string;\n}): string {\n const importsByName = new Map<string, ExtraImport>();\n for (const name of usedRefs) {\n if (name === entryName) continue;\n importsByName.set(name, { name });\n }\n for (const imp of extraImports) {\n if (imp.name === entryName || !componentNames.has(imp.name)) continue;\n importsByName.set(imp.name, imp);\n }\n return [...importsByName.values()]\n .toSorted((a, b) => a.name.localeCompare(b.name))\n .map(({ name, alias }) => {\n const importedFile = conventionName(name, namingConvention);\n const spec = alias ? `${name} as ${alias}` : name;\n return `import { ${spec} } from './${importedFile}${importExt}';`;\n })\n .join('\\n');\n}\n\nconst isPrimitiveSchemaName = (name: string) =>\n ['string', 'number', 'boolean', 'void', 'unknown', 'Blob'].includes(name);\n\nconst dedupeSchemasByName = <T extends { name: string }>(schemas: T[]) => {\n const uniqueSchemas = new Map<string, T>();\n\n for (const schema of schemas) {\n if (!uniqueSchemas.has(schema.name)) {\n uniqueSchemas.set(schema.name, schema);\n }\n }\n\n return [...uniqueSchemas.values()];\n};\n\nconst groupSchemasByFilePath = <T extends { filePath: string }>(\n schemas: T[],\n) => {\n const grouped = new Map<string, T[]>();\n\n for (const schema of schemas) {\n const key = schema.filePath.toLowerCase();\n const existingGroup = grouped.get(key);\n\n if (existingGroup) {\n existingGroup.push(schema);\n } else {\n grouped.set(key, [schema]);\n }\n }\n\n const sortedGroups = [...grouped.values()].map((group) =>\n [...group].toSorted((a, b) =>\n a.filePath.localeCompare(b.filePath, 'en', { numeric: true }),\n ),\n );\n\n return sortedGroups.toSorted((a, b) =>\n a[0].filePath.localeCompare(b[0].filePath, 'en', { numeric: true }),\n );\n};\n\nasync function writeZodSchemaIndex(\n schemasPath: string,\n fileExtension: string,\n header: string,\n schemaNames: string[],\n namingConvention: NamingConvention,\n shouldMergeExisting = false,\n) {\n const importFileExtension = fileExtension.replace(/\\.ts$/, '');\n const indexPath = path.join(schemasPath, `index.ts`);\n\n let existingExports = '';\n if (shouldMergeExisting && (await fs.pathExists(indexPath))) {\n const existingContent = await fs.readFile(indexPath, 'utf8');\n const headerMatch = /^(\\/\\*\\*[\\s\\S]*?\\*\\/\\n)?/.exec(existingContent);\n const headerPart = headerMatch ? headerMatch[0] : '';\n existingExports = existingContent.slice(headerPart.length).trim();\n }\n\n const newExports = schemaNames\n .map((schemaName) => {\n const fileName = conventionName(schemaName, namingConvention);\n return `export * from './${fileName}${importFileExtension}';`;\n })\n .toSorted()\n .join('\\n');\n\n const allExports = existingExports\n ? `${existingExports}\\n${newExports}`\n : newExports;\n\n const uniqueExports = [...new Set(allExports.split('\\n'))]\n .filter((line) => line.trim())\n .toSorted()\n .join('\\n');\n\n await fs.outputFile(indexPath, `${header}\\n${uniqueExports}\\n`);\n}\n\nexport function generateZodSchemasInline(\n builder: WriteZodSchemasInput,\n output: WriteZodOutputOptions,\n includeZodImport = true,\n paramsMutator?: GeneratorMutator,\n includeParamsImport = false,\n): string {\n const useReusableSchemas =\n output.override.zod.generateReusableSchemas === true;\n\n if (useReusableSchemas) {\n return generateZodSchemasInlineReusable(\n builder,\n output,\n includeZodImport,\n paramsMutator,\n includeParamsImport,\n );\n }\n\n const schemasWithOpenApiDef = builder.schemas.filter((s) => s.schema);\n\n if (schemasWithOpenApiDef.length === 0) {\n return '';\n }\n\n const isZodV4 = !!output.packageJson && isZodVersionV4(output.packageJson);\n const strict = output.override.zod.strict.body;\n const coerce = output.override.zod.coerce.body;\n const schemas: ZodSchemaFileEntry[] = [];\n\n for (const { name, schema: schemaObject } of schemasWithOpenApiDef) {\n if (!schemaObject) {\n continue;\n }\n\n const context: ContextSpec = {\n spec: builder.spec,\n target: builder.target,\n workspace: '',\n output: output as ContextSpec['output'],\n };\n\n const dereferencedSchema = dereference(schemaObject, context);\n\n const zodDefinition = generateZodValidationSchemaDefinition(\n dereferencedSchema,\n context,\n name,\n strict,\n isZodV4,\n {\n required: true,\n emitMeta: output.override.zod.generateMeta,\n },\n );\n\n const parsedZodDefinition = parseZodValidationSchemaDefinition(\n zodDefinition,\n context,\n coerce,\n strict,\n isZodV4,\n );\n\n schemas.push({\n schemaName: name,\n consts: parsedZodDefinition.consts,\n zodExpression: parsedZodDefinition.zod,\n });\n }\n\n if (schemas.length === 0) {\n return '';\n }\n\n return generateZodSchemaFileContent('', schemas, includeZodImport);\n}\n\nfunction generateZodSchemasInlineReusable(\n builder: WriteZodSchemasInput,\n output: WriteZodOutputOptions,\n includeZodImport = true,\n paramsMutator?: GeneratorMutator,\n includeParamsImport = false,\n): string {\n const isZodV4 = !!output.packageJson && isZodVersionV4(output.packageJson);\n const strict = output.override.zod.strict.body;\n const coerce = output.override.zod.coerce.body;\n const context: ContextSpec = {\n spec: builder.spec,\n target: builder.target,\n workspace: '',\n output: output as ContextSpec['output'],\n };\n\n // Seed from the RAW `components.schemas` keys, NOT `builder.schemas` (whose\n // `name` is the *sanitized* model identifier, e.g. `__schema0` -> `_Schema0`).\n // Building a ref from a sanitized name yields `#/components/schemas/_Schema0`,\n // which doesn't exist in `components.schemas`, so the schema was silently\n // dropped whenever it was reachable only from operations (when referenced by\n // another component schema it survived via transitive expansion, masking the\n // bug). Mirrors `writeZodSchemasReusable`, which already seeds from raw keys.\n const componentSchemas = (builder.spec.components?.schemas ?? {}) as Record<\n string,\n unknown\n >;\n const refs = Object.keys(componentSchemas).map(\n (schemaName) => `#/components/schemas/${schemaName}`,\n );\n if (refs.length === 0) return '';\n\n resolveSchemaNames(refs, context);\n\n const entries = generateReusableSchemaSet(refs, context, {\n strict,\n isZodV4,\n coerce,\n generateMeta: output.override.zod.generateMeta,\n paramsMutator,\n });\n\n const rewritten = rewriteReusableSchemas(entries);\n\n // Single-file inline mode emits every component schema in one file, so\n // recursive entries' TS-type references resolve in-file with no extra\n // imports — discard `extraImports` here.\n const body = rewritten\n .map((entry) => renderReusableSchemaEntry(entry, context).content)\n .join('\\n\\n');\n\n // Omit the zod import when concatenated into a file that already imports it\n // (inline single-mode output where the zod client emits `import * as zod`).\n const zodImport = includeZodImport ? `import { z as zod } from 'zod';\\n` : '';\n // In split modes (`split` / `tags-split`) the inline schemas are written to\n // a separate `.schemas` file with no other imports, so the params-mutator\n // import has to be emitted here. In `single` / `tags` modes the schemas are\n // concatenated into the operation file, which already imports the same\n // mutator via its per-verb mutators array (see `generateZodRoute`) — we\n // skip emitting it again to avoid a duplicate import line.\n const paramsImport =\n paramsMutator &&\n includeParamsImport &&\n bodyReferencesMutator(body, paramsMutator)\n ? `${buildMutatorImportStatement(paramsMutator)}\\n`\n : '';\n const prefix =\n zodImport || paramsImport ? `${zodImport}${paramsImport}\\n` : '';\n return `${prefix}${body}\\n`;\n}\n\nexport async function writeZodSchemas(\n builder: WriteZodSchemasInput,\n schemasPath: string,\n fileExtension: string,\n header: string,\n output: WriteZodOutputOptions,\n paramsMutator?: GeneratorMutator,\n) {\n const useReusableSchemas = output.override.zod.generateReusableSchemas;\n\n if (useReusableSchemas) {\n await writeZodSchemasReusable(\n builder,\n schemasPath,\n fileExtension,\n header,\n output,\n paramsMutator,\n );\n return;\n }\n\n const schemasWithOpenApiDef = builder.schemas.filter((s) => s.schema);\n const schemasToWrite: ZodSchemaFileToWrite[] = [];\n const isZodV4 = !!output.packageJson && isZodVersionV4(output.packageJson);\n const strict = output.override.zod.strict.body;\n const coerce = output.override.zod.coerce.body;\n\n for (const generatorSchema of schemasWithOpenApiDef) {\n const { name, schema: schemaObject } = generatorSchema;\n\n if (!schemaObject) {\n continue;\n }\n\n const fileName = conventionName(name, output.namingConvention);\n const filePath = path.join(schemasPath, `${fileName}${fileExtension}`);\n const context: ContextSpec = {\n spec: builder.spec,\n target: builder.target,\n workspace: '',\n output: output as ContextSpec['output'],\n };\n\n // Dereference the schema to resolve $ref\n const dereferencedSchema = dereference(schemaObject, context);\n\n const zodDefinition = generateZodValidationSchemaDefinition(\n dereferencedSchema,\n context,\n name,\n strict,\n isZodV4,\n {\n required: true,\n emitMeta: output.override.zod.generateMeta,\n },\n );\n\n const parsedZodDefinition = parseZodValidationSchemaDefinition(\n zodDefinition,\n context,\n coerce,\n strict,\n isZodV4,\n );\n\n schemasToWrite.push({\n schemaName: name,\n filePath,\n consts: parsedZodDefinition.consts,\n zodExpression: parsedZodDefinition.zod,\n });\n }\n\n const groupedSchemasToWrite = groupSchemasByFilePath(schemasToWrite);\n\n for (const schemaGroup of groupedSchemasToWrite) {\n const fileContent = generateZodSchemaFileContent(header, schemaGroup);\n\n await fs.outputFile(schemaGroup[0].filePath, fileContent);\n }\n\n if (output.indexFiles) {\n const schemaNames = groupedSchemasToWrite.map(\n (schemaGroup) => schemaGroup[0].schemaName,\n );\n await writeZodSchemaIndex(\n schemasPath,\n fileExtension,\n header,\n schemaNames,\n output.namingConvention,\n false,\n );\n }\n}\n\nasync function writeZodSchemasReusable(\n builder: WriteZodSchemasInput,\n schemasPath: string,\n fileExtension: string,\n header: string,\n output: WriteZodOutputOptions,\n paramsMutator?: GeneratorMutator,\n) {\n const isZodV4 = !!output.packageJson && isZodVersionV4(output.packageJson);\n const strict = output.override.zod.strict.body;\n const coerce = output.override.zod.coerce.body;\n const context: ContextSpec = {\n spec: builder.spec,\n target: builder.target,\n workspace: '',\n output: output as ContextSpec['output'],\n };\n\n // Roots = every component schema, keyed by its RAW OpenAPI name taken\n // straight from `spec.components.schemas`. We must NOT derive these from\n // `builder.schemas`, whose `name` is the sanitized model identifier (e.g.\n // `PaginatedResponse_Asset_` becomes `PaginatedResponseAsset`): operation\n // files reference component schemas by `resolveSchemaName(<raw $ref>)`, so\n // building roots from sanitized names and then filtering them against the\n // raw-keyed `components.schemas` silently dropped every schema whose name\n // needs sanitizing. Those schemas were never emitted, yet the operation\n // files still imported them — producing dangling imports that don't compile.\n const componentSchemas = (builder.spec.components?.schemas ?? {}) as Record<\n string,\n unknown\n >;\n const refs = Object.keys(componentSchemas).map(\n (schemaName) => `#/components/schemas/${schemaName}`,\n );\n\n // Conflict guard.\n resolveSchemaNames(refs, context);\n\n const entries = generateReusableSchemaSet(refs, context, {\n strict,\n isZodV4,\n coerce,\n generateMeta: output.override.zod.generateMeta,\n paramsMutator,\n });\n\n const rewritten = rewriteReusableSchemas(entries);\n\n // Render bodies first so each entry's `extraImports` (names referenced only\n // by the recursive TS type body, e.g. an `AssetRelationType` used as a\n // `Record<>` key the zod runtime collapses to `zod.string()`) can be merged\n // into the per-file import list before assembling the file content.\n const componentNames = new Set(\n Object.keys(builder.spec.components?.schemas ?? {}).map((schemaName) =>\n resolveSchemaName(`#/components/schemas/${schemaName}`, context),\n ),\n );\n\n // When `override.zod.params` is set, each component schema may reference\n // the user-provided mutator (e.g. `zodParams`). Pre-compute the import\n // line once relative to `schemasPath`; every reusable schema file lives in\n // the same directory, so the relative path is identical across files.\n const paramsMutatorImport = paramsMutator\n ? buildMutatorImportStatement(paramsMutator)\n : undefined;\n\n for (const entry of rewritten) {\n const fileName = conventionName(entry.name, output.namingConvention);\n const filePath = path.join(schemasPath, `${fileName}${fileExtension}`);\n const importExt = fileExtension.replace(/\\.ts$/, '');\n const rendered = renderReusableSchemaEntry(entry, context);\n const refImports = buildSiblingImports({\n usedRefs: entry.usedRefs,\n extraImports: rendered.extraImports,\n entryName: entry.name,\n componentNames,\n namingConvention: output.namingConvention,\n importExt,\n });\n // Only emit the params mutator import on files that actually reference it\n // (schemas with no leaf validators — e.g. a pure `$ref` wrapper — won't).\n const needsParamsImport =\n !!paramsMutator && bodyReferencesMutator(entry.zod, paramsMutator);\n const imports = [\n ...(needsParamsImport && paramsMutatorImport\n ? [paramsMutatorImport]\n : []),\n ...(refImports ? [refImports] : []),\n ].join('\\n');\n\n const fileContent =\n `${header}import { z as zod } from 'zod';\\n` +\n (imports ? `${imports}\\n\\n` : '\\n') +\n `${rendered.content}\\n`;\n\n await fs.outputFile(filePath, fileContent);\n }\n\n if (output.indexFiles && rewritten.length > 0) {\n const schemaNames = rewritten.map((e) => e.name);\n await writeZodSchemaIndex(\n schemasPath,\n fileExtension,\n header,\n schemaNames,\n output.namingConvention,\n true,\n );\n }\n}\n\nexport async function writeZodSchemasFromVerbs(\n verbOptions: WriteZodSchemasFromVerbsInput,\n schemasPath: string,\n fileExtension: string,\n header: string,\n output: WriteZodOutputOptions,\n context: WriteZodSchemasFromVerbsContext,\n) {\n const zodContext = context as unknown as ContextSpec;\n const verbOptionsArray = Object.values(verbOptions);\n\n if (verbOptionsArray.length === 0) {\n return;\n }\n\n const isZodV4 = !!output.packageJson && isZodVersionV4(output.packageJson);\n const strict = output.override.zod.strict.body;\n const coerce = output.override.zod.coerce.body;\n const useReusableSchemas =\n output.override.zod.generateReusableSchemas === true;\n\n const generateVerbsSchemas = verbOptionsArray.flatMap((verbOption) => {\n const operation = verbOption.originalOperation;\n const shouldGenerate = {\n ...output.override.zod.generate,\n ...verbOption.override?.zod.generate,\n };\n\n const requestBody = operation.requestBody;\n const requestBodyContent =\n requestBody && 'content' in requestBody\n ? (requestBody as OpenApiRequestBodyObject).content\n : undefined;\n // Pick the first available body media type. JSON wins; otherwise fall back\n // to form-data / urlencoded so we still generate a `*Body` schema for\n // operations whose only payload is multipart (e.g. file uploads). Without\n // this, endpoints that import `${OperationName}Body` from the zod schemas\n // path resolve to a missing export. (issue #3066)\n const jsonBodyMedia = requestBodyContent?.['application/json'];\n const formDataBodyMedia = requestBodyContent?.['multipart/form-data'];\n const formUrlEncodedBodyMedia =\n requestBodyContent?.['application/x-www-form-urlencoded'];\n const [bodyContentType, bodyMedia] = jsonBodyMedia\n ? (['application/json', jsonBodyMedia] as const)\n : formDataBodyMedia\n ? (['multipart/form-data', formDataBodyMedia] as const)\n : formUrlEncodedBodyMedia\n ? ([\n 'application/x-www-form-urlencoded',\n formUrlEncodedBodyMedia,\n ] as const)\n : [undefined, undefined];\n const bodySchema = bodyMedia?.schema as OpenApiSchemaObject | undefined;\n\n const bodySchemas =\n shouldGenerate.body && bodySchema\n ? [\n {\n name: `${pascal(verbOption.operationName)}Body`,\n schema: useReusableSchemas\n ? bodySchema\n : dereference(bodySchema, zodContext),\n bodyContentType,\n encoding: bodyMedia?.encoding,\n },\n ]\n : [];\n\n const parameters = operation.parameters;\n\n const queryParams = parameters?.filter(\n (p): p is OpenApiParameterObject => 'in' in p && p.in === 'query',\n );\n\n const queryParamsSchemas =\n shouldGenerate.query && queryParams && queryParams.length > 0\n ? [\n {\n name: `${pascal(verbOption.operationName)}Params`,\n schema: {\n type: 'object' as const,\n properties: Object.fromEntries(\n queryParams\n .filter((p) => 'schema' in p && p.schema)\n .map((p) => [\n p.name,\n useReusableSchemas\n ? (p.schema as OpenApiSchemaObject)\n : dereference(\n p.schema as OpenApiSchemaObject,\n zodContext,\n ),\n ]),\n ) as Record<string, OpenApiSchemaObject>,\n required: queryParams\n .filter((p) => p.required)\n .map((p) => p.name)\n .filter((name): name is string => name !== undefined),\n },\n },\n ]\n : [];\n\n const headerParams = parameters?.filter(\n (p): p is OpenApiParameterObject => 'in' in p && p.in === 'header',\n );\n\n const headerParamsSchemas =\n shouldGenerate.header && headerParams && headerParams.length > 0\n ? [\n {\n name: `${pascal(verbOption.operationName)}Headers`,\n schema: {\n type: 'object' as const,\n properties: Object.fromEntries(\n headerParams\n .filter((p) => 'schema' in p && p.schema)\n .map((p) => [\n p.name,\n useReusableSchemas\n ? (p.schema as OpenApiSchemaObject)\n : dereference(\n p.schema as OpenApiSchemaObject,\n zodContext,\n ),\n ]),\n ) as Record<string, OpenApiSchemaObject>,\n required: headerParams\n .filter((p) => p.required)\n .map((p) => p.name)\n .filter((name): name is string => name !== undefined),\n },\n },\n ]\n : [];\n\n const responseSchemas = shouldGenerate.response\n ? [\n ...verbOption.response.types.success,\n ...verbOption.response.types.errors,\n ]\n .filter(\n (\n responseType,\n ): responseType is typeof responseType & {\n originalSchema: OpenApiSchemaObject;\n } =>\n !!responseType.originalSchema &&\n !responseType.isRef &&\n isValidSchemaIdentifier(responseType.value) &&\n !isPrimitiveSchemaName(responseType.value),\n )\n .map((responseType) => ({\n name: responseType.value,\n schema: useReusableSchemas\n ? responseType.originalSchema\n : dereference(responseType.originalSchema, zodContext),\n }))\n : [];\n\n return dedupeSchemasByName([\n ...bodySchemas,\n ...queryParamsSchemas,\n ...headerParamsSchemas,\n ...responseSchemas,\n ]);\n });\n\n const uniqueVerbsSchemas = dedupeSchemasByName(generateVerbsSchemas);\n const schemasToWrite: ZodSchemaFileToWrite[] = [];\n\n for (const entry of uniqueVerbsSchemas) {\n // Pure-ref wrapper skip: if the underlying schema is just `{ $ref: ... }` AND\n // the flag is on, don't emit a per-operation wrapper file. Consumers import\n // the named component schema directly.\n if (\n useReusableSchemas &&\n entry.schema &&\n typeof (entry.schema as { $ref?: unknown }).$ref === 'string' &&\n Object.keys(entry.schema).length === 1\n ) {\n continue;\n }\n\n const { name, schema } = entry;\n const fileName = conventionName(name, output.namingConvention);\n const filePath = path.join(schemasPath, `${fileName}${fileExtension}`);\n\n // multipart/form-data bodies need file-aware overrides so binary fields\n // become `z.instanceof(File)` instead of plain strings.\n const isFormDataBody =\n 'bodyContentType' in entry &&\n entry.bodyContentType === 'multipart/form-data';\n\n const zodDefinition: ZodValidationSchemaDefinition = isFormDataBody\n ? generateFormDataZodSchema(\n schema,\n zodContext,\n name,\n strict,\n isZodV4,\n 'encoding' in entry\n ? (entry.encoding as\n | Record<string, { contentType?: string }>\n | undefined)\n : undefined,\n useReusableSchemas,\n )\n : generateZodValidationSchemaDefinition(\n schema,\n zodContext,\n name,\n strict,\n isZodV4,\n {\n required: true,\n useReusableSchemas,\n },\n );\n\n const parsedZodDefinition = parseZodValidationSchemaDefinition(\n zodDefinition,\n zodContext,\n coerce,\n strict,\n isZodV4,\n );\n\n // Operation schemas sit at the top of the dependency graph, so any\n // `__REF_<name>__` sentinel resolves to a direct (non-lazy) reference.\n // Rewrite them to bare identifiers and emit the matching imports, the\n // same way `generateZod` does for the operation files (issue #3463).\n let zodExpression = parsedZodDefinition.zod;\n let importStatements: string[] | undefined;\n if (useReusableSchemas && parsedZodDefinition.usedRefs.size > 0) {\n zodExpression = rewriteSentinelsToDirect(zodExpression);\n const importExt = fileExtension.replace(/\\.ts$/, '');\n importStatements = [...parsedZodDefinition.usedRefs]\n .filter((refName) => refName !== name)\n .toSorted()\n .map((refName) => {\n const importedFile = conventionName(refName, output.namingConvention);\n return `import { ${refName} } from './${importedFile}${importExt}';`;\n });\n }\n\n schemasToWrite.push({\n schemaName: name,\n filePath,\n consts: parsedZodDefinition.consts,\n zodExpression,\n importStatements,\n });\n }\n\n const groupedSchemasToWrite = groupSchemasByFilePath(schemasToWrite);\n\n for (const schemaGroup of groupedSchemasToWrite) {\n const fileContent = generateZodSchemaFileContent(header, schemaGroup);\n\n await fs.outputFile(schemaGroup[0].filePath, fileContent);\n }\n\n if (output.indexFiles && uniqueVerbsSchemas.length > 0) {\n const schemaNames = groupedSchemasToWrite.map(\n (schemaGroup) => schemaGroup[0].schemaName,\n );\n await writeZodSchemaIndex(\n schemasPath,\n fileExtension,\n header,\n schemaNames,\n output.namingConvention,\n true,\n );\n }\n}\n","import path from 'node:path';\n\nimport {\n type ContextSpec,\n createSuccessMessage,\n type FakerMockOptions,\n fixCrossDirectoryImports,\n fixRegularSchemaImports,\n generateDependencyImports,\n generateMutator,\n getFileInfo,\n getImportExtension,\n getMockFileExtensionByTypeName,\n isFunction,\n isObject,\n isString,\n jsDoc,\n logWarning,\n type NormalizedOptions,\n type OpenApiInfoObject,\n OutputMockType,\n OutputMode,\n splitSchemasByType,\n SupportedFormatter,\n upath,\n writeGeneratedFile,\n writeSchemas,\n writeSingleMode,\n type WriteSpecBuilder,\n writeSplitMode,\n writeSplitTagsMode,\n writeTagsMode,\n} from '@orval/core';\nimport { generateFakerForSchemas } from '@orval/mock';\nimport { execa, ExecaError } from 'execa';\nimport fs from 'fs-extra';\nimport { unique } from 'remeda';\nimport type { TypeDocOptions } from 'typedoc';\n\nimport { formatWithPrettier } from './formatters/prettier';\nimport { executeHook } from './utils';\nimport {\n generateZodSchemasInline,\n writeZodSchemas,\n writeZodSchemasFromVerbs,\n} from './write-zod-specs';\n\nasync function runExternalFormatter(\n bin: string,\n args: string[],\n projectTitle?: string,\n): Promise<void> {\n try {\n await execa(bin, args);\n } catch (error) {\n let message: string;\n if (error instanceof ExecaError) {\n message =\n error.code === 'ENOENT'\n ? `⚠️ ${projectTitle ? `${projectTitle} - ` : ''}${bin} not found`\n : error.message;\n } else if (error instanceof Error) {\n message = error.message;\n } else {\n message = `⚠️ ${projectTitle ? `${projectTitle} - ` : ''}${bin} failed`;\n }\n logWarning(message);\n }\n}\n\nexport async function runFormatter(\n formatter: SupportedFormatter | undefined,\n paths: string[],\n projectTitle?: string,\n): Promise<void> {\n switch (formatter) {\n case SupportedFormatter.PRETTIER: {\n await formatWithPrettier(paths, projectTitle);\n break;\n }\n case SupportedFormatter.BIOME: {\n await runExternalFormatter(\n SupportedFormatter.BIOME,\n ['check', '--write', ...paths],\n projectTitle,\n );\n break;\n }\n case SupportedFormatter.OXFMT: {\n await runExternalFormatter(SupportedFormatter.OXFMT, paths, projectTitle);\n break;\n }\n }\n}\n\nfunction getHeader(\n option: false | ((info: OpenApiInfoObject) => string | string[]),\n info: OpenApiInfoObject,\n): string {\n if (!option) {\n return '';\n }\n\n const header = option(info);\n return Array.isArray(header) ? jsDoc({ description: header }) : header;\n}\n\n/**\n * Add re-export of operation schemas from the main schemas index file.\n * Handles the case where the index file doesn't exist (no regular schemas).\n */\nasync function addOperationSchemasReExport(\n schemaPath: string,\n operationSchemasPath: string,\n header: string,\n): Promise<void> {\n const schemaIndexPath = path.join(schemaPath, `index.ts`);\n const esmImportPath = upath.getRelativeImportPath(\n schemaIndexPath,\n operationSchemasPath,\n );\n const exportLine = `export * from '${esmImportPath}';\\n`;\n\n const indexExists = await fs.pathExists(schemaIndexPath);\n if (indexExists) {\n // Check if export already exists to prevent duplicates on re-runs\n // Use regex to handle both single and double quotes\n const existingContent = await fs.readFile(schemaIndexPath, 'utf8');\n const exportPattern = new RegExp(\n String.raw`export\\s*\\*\\s*from\\s*['\"]${esmImportPath.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`)}['\"]`,\n );\n if (!exportPattern.test(existingContent)) {\n await fs.appendFile(schemaIndexPath, exportLine);\n }\n } else {\n // Create index with header if file doesn't exist (no regular schemas case)\n const content =\n header && header.trim().length > 0\n ? `${header}\\n${exportLine}`\n : exportLine;\n await fs.outputFile(schemaIndexPath, content);\n }\n}\n\n/**\n * Emit `<schemas-dir>/index.faker.ts` (or `<output-root>/schemas.faker.ts`\n * when `output.schemas` is not configured) when a faker generator entry has\n * `schemas: true`. Each `components/schemas` entry becomes a\n * `get<SchemaName>Mock(overrides)` factory in the file. Returns the written\n * file path so callers can include it in formatter / hook runs, or\n * `undefined` if no file was written.\n */\nasync function writeFakerSchemaMocks(\n builder: WriteSpecBuilder,\n options: NormalizedOptions,\n header: string,\n): Promise<string | undefined> {\n const { output } = options;\n // Pick the opted-in faker entry directly. The duplicate-type guard in\n // `normalizeMocksOption` keeps this unambiguous today, and finding by\n // `schemas: true` also makes the intent obvious if that guard ever\n // loosens (so a `faker({ schemas: false })` entry can't accidentally\n // win the lookup).\n const fakerEntry = output.mock.generators.find(\n (g): g is FakerMockOptions =>\n !isFunction(g) && g.type === OutputMockType.FAKER && g.schemas === true,\n );\n if (!fakerEntry) {\n return undefined;\n }\n\n const schemasWithDef = builder.schemas.filter((s) => !!s.schema);\n if (schemasWithDef.length === 0) {\n return undefined;\n }\n\n const context: ContextSpec = {\n spec: builder.spec,\n target: builder.target,\n workspace: '',\n output,\n };\n\n const { implementation, imports } = generateFakerForSchemas(\n schemasWithDef,\n context,\n fakerEntry,\n );\n\n if (!implementation.trim()) {\n return undefined;\n }\n\n let filePath: string;\n let schemaImportPath: string | undefined;\n const fileExtension = output.fileExtension || '.ts';\n\n if (output.schemas) {\n const schemasDir = isString(output.schemas)\n ? output.schemas\n : output.schemas.path;\n filePath = path.join(schemasDir, `index.faker${fileExtension}`);\n schemaImportPath = '.';\n } else {\n const targetInfo = output.target\n ? getFileInfo(output.target, { extension: fileExtension })\n : undefined;\n const dir = targetInfo?.dirname ?? process.cwd();\n filePath = path.join(dir, `schemas.faker${fileExtension}`);\n // Without a dedicated schemas dir we have no separate types file to\n // import from; the factories will reference inline types declared in\n // the main output target. Append `getImportExtension` so NodeNext /\n // Node16 module resolution gets the required local-file extension.\n schemaImportPath = targetInfo\n ? `./${targetInfo.filename}${getImportExtension(\n fileExtension,\n output.tsconfig,\n )}`\n : undefined;\n }\n\n // Route every schema-related import (both type-only and runtime value\n // forms) onto the consolidated schemas path. Both `import { Foo }` and\n // `import type { Foo }` come from the same module here, so we treat\n // them uniformly — `generateDependencyImports` splits values vs types\n // back out into separate `import` / `import type` lines as needed.\n const reroutedImports = imports.map((imp) =>\n imp.importPath ? imp : { ...imp, importPath: schemaImportPath },\n );\n\n // `generateDependencyImports` expects a list of `{ exports, dependency }`\n // groups (one per source module). Bucket all rerouted imports by their\n // resolved `importPath` so each module emits a single `import type { ... }`\n // line.\n const grouped = new Map<string, typeof reroutedImports>();\n for (const imp of reroutedImports) {\n const key = imp.importPath ?? '';\n if (!key) continue;\n const bucket = grouped.get(key) ?? [];\n bucket.push(imp);\n grouped.set(key, bucket);\n }\n\n const importsHeader = generateDependencyImports(\n implementation,\n [\n {\n exports: [{ name: 'faker', values: true }],\n dependency: fakerEntry.locale\n ? `@faker-js/faker/locale/${fakerEntry.locale}`\n : '@faker-js/faker',\n },\n ...[...grouped.entries()].map(([dependency, exports]) => ({\n exports,\n dependency,\n })),\n ],\n undefined,\n !!output.schemas,\n false,\n );\n\n const content = `${header}${importsHeader}\\n\\n${implementation}`;\n await writeGeneratedFile(filePath, content);\n return filePath;\n}\n\nfunction isSchemaValidatorClient(\n client: NormalizedOptions['output']['client'],\n): boolean {\n return client === 'zod' || client === 'effect';\n}\n\nfunction shouldGenerateZodSchemasInline(\n output: NormalizedOptions['output'],\n hasOperations: boolean,\n): boolean {\n if (output.client !== 'zod' || output.schemas) {\n return false;\n }\n // With `generateReusableSchemas`, operations reference component schemas by\n // name, so the component definitions must be emitted inline alongside the\n // operations (otherwise the references are dangling). Without the flag,\n // operations inline their own schemas, so we only emit the component\n // schemas inline when there are no operations.\n // `NormalizedOutputOptions` types this as a required `boolean`, so use it\n // directly (a `=== true` compare trips no-unnecessary-boolean-literal-compare).\n if (output.override.zod.generateReusableSchemas) {\n return true;\n }\n return !hasOperations;\n}\n\nfunction shouldGenerateSchemas(\n output: NormalizedOptions['output'],\n hasOperations: boolean,\n): boolean {\n return (\n (!output.schemas && !isSchemaValidatorClient(output.client)) ||\n shouldGenerateZodSchemasInline(output, hasOperations)\n );\n}\n\nexport async function writeSpecs(\n builder: WriteSpecBuilder,\n workspace: string,\n options: NormalizedOptions,\n projectName?: string,\n) {\n const { info, schemas, target } = builder;\n const { output } = options;\n const projectTitle = projectName ?? info.title;\n\n const header = getHeader(output.override.header, info);\n\n if (output.schemas) {\n const schemasPath = isString(output.schemas)\n ? output.schemas\n : output.schemas.path;\n const isZodSchemas =\n (!isString(output.schemas) && output.schemas.type === 'zod') ||\n // Auto-promote a string `schemas:` to the zod writer when client is zod\n // and the reusable flag is on. We deliberately don't promote when the\n // user explicitly set `{ type: 'typescript' }` — that signals intent\n // to keep TS types, even alongside a zod client.\n (isString(output.schemas) &&\n output.client === 'zod' &&\n output.override.zod.generateReusableSchemas);\n\n if (isZodSchemas) {\n // Use the schema-specific extension so the global `fileExtension` (which\n // also drives client/mock outputs) isn't dragged into the zod world.\n const fileExtension = output.schemaFileExtension;\n\n // Reusable component schemas live as separate files under `schemasPath`,\n // so we resolve the user's `override.zod.params` mutator once relative\n // to that directory and pass it down. Each emitted schema file lives in\n // the same dir, so the relative import is identical across files.\n const schemasParamsMutator = output.override.zod.params\n ? await generateMutator({\n output: path.join(schemasPath, `__params__${fileExtension}`),\n mutator: output.override.zod.params,\n name: 'zodParams',\n workspace,\n tsconfig: output.tsconfig,\n })\n : undefined;\n\n await writeZodSchemas(\n builder,\n schemasPath,\n fileExtension,\n header,\n output,\n schemasParamsMutator,\n );\n\n await writeZodSchemasFromVerbs(\n builder.verbOptions,\n schemasPath,\n fileExtension,\n header,\n output,\n {\n spec: builder.spec,\n target: builder.target,\n workspace,\n output,\n },\n );\n } else {\n const fileExtension = output.fileExtension || '.ts';\n\n // Split schemas if operationSchemas path is configured\n if (output.operationSchemas) {\n const { regularSchemas, operationSchemas: opSchemas } =\n splitSchemasByType(schemas);\n\n // Fix cross-directory imports before writing (both directions)\n const regularSchemaNames = new Set(regularSchemas.map((s) => s.name));\n const operationSchemaNames = new Set(opSchemas.map((s) => s.name));\n fixCrossDirectoryImports(\n opSchemas,\n regularSchemaNames,\n schemasPath,\n output.operationSchemas,\n output.namingConvention,\n fileExtension,\n output.tsconfig,\n );\n fixRegularSchemaImports(\n regularSchemas,\n operationSchemaNames,\n schemasPath,\n output.operationSchemas,\n output.namingConvention,\n fileExtension,\n output.tsconfig,\n );\n\n // Write regular schemas to schemas path\n if (regularSchemas.length > 0) {\n await writeSchemas({\n schemaPath: schemasPath,\n schemas: regularSchemas,\n target,\n namingConvention: output.namingConvention,\n fileExtension,\n header,\n indexFiles: output.indexFiles,\n tsconfig: output.tsconfig,\n factoryOutputDirectory: output.factoryMethods?.outputDirectory,\n });\n }\n\n // Write operation schemas to operationSchemas path\n if (opSchemas.length > 0) {\n await writeSchemas({\n schemaPath: output.operationSchemas,\n schemas: opSchemas,\n target,\n namingConvention: output.namingConvention,\n fileExtension,\n header,\n indexFiles: output.indexFiles,\n tsconfig: output.tsconfig,\n factoryOutputDirectory: output.factoryMethods?.outputDirectory,\n });\n\n // Add re-export from operations in the main schemas index\n if (output.indexFiles) {\n await addOperationSchemasReExport(\n schemasPath,\n output.operationSchemas,\n header,\n );\n }\n }\n } else {\n await writeSchemas({\n schemaPath: schemasPath,\n schemas,\n target,\n namingConvention: output.namingConvention,\n fileExtension,\n header,\n indexFiles: output.indexFiles,\n tsconfig: output.tsconfig,\n factoryOutputDirectory: output.factoryMethods?.outputDirectory,\n });\n }\n }\n }\n\n // Emit a consolidated faker mock file for `components/schemas` when the\n // faker generator opts in with `schemas: true`. Lives alongside the\n // generated TS schema types so factories can import them directly.\n const fakerSchemaPath = await writeFakerSchemaMocks(builder, options, header);\n\n let implementationPaths: string[] = [];\n\n if (output.target) {\n const writeMode = getWriteMode(output.mode);\n const hasOperations = Object.keys(builder.operations).length > 0;\n const needZodSchemasInline = shouldGenerateZodSchemasInline(\n output,\n hasOperations,\n );\n // The zod client's `import * as zod from 'zod'` is a *usage-gated* dependency\n // import: it's only emitted when an operation's generated schema actually\n // references the `zod` token. When every operation is a pure-`$ref` alias\n // (e.g. `export const FooResponse = Bar`), the client emits no zod import —\n // so the inline schema block (which always uses zod) must supply it itself.\n // When an operation does use zod the client already imports it, and a second\n // import would redeclare the `zod` binding — so the inline block omits it.\n const operationsUseZod = Object.values(builder.operations).some(\n (operation) => /\\bzod\\b/.test(operation.implementation),\n );\n const includeZodImport = !operationsUseZod;\n\n // Inline component schemas (when `generateReusableSchemas` is on without a\n // dedicated `output.schemas` dir) need their own `paramsMutator` resolved\n // relative to `output.target`. Per-operation mutators in `generateZodRoute`\n // don't cover the shared `export const Pet = …` definitions emitted here,\n // so without this the inlined components would silently skip injection.\n const inlineSchemasParamsMutator =\n needZodSchemasInline && output.override.zod.params\n ? await generateMutator({\n output: output.target,\n mutator: output.override.zod.params,\n name: 'zodParams',\n workspace,\n tsconfig: output.tsconfig,\n })\n : undefined;\n // Every non-`single` mode (`split` / `tags` / `tags-split`) writes inline\n // schemas to a separate `.schemas` file alongside the operation file(s),\n // so they need their own params-mutator import. Only in `single` mode do\n // the schemas concatenate into the operation file and inherit its import\n // (emitted via each verb's `mutators` array in `generateZodRoute`) — re-\n // emitting from inline would produce a duplicate `import` line there.\n // With no operations at all, even in `single` mode the file builder has\n // no operation mutators to lean on, so we still emit.\n const isSchemasInSeparateFile = output.mode !== OutputMode.SINGLE;\n const includeParamsImport = !hasOperations || isSchemasInSeparateFile;\n\n implementationPaths = await writeMode({\n builder,\n workspace,\n output,\n projectName,\n header,\n needSchema: shouldGenerateSchemas(output, hasOperations),\n generateSchemasInline: needZodSchemasInline\n ? () =>\n generateZodSchemasInline(\n builder,\n output,\n includeZodImport,\n inlineSchemasParamsMutator,\n includeParamsImport,\n )\n : undefined,\n });\n }\n\n if (output.workspace) {\n const workspacePath = output.workspace;\n const indexFile = path.join(workspacePath, 'index.ts');\n // Skip per-mock-entry output files when emitting the workspace index.\n // The cleanup pass removes any path matching `.<ext>.ts` for every\n // configured generator's extension (`msw`, `faker`, etc.).\n const mockExtensions = output.mock.generators.map((g) =>\n getMockFileExtensionByTypeName(g),\n );\n const imports = implementationPaths\n .filter(\n (p) =>\n mockExtensions.length === 0 ||\n !mockExtensions.some((ext) => p.endsWith(`.${ext}.ts`)),\n )\n .map((p) =>\n upath.getRelativeImportPath(\n indexFile,\n getFileInfo(p).pathWithoutExtension,\n true,\n ),\n );\n\n if (output.schemas) {\n const schemasPath = isString(output.schemas)\n ? output.schemas\n : output.schemas.path;\n imports.push(\n upath.getRelativeImportPath(\n indexFile,\n getFileInfo(schemasPath).dirname,\n ),\n );\n }\n\n if (output.operationSchemas) {\n imports.push(\n upath.getRelativeImportPath(\n indexFile,\n getFileInfo(output.operationSchemas).dirname,\n ),\n );\n }\n\n if (output.indexFiles) {\n if (await fs.pathExists(indexFile)) {\n const data = await fs.readFile(indexFile, 'utf8');\n const importsNotDeclared = imports.filter((imp) => !data.includes(imp));\n await fs.appendFile(\n indexFile,\n unique(importsNotDeclared)\n .map((imp) => `export * from '${imp}';\\n`)\n .join(''),\n );\n } else {\n await fs.outputFile(\n indexFile,\n unique(imports)\n .map((imp) => `export * from '${imp}';`)\n .join('\\n') + '\\n',\n );\n }\n\n implementationPaths = [indexFile, ...implementationPaths];\n }\n }\n\n if (builder.extraFiles.length > 0) {\n await Promise.all(\n builder.extraFiles.map(async (file) =>\n fs.outputFile(file.path, file.content),\n ),\n );\n\n implementationPaths = [\n ...implementationPaths,\n ...builder.extraFiles.map((file) => file.path),\n ];\n }\n\n const paths = [\n ...(output.schemas\n ? [\n getFileInfo(\n isString(output.schemas) ? output.schemas : output.schemas.path,\n ).dirname,\n ]\n : []),\n ...(fakerSchemaPath ? [fakerSchemaPath] : []),\n ...(output.operationSchemas\n ? [getFileInfo(output.operationSchemas).dirname]\n : []),\n ...implementationPaths,\n ];\n\n if (options.hooks.afterAllFilesWrite) {\n await executeHook(\n 'afterAllFilesWrite',\n options.hooks.afterAllFilesWrite,\n paths,\n );\n }\n\n await runFormatter(output.formatter, paths, projectTitle);\n\n if (output.docs) {\n try {\n let config: Partial<TypeDocOptions> = {};\n let configPath: string | undefined;\n if (isObject(output.docs)) {\n ({ configPath, ...config } = output.docs);\n if (configPath) {\n config.options = configPath;\n }\n }\n\n const getTypedocApplication = async () => {\n const { Application } = await import('typedoc');\n return Application;\n };\n\n const Application = await getTypedocApplication();\n const app = await Application.bootstrapWithPlugins({\n entryPoints: paths.map((x) => upath.toUnix(x)),\n theme: 'markdown',\n // Skip TypeScript diagnostics on the consuming project: TypeDoc would\n // otherwise pick up the user's tsconfig and surface errors from files\n // unrelated to the generated entry points (e.g. a demo `App.tsx`\n // with an unused `React` default import under the new JSX transform —\n // see #3338). User-overridable via the `docs` option below.\n skipErrorChecking: true,\n // Set the custom config location if it has been provided.\n ...config,\n plugin: ['typedoc-plugin-markdown', ...(config.plugin ?? [])],\n });\n // Set defaults if the have not been provided by the external config.\n if (!app.options.isSet('readme')) {\n app.options.setValue('readme', 'none');\n }\n if (!app.options.isSet('logLevel')) {\n app.options.setValue('logLevel', 'None');\n }\n const project = await app.convert();\n if (project) {\n const outputPath = app.options.getValue('out');\n await app.generateDocs(project, outputPath);\n\n await runFormatter(output.formatter, [outputPath], projectTitle);\n } else {\n throw new Error('TypeDoc not initialized');\n }\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : `⚠️ ${projectTitle ? `${projectTitle} - ` : ''}Unable to generate docs`;\n\n logWarning(message);\n }\n }\n\n createSuccessMessage(projectTitle);\n}\n\nfunction getWriteMode(mode: OutputMode) {\n switch (mode) {\n case OutputMode.SPLIT: {\n return writeSplitMode;\n }\n case OutputMode.TAGS: {\n return writeTagsMode;\n }\n case OutputMode.TAGS_SPLIT: {\n return writeSplitTagsMode;\n }\n default: {\n return writeSingleMode;\n }\n }\n}\n","import {\n getFileInfo,\n isString,\n log,\n type NormalizedOptions,\n removeFilesAndEmptyFolders,\n} from '@orval/core';\n\nimport { importSpecs } from './import-specs';\nimport { writeSpecs } from './write-specs';\n\n/**\n * Generate client/spec files for a single Orval project.\n *\n * @param workspace - Absolute or relative workspace path used to resolve imports.\n * @param options - Normalized generation options for this project.\n * @param projectName - Optional project name used in logging output.\n * @returns A promise that resolves once generation (and optional cleaning) completes.\n *\n * @example\n * await generateSpec(process.cwd(), normalizedOptions, 'my-project');\n */\nexport async function generateSpec(\n workspace: string,\n options: NormalizedOptions,\n projectName?: string,\n) {\n if (options.output.clean) {\n const extraPatterns = Array.isArray(options.output.clean)\n ? options.output.clean\n : [];\n\n if (options.output.target) {\n await removeFilesAndEmptyFolders(\n ['**/*', '!**/*.d.ts', ...extraPatterns],\n getFileInfo(options.output.target).dirname,\n );\n }\n if (options.output.schemas) {\n const schemasPath = isString(options.output.schemas)\n ? options.output.schemas\n : options.output.schemas.path;\n await removeFilesAndEmptyFolders(\n ['**/*', '!**/*.d.ts', ...extraPatterns],\n getFileInfo(schemasPath).dirname,\n );\n }\n log(`${projectName} Cleaning output folder`);\n }\n\n const writeSpecBuilder = await importSpecs(workspace, options, projectName);\n await writeSpecs(writeSpecBuilder, workspace, options, projectName);\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { type Config, type ConfigExternal, isFunction } from '@orval/core';\nimport { createJiti } from 'jiti';\n\n/**\n * Resolve the Orval config file path.\n *\n * @param configFilePath - Optional path to the config file (absolute or relative).\n * @returns The absolute path to the resolved config file.\n * @throws If a provided path does not exist or if no config file is found.\n *\n * @example\n * // explicit path\n * const p = findConfigFile('./orval.config.ts');\n *\n * @example\n * // automatic discovery (searches process.cwd())\n * const p = findConfigFile();\n */\nexport function findConfigFile(configFilePath?: string) {\n if (configFilePath) {\n const absolutePath = path.isAbsolute(configFilePath)\n ? configFilePath\n : path.resolve(process.cwd(), configFilePath);\n\n if (!fs.existsSync(absolutePath))\n throw new Error(`Config file ${configFilePath} does not exist`);\n\n return absolutePath;\n }\n\n const root = process.cwd();\n const exts = ['.ts', '.js', '.mjs', '.mts'];\n for (const ext of exts) {\n const fullPath = path.resolve(root, `orval.config${ext}`);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n\n throw new Error(`No config file found in ${root}`);\n}\n\n/**\n * Load an Orval config file\n * @param configFilePath - Path to the config file (absolute or relative).\n * @returns The resolved Orval `Config` object.\n * @throws If the module does not provide a default export or the default export resolves to `undefined`.\n *\n * @example\n * // load a config object\n * const cfg = await loadConfigFile('./orval.config.ts');\n */\nexport async function loadConfigFile(configFilePath: string): Promise<Config> {\n const jiti = createJiti(process.cwd(), {\n interopDefault: true,\n });\n\n const configExternal = await jiti.import<ConfigExternal | undefined>(\n configFilePath,\n {\n default: true,\n },\n );\n\n if (configExternal === undefined) {\n throw new Error(`${configFilePath} doesn't have a default export`);\n }\n\n const config = await (isFunction(configExternal)\n ? configExternal()\n : configExternal);\n\n return config;\n}\n"],"mappings":";;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AQ,QAAQ,KAAK,EAAE,eAAe;AAE/C,MAAI,CAACC,KAAG,WAAW,aAAa,CAC9B,OAAM,IAAI,MAAM,eAAe,eAAe,iBAAiB;AAEjE,SAAO;;CAGT,MAAM,OAAO,QAAQ,KAAK;AAE1B,MAAK,MAAM,OADE;EAAC;EAAO;EAAO;EAAQ;EAAO,EACnB;EACtB,MAAM,WAAW,KAAK,QAAQ,MAAM,eAAe,MAAM;AACzD,MAAIA,KAAG,WAAW,SAAS,CACzB,QAAO;;AAIX,OAAM,IAAI,MAAM,2BAA2B,OAAO;;;;;;;;;;;;AAapD,eAAsB,eAAe,gBAAyC;CAK5E,MAAM,iBAAiB,MAJV,WAAW,QAAQ,KAAK,EAAE,EACrC,gBAAgB,MACjB,CAAC,CAEgC,OAChC,gBACA,EACE,SAAS,MACV,CACF;AAED,KAAI,mBAAmB,KAAA,EACrB,OAAM,IAAI,MAAM,GAAG,eAAe,gCAAgC;AAOpE,QAJe,OAAO,WAAW,eAAe,GAC5C,gBAAgB,GAChB"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ConfigExternal, GlobalOptions, InputTransformerFn, Options, OptionsExport } from "@orval/core";
|
|
2
|
+
import { ZodParamsContext } from "@orval/zod";
|
|
2
3
|
export * from "@orval/core";
|
|
3
4
|
|
|
4
5
|
//#region src/generate.d.ts
|
|
@@ -16,5 +17,5 @@ declare function defineConfig(options: ConfigExternal): ConfigExternal;
|
|
|
16
17
|
*/
|
|
17
18
|
declare function defineTransformer(transformer: InputTransformerFn): InputTransformerFn;
|
|
18
19
|
//#endregion
|
|
19
|
-
export { type Options, generate as default, generate, defineConfig, defineTransformer };
|
|
20
|
+
export { type Options, type ZodParamsContext, generate as default, generate, defineConfig, defineTransformer };
|
|
20
21
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as defineConfig, i as startWatcher, n as loadConfigFile, o as defineTransformer, r as generateSpec, s as normalizeOptions, t as findConfigFile } from "./config-
|
|
1
|
+
import { a as defineConfig, i as startWatcher, n as loadConfigFile, o as defineTransformer, r as generateSpec, s as normalizeOptions, t as findConfigFile } from "./config-yIkhToq8.mjs";
|
|
2
2
|
import { getWarningCount, isString, logError, resetWarnings, setVerbose } from "@orval/core";
|
|
3
3
|
export * from "@orval/core";
|
|
4
4
|
//#region src/generate.ts
|