@hey-api/shared 0.2.1 โ†’ 0.2.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["safePackage: PackageJson","lines: Array<string>","path","registryRegExp","getRegistryUrl","parseShorthand","queryParams: string | undefined","registryRegExp","getRegistryUrl","namespace","parseShorthand","defaultWatch: Watch","inputs: Array<Input>","input: Input","result: Pick<\n Partial<Input>,\n | 'api_key'\n | 'branch'\n | 'commit_sha'\n | 'organization'\n | 'project'\n | 'registry'\n | 'tags'\n | 'version'\n > &\n Pick<Input, 'path'>","path","queryParams: Array<string>","lines: Array<string>","logs: Logs","valueToObject: ValueToObject","mappers","fields","defaultValue","satisfies: typeof semver.satisfies","graph","uniqueItems: Array<IR.SchemaObject>","typeIds: Array<string>","path","result: OperationResponsesMap","errors: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'>","responses: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'>","defaultResponse: IR.ResponseObject | undefined","result: string","path","ir","section","path","entries: Array<[string, string]>","arrayBuffer: ArrayBuffer | undefined","hasChanged: boolean | undefined","response: Response | undefined","declIndex: Map<string, number>","walkDeclarations: WalkFn","graph","walkTopological: WalkFn","order: Array<string>","getGroup: GetPointerPriorityFn","walk: WalkFn","matchIrPointerToGroup: MatchPointerToGroupFn<IrTopLevelKind>","patterns: Record<IrTopLevelKind, RegExp>","kind","kindPriority: KindPriority","partial: Partial<KindPriority>","getIrPointerPriority: GetPointerPriorityFn","path","defaultGetKind: Required<Required<Hooks>['operations']>['getKind']","callback: (event: WalkEvent<TKind>) => void","events: ReadonlyArray<TKind>","options: WalkOptions<TKind>","event: WalkEvent | undefined","baseEvent: BaseEvent","symbolIn: SymbolIn","result: EventHooks","path","contextTags: ReadonlyArray<string> | undefined","contextAnchor: string | undefined","path","walk: Walker<TResult, TPlugin>","walk","namespace","keys: Array<string>","regexps: Array<RegExp>","path","filters: Filters","dependencies: Set<string> | undefined","resourceMetadata: ResourceMetadata","graph","path","namespace","path","walkSchemas","path","rootEnums: Record<string, unknown>","rootEnumSignatures: Record<string, string>","inlineEnums: Array<{\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n signature: string;\n }>","signatureToName: Record<string, string | undefined>","signatureToSchema: Record<string, unknown>","path","graph","childResult: Partial<PointerDependenciesResult>","worklist: Set<string>","graph: Graph","walk","path","deprecated: boolean | undefined","tags: Set<string> | undefined","cache: Cache","path","originals: OriginalSchemas","graph","contextVariant: Scope | null","variants: SplitMapping[keyof SplitMapping]","updatedMapping: Record<string, string>","split: SplitSchemas","deepEqual","walk","renameMap: Record<string, string>","path","filterSpec","filtered: typeof spec.definitions","path","contentToSchema","mediaTypeObjects","objects: Array<Content>","values: Array<string>","getSchemaType","parseSchemaJsDoc","parseSchemaMeta","parseArray","schemaItems: Array<IR.SchemaObject>","schemaToIrSchema","parseBoolean","parseNumber","parseObject","schemaProperties: Record<string, IR.SchemaObject>","parseString","parseExtensions","initIrSchema","irSchema: IR.SchemaObject","parseAllOf","ref","valueSchemas: ReadonlyArray<IR.SchemaObject>","irDiscriminatorSchema: IR.SchemaObject","parseOneType","nestedItems: Array<IR.SchemaObject>","parseEnum","enumType: SchemaType<SchemaObject> | 'null' | undefined","parseRef","irSchema","parseNullableType","typeIrSchema: IR.SchemaObject","parseType","parseUnknown","parseSchema","isPaginationType","paginationField","ref","name","getSchemaType","parseOperationJsDoc","initIrOperation","irOperation: IR.OperationObject","operationToIrOperation","requestBodyObject: IR.BodyObject","requestBodyObjectRequired: Array<string>","schema: SchemaObject","mediaTypeObjects","content","paginationField","schemaToIrSchema","contentToSchema","securitySchemeObjects: Map<string, IR.SecurityObject>","irSecuritySchemeObject: IR.SecurityObject | undefined","parsePathOperation","path","defaultExplode","defaultStyle","parametersArrayToObject","parametersObject: IR.ParametersObject","parameterToIrParameter","finalSchema: SchemaObject","paginationField","irParameter: IR.ParameterObject","schemaToIrSchema","errorResponse: Url","path","parseServers","schemes: ReadonlyArray<string>","path","validateOpenApiSpec","issues: Array<ValidatorIssue>","path","validateOpenApiSpec","graph","state: State","path","commonOperation: OperationObject","operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'>","parametersArrayToObject","filterSpec","filtered: typeof spec.components.parameters","filtered: typeof spec.components.requestBodies","filtered: typeof spec.components.responses","filtered: typeof spec.components.schemas","path","contentToSchema","mediaTypeObjects","objects: Array<Content>","findDiscriminatorPropertyType","findDiscriminatorsInSchema","resolvedSchema: SchemaObject","getAllDiscriminatorValues","values: Array<string>","parseSchemaJsDoc","parseSchemaMeta","parseArray","schemaItems: Array<IR.SchemaObject>","schemaToIrSchema","parseBoolean","parseNumber","parseObject","schemaProperties: Record<string, IR.SchemaObject>","parseString","parseExtensions","initIrSchema","irSchema: IR.SchemaObject","parseAllOf","discriminatorsToAdd: Array<DiscriminatorInfo>","ref","valueSchemas: ReadonlyArray<IR.SchemaObject>","discriminatorProperty: IR.SchemaObject","inlineSchema: IR.SchemaObject | undefined","irDiscriminatorSchema: IR.SchemaObject","parseOneType","nestedItems: Array<IR.SchemaObject>","parseAnyOf","parseEnum","enumType: SchemaType<SchemaObject> | 'null' | undefined","parseOneOf","parseRef","irSchema","typeIrSchema: IR.SchemaObject","parseType","parseUnknown","parseSchema","isPaginationType","paginationField","ref","refSchema: SchemaObject | ReferenceObject | undefined","mediaTypeObjects","content","name","parseOperationJsDoc","initIrOperation","irOperation: IR.OperationObject","operationToIrOperation","mediaTypeObjects","content","paginationField","schemaToIrSchema","contentToSchema","securitySchemeObjects: Map<string, IR.SecurityObject>","parsePathOperation","path","defaultAllowReserved","defaultExplode","defaultStyle","parametersArrayToObject","parametersObject: IR.ParametersObject","parameterToIrParameter","mediaTypeObjects","content","finalSchema: SchemaObject","paginationField","irParameter: IR.ParameterObject","schemaToIrSchema","parseParameter","requestBodyToIrRequestBody","mediaTypeObjects","content","irRequestBody: IR.RequestBodyObject","schemaToIrSchema","parseRequestBody","parseServers","validateOpenApiSpec","issues: Array<ValidatorIssue>","path","validateOpenApiSpec","graph","state: State","path","operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method' | 'operation'> & {\n operation: Omit<Parameters<typeof parsePathOperation>[0]['operation'], 'responses'>;\n }","parametersArrayToObject","filtered: typeof spec.components.parameters","filtered: typeof spec.components.requestBodies","filtered: typeof spec.components.responses","filtered: typeof spec.components.schemas","path","objects: Array<Content>","resolvedSchema: SchemaObject","values: Array<string>","schemaItems: Array<IR.SchemaObject>","schemaProperties: Record<string, IR.SchemaObject>","patternProperties: Record<string, IR.SchemaObject>","irSchema: IR.SchemaObject","discriminatorsToAdd: Array<DiscriminatorInfo>","ref","valueSchemas: ReadonlyArray<IR.SchemaObject>","discriminatorProperty: IR.SchemaObject","inlineSchema: IR.SchemaObject | undefined","irDiscriminatorSchema: IR.SchemaObject","nestedItems: Array<IR.SchemaObject>","enumType: SchemaType<SchemaObject> | undefined","irSchema","irRefSchema: IR.SchemaObject","typeIrSchema: IR.SchemaObject","ref","refSchema: SchemaObject | undefined","content","name","schema","irOperation: IR.OperationObject","content","securitySchemeObjects: Map<string, IR.SecurityObject>","path","parametersObject: IR.ParametersObject","content","finalSchema: SchemaObject","irParameter: IR.ParameterObject","content","irRequestBody: IR.RequestBodyObject","issues: Array<ValidatorIssue>","path","state: Parameters<typeof parseWebhookOperation>[0]['state']","operationArgs: Omit<Parameters<typeof parseWebhookOperation>[0], 'method'>","graph","state: State","path","operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'>","path","STRUCTURAL_ROLE: Record<string, 'name' | 'index'>","STRUCTURAL_SUFFIX: Record<string, string>","ROOT_CONTEXT: Record<string | number, RootContextConfig>","names: Array<string>","path"],"sources":["../src/tsConfig.ts","../src/cli.ts","../src/fs.ts","../src/error.ts","../src/config/engine.ts","../src/utils/input/heyApi.ts","../src/utils/input/readme.ts","../src/utils/input/scalar.ts","../src/utils/input/index.ts","../src/config/input/input.ts","../src/config/input/path.ts","../src/config/logs.ts","../src/config/output/postprocess.ts","../src/config/utils/config.ts","../src/config/output/source/config.ts","../src/config/parser/config.ts","../src/config/utils/dependencies.ts","../src/debug/graph.ts","../src/ir/parameter.ts","../src/ir/schema.ts","../src/ir/utils.ts","../src/ir/operation.ts","../src/utils/naming/naming.ts","../src/openApi/shared/utils/operation.ts","../src/debug/ir.ts","../src/debug/index.ts","../src/getSpec.ts","../src/utils/minHeap.ts","../src/graph/walk.ts","../src/ir/graph.ts","../src/utils/ref.ts","../src/plugins/shared/utils/instance.ts","../src/ir/context.ts","../src/ir/intents.ts","../src/ir/schema-processor.ts","../src/ir/schema-walker.ts","../src/openApi/shared/utils/filter.ts","../src/openApi/shared/graph/meta.ts","../src/openApi/shared/utils/schema.ts","../src/openApi/shared/utils/schemaChildRelationships.ts","../src/openApi/shared/utils/transforms.ts","../src/openApi/shared/transforms/utils.ts","../src/openApi/shared/transforms/enums.ts","../src/openApi/shared/transforms/propertiesRequiredByDefault.ts","../src/openApi/shared/utils/deepEqual.ts","../src/openApi/shared/utils/graph.ts","../src/openApi/shared/transforms/readWrite.ts","../src/openApi/shared/transforms/schemas.ts","../src/openApi/shared/transforms/index.ts","../src/openApi/shared/utils/parameter.ts","../src/openApi/shared/utils/validator.ts","../src/openApi/2.0.x/parser/filter.ts","../src/ir/mediaType.ts","../src/openApi/2.0.x/parser/mediaType.ts","../src/ir/pagination.ts","../src/openApi/shared/utils/discriminator.ts","../src/openApi/2.0.x/parser/schema.ts","../src/openApi/2.0.x/parser/pagination.ts","../src/openApi/2.0.x/parser/operation.ts","../src/openApi/2.0.x/parser/parameter.ts","../src/utils/url.ts","../src/openApi/2.0.x/parser/server.ts","../src/openApi/2.0.x/parser/validate.ts","../src/openApi/2.0.x/parser/index.ts","../src/openApi/3.0.x/parser/filter.ts","../src/openApi/3.0.x/parser/mediaType.ts","../src/openApi/3.0.x/parser/schema.ts","../src/openApi/3.0.x/parser/pagination.ts","../src/openApi/3.0.x/parser/operation.ts","../src/openApi/3.0.x/parser/parameter.ts","../src/openApi/3.0.x/parser/requestBody.ts","../src/openApi/3.0.x/parser/server.ts","../src/openApi/3.0.x/parser/validate.ts","../src/openApi/3.0.x/parser/index.ts","../src/openApi/3.1.x/parser/filter.ts","../src/openApi/3.1.x/parser/mediaType.ts","../src/openApi/3.1.x/parser/schema.ts","../src/openApi/3.1.x/parser/pagination.ts","../src/openApi/3.1.x/parser/operation.ts","../src/openApi/3.1.x/parser/parameter.ts","../src/openApi/3.1.x/parser/requestBody.ts","../src/openApi/3.1.x/parser/server.ts","../src/openApi/3.1.x/parser/validate.ts","../src/openApi/3.1.x/parser/webhook.ts","../src/openApi/3.1.x/parser/index.ts","../src/openApi/index.ts","../src/openApi/shared/locations/operation.ts","../src/openApi/shared/utils/patch.ts","../src/plugins/shared/utils/config.ts","../src/utils/escape.ts","../src/utils/exports.ts","../src/utils/path.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { AnyString } from '@hey-api/types';\nimport ts from 'typescript';\n\nexport function findPackageJson(initialDir: string): unknown | undefined {\n let dir = initialDir;\n while (dir !== path.dirname(dir)) {\n const files = fs.readdirSync(dir);\n const candidates = files.filter((file) => file === 'package.json');\n\n if (candidates[0]) {\n const packageJsonPath = path.join(dir, candidates[0]);\n return JSON.parse(\n fs.readFileSync(packageJsonPath, {\n encoding: 'utf8',\n }),\n );\n }\n\n dir = path.dirname(dir);\n }\n\n return;\n}\n\ntype PackageJson = {\n bugs: {\n url: string;\n };\n name: string;\n version: string;\n};\n\nexport function loadPackageJson(initialDir: string): PackageJson | undefined {\n const packageJson = findPackageJson(initialDir);\n\n const safePackage: PackageJson = {\n bugs: {\n url: '',\n },\n name: '',\n version: '',\n };\n\n if (packageJson && typeof packageJson === 'object') {\n if ('name' in packageJson && typeof packageJson.name === 'string') {\n safePackage.name = packageJson.name;\n }\n\n if ('version' in packageJson && typeof packageJson.version === 'string') {\n safePackage.version = packageJson.version;\n }\n\n if ('bugs' in packageJson && packageJson.bugs && typeof packageJson.bugs === 'object') {\n if ('url' in packageJson.bugs && typeof packageJson.bugs.url === 'string') {\n safePackage.bugs.url = packageJson.bugs.url;\n if (safePackage.bugs.url && !safePackage.bugs.url.endsWith('/')) {\n safePackage.bugs.url += '/';\n }\n }\n }\n }\n\n if (!safePackage.name) return;\n\n return safePackage;\n}\n\nexport function findTsConfigPath(baseDir: string, tsConfigPath?: AnyString | null): string | null {\n if (tsConfigPath === null) {\n return null;\n }\n\n if (tsConfigPath) {\n const resolved = path.isAbsolute(tsConfigPath)\n ? tsConfigPath\n : path.resolve(baseDir, tsConfigPath);\n return fs.existsSync(resolved) ? resolved : null;\n }\n\n let dir = baseDir;\n while (dir !== path.dirname(dir)) {\n const files = fs.readdirSync(dir);\n const candidates = files\n .filter((file) => file.startsWith('tsconfig') && file.endsWith('.json'))\n .sort((file) => (file === 'tsconfig.json' ? -1 : 1));\n\n if (candidates[0]) {\n return path.join(dir, candidates[0]);\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\nexport function loadTsConfig(configPath: string | null): ts.ParsedCommandLine | null {\n if (!configPath) {\n return null;\n }\n\n const raw = ts.readConfigFile(configPath, ts.sys.readFile);\n\n if (raw.error) {\n throw new Error(`Couldn't read tsconfig from path: ${configPath}`);\n }\n\n return ts.parseJsonConfigFileContent(raw.config, ts.sys, path.dirname(configPath));\n}\n","import colors from 'ansi-colors';\n\nimport { loadPackageJson } from './tsConfig';\n\nconst textAscii = `\n888 | e 888~-_ 888\n888___| e88~~8e Y88b / d8b 888 \\\\ 888\n888 | d888 88b Y888/ /Y88b 888 | 888\n888 | 8888__888 Y8/ / Y88b 888 / 888\n888 | Y888 , Y /____Y88b 888_-~ 888\n888 | \"88___/ / / Y88b 888 888\n _/\n`;\n\nconst asciiToLines = (\n ascii: string,\n options?: {\n padding?: number;\n },\n) => {\n const lines: Array<string> = [];\n const padding = Array.from<string>({ length: options?.padding ?? 0 }).fill('');\n lines.push(...padding);\n let maxLineLength = 0;\n let line = '';\n for (const char of ascii) {\n if (char === '\\n') {\n if (line) {\n lines.push(line);\n maxLineLength = Math.max(maxLineLength, line.length);\n line = '';\n }\n } else {\n line += char;\n }\n }\n lines.push(...padding);\n return { lines, maxLineLength };\n};\n\n// TODO: show ascii logo only in `--help` and `--version` commands\nexport function printCliIntro(initialDir: string, showLogo: boolean = false): void {\n const packageJson = loadPackageJson(initialDir);\n if (packageJson) {\n if (showLogo) {\n const text = asciiToLines(textAscii, { padding: 1 });\n for (const line of text.lines) {\n console.log(colors.cyan(line));\n }\n }\n console.log(colors.gray(`${packageJson.name} v${packageJson.version}`));\n }\n console.log('');\n}\n","import type { PathLike } from 'node:fs';\nimport fs from 'node:fs';\n\nexport function ensureDirSync(path: PathLike): void {\n if (!fs.existsSync(path)) {\n fs.mkdirSync(path, { recursive: true });\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport colors from 'ansi-colors';\n\nimport { ensureDirSync } from './fs';\nimport { loadPackageJson } from './tsConfig';\n\ntype IJobError = {\n error: Error;\n jobIndex: number;\n};\n\n/**\n * Represents a single configuration error.\n *\n * Used for reporting issues with a specific config instance.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Aggregates multiple config errors with their job indices for reporting.\n */\nexport class ConfigValidationError extends Error {\n readonly errors: ReadonlyArray<IJobError>;\n\n constructor(errors: Array<IJobError>) {\n super(`Found ${errors.length} configuration ${errors.length === 1 ? 'error' : 'errors'}.`);\n this.name = 'ConfigValidationError';\n this.errors = errors;\n }\n}\n\n/**\n * Represents a runtime error originating from a specific job.\n *\n * Used for reporting job-level failures that are not config validation errors.\n */\nexport class JobError extends Error {\n readonly originalError: IJobError;\n\n constructor(message: string, error: IJobError) {\n super(message);\n this.name = 'JobError';\n this.originalError = error;\n }\n}\n\nexport class HeyApiError extends Error {\n args: ReadonlyArray<unknown>;\n event: string;\n pluginName: string;\n\n constructor({\n args,\n error,\n event,\n name,\n pluginName,\n }: {\n args: unknown[];\n error: Error;\n event: string;\n name: string;\n pluginName: string;\n }) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n super(message);\n\n this.args = args;\n this.cause = error.cause;\n this.event = event;\n this.name = name || error.name;\n this.pluginName = pluginName;\n this.stack = error.stack;\n }\n}\n\nexport function logCrashReport(error: unknown, logsDir: string): string | undefined {\n if (error instanceof ConfigError || error instanceof ConfigValidationError) {\n return;\n }\n\n if (error instanceof JobError) {\n error = error.originalError.error;\n }\n\n const logName = `openapi-ts-error-${Date.now()}.log`;\n const fullDir = path.resolve(process.cwd(), logsDir);\n ensureDirSync(fullDir);\n const logPath = path.resolve(fullDir, logName);\n\n let logContent = `[${new Date().toISOString()}] `;\n\n if (error instanceof HeyApiError) {\n logContent += `${error.name} during event \"${error.event}\"\\n`;\n if (error.pluginName) {\n logContent += `Plugin: ${error.pluginName}\\n`;\n }\n logContent += `Arguments: ${JSON.stringify(error.args, null, 2)}\\n\\n`;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n logContent += `Error: ${message}\\n`;\n if (stack) {\n logContent += `Stack:\\n${stack}\\n`;\n }\n\n fs.writeFileSync(logPath, logContent);\n\n return logPath;\n}\n\nexport async function openGitHubIssueWithCrashReport(\n error: unknown,\n initialDir: string,\n): Promise<void> {\n const packageJson = loadPackageJson(initialDir);\n if (!packageJson?.bugs.url) return;\n\n if (error instanceof JobError) {\n error = error.originalError.error;\n }\n\n let body = '';\n\n if (error instanceof HeyApiError) {\n if (error.pluginName) {\n body += `**Plugin**: \\`${error.pluginName}\\`\\n`;\n }\n body += `**Event**: \\`${error.event}\\`\\n`;\n body += `**Arguments**:\\n\\`\\`\\`ts\\n${JSON.stringify(error.args, null, 2)}\\n\\`\\`\\`\\n\\n`;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n body += `**Error**: \\`${message}\\`\\n`;\n if (stack) {\n body += `\\n**Stack Trace**:\\n\\`\\`\\`\\n${stack}\\n\\`\\`\\``;\n }\n\n const search = new URLSearchParams({\n body,\n labels: 'bug ๐Ÿ”ฅ',\n title: 'Crash Report',\n });\n const url = `${packageJson.bugs.url}new?${search.toString()}`;\n const open = (await import('open')).default;\n await open(url);\n}\n\nexport function printCrashReport({\n error,\n logPath,\n}: {\n error: unknown;\n logPath: string | undefined;\n}): void {\n if (error instanceof ConfigValidationError && error.errors.length) {\n const groupByJob = new Map<number, Array<Error>>();\n for (const { error: err, jobIndex } of error.errors) {\n if (!groupByJob.has(jobIndex)) {\n groupByJob.set(jobIndex, []);\n }\n groupByJob.get(jobIndex)!.push(err);\n }\n\n for (const [jobIndex, errors] of groupByJob.entries()) {\n const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `);\n const count = errors.length;\n const baseString = colors.red(\n `Found ${count} configuration ${count === 1 ? 'error' : 'errors'}:`,\n );\n console.error(`${jobPrefix}โ—๏ธ ${baseString}`);\n errors.forEach((err, index) => {\n const itemPrefixStr = ` [${index + 1}] `;\n const itemPrefix = colors.red(itemPrefixStr);\n console.error(`${jobPrefix}${itemPrefix}${colors.white(err.message)}`);\n });\n }\n } else {\n let jobPrefix = colors.gray('[root] ');\n if (error instanceof JobError) {\n jobPrefix = colors.gray(`[Job ${error.originalError.jobIndex + 1}] `);\n error = error.originalError.error;\n }\n\n const baseString = colors.red('Failed with the message:');\n console.error(`${jobPrefix}โŒ ${baseString}`);\n const itemPrefixStr = ` `;\n const itemPrefix = colors.red(itemPrefixStr);\n console.error(\n `${jobPrefix}${itemPrefix}${typeof error === 'string' ? error : error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n\n if (logPath) {\n const jobPrefix = colors.gray('[root] ');\n console.error(`${jobPrefix}${colors.cyan('๐Ÿ“„ Crash log saved to:')} ${colors.gray(logPath)}`);\n }\n}\n\nexport async function shouldReportCrash({\n error,\n isInteractive,\n}: {\n error: unknown;\n isInteractive: boolean | undefined;\n}): Promise<boolean> {\n if (!isInteractive || error instanceof ConfigError || error instanceof ConfigValidationError) {\n return false;\n }\n\n return new Promise((resolve) => {\n const jobPrefix = colors.gray('[root] ');\n console.log(\n `${jobPrefix}${colors.yellow('๐Ÿ“ข Open a GitHub issue with crash details? (y/N):')}`,\n );\n process.stdin.setEncoding('utf8');\n process.stdin.once('data', (data: string) => {\n resolve(data.trim().toLowerCase() === 'y');\n });\n });\n}\n","import { ConfigError } from '../error';\n\nexport function checkNodeVersion(): void {\n if (typeof Bun !== 'undefined') {\n const [major] = Bun.version.split('.').map(Number);\n if (major! < 1) {\n throw new ConfigError(\n `Unsupported Bun version ${Bun.version}. Please use Bun 1.0.0 or newer.`,\n );\n }\n } else if (typeof process !== 'undefined' && process.versions?.node) {\n const [major] = process.versions.node.split('.').map(Number);\n if (major! < 20) {\n throw new ConfigError(\n `Unsupported Node version ${process.versions.node}. Please use Node 20 or newer.`,\n );\n }\n }\n}\n","import type { Input } from '../../config/input/types';\n\n// Regular expression to match Hey API Registry input formats:\n// - {organization}/{project}?{queryParams}\nconst registryRegExp = /^([\\w-]+)\\/([\\w-]+)(?:\\?([\\w=&.-]*))?$/;\n\nexport const heyApiRegistryBaseUrl = 'https://get.heyapi.dev';\n\n/**\n * Creates a full Hey API Registry URL.\n *\n * @param organization - Hey API organization slug\n * @param project - Hey API project slug\n * @param queryParams - Optional query parameters\n * @returns The full Hey API registry URL.\n */\nexport function getRegistryUrl(\n organization: string,\n project: string,\n queryParams?: string,\n): string {\n return `${heyApiRegistryBaseUrl}/${organization}/${project}${queryParams ? `?${queryParams}` : ''}`;\n}\n\nexport type Parsed = {\n organization: string;\n project: string;\n queryParams?: string;\n};\n\n/**\n * Parses a Hey API input string and extracts components.\n *\n * @param input - Hey API configuration input\n * @returns Parsed Hey API input components\n * @throws Error if the input format is invalid\n */\nexport function parseShorthand(\n input: Input & {\n path: string;\n },\n): Parsed {\n let organization = input.organization;\n let project = input.project;\n let queryParams: string | undefined;\n\n if (input.path) {\n const match = input.path.match(registryRegExp);\n\n if (!match) {\n throw new Error(\n `Invalid Hey API shorthand format. Expected \"organization/project?queryParams\" or \"organization/project\", received: ${input.path}`,\n );\n }\n\n organization = match[1];\n project = match[2];\n queryParams = match[3];\n }\n\n if (!organization) {\n throw new Error('The Hey API organization cannot be empty.');\n }\n\n if (!project) {\n throw new Error('The Hey API project cannot be empty.');\n }\n\n const result: Parsed = {\n organization,\n project,\n queryParams,\n };\n\n return result;\n}\n\n/**\n * Transforms a Hey API shorthand string to the corresponding API URL.\n *\n * @param input - Hey API configuration input\n * @returns The Hey API Registry URL\n */\nexport function inputToHeyApiPath(\n input: Input & {\n path: string;\n },\n): Partial<Input> {\n const parsed = parseShorthand(input);\n return {\n path: getRegistryUrl(parsed.organization, parsed.project, parsed.queryParams),\n registry: 'hey-api',\n };\n}\n","import type { Input } from '../../config/input/types';\n\n// Regular expression to match ReadMe API Registry input formats:\n// - @{organization}/{project}#{uuid}\n// - {uuid}\nconst registryRegExp = /^(@([\\w-]+)\\/([\\w\\-.]+)#)?([\\w-]+)$/;\n\n/**\n * Creates a full ReadMe API Registry URL.\n *\n * @param uuid - ReadMe UUID\n * @returns The full ReadMe API registry URL.\n */\nexport function getRegistryUrl(uuid: string): string {\n return `https://dash.readme.com/api/v1/api-registry/${uuid}`;\n}\n\nexport type Parsed = {\n organization?: string;\n project?: string;\n uuid: string;\n};\n\nconst namespace = 'readme';\n\n/**\n * Parses a ReadMe input string and extracts components.\n *\n * @param shorthand - ReadMe format string (@org/project#uuid or uuid)\n * @returns Parsed ReadMe input components\n * @throws Error if the input format is invalid\n */\nexport function parseShorthand(shorthand: string): Parsed {\n const match = shorthand.match(registryRegExp);\n\n if (!match) {\n throw new Error(\n `Invalid ReadMe shorthand format. Expected \"${namespace}:@organization/project#uuid\" or \"${namespace}:uuid\", received: ${namespace}:${shorthand}`,\n );\n }\n\n const [, , organization, project, uuid] = match;\n\n if (!uuid) {\n throw new Error('The ReadMe UUID cannot be empty.');\n }\n\n const result: Parsed = {\n organization,\n project,\n uuid,\n };\n\n return result;\n}\n\n/**\n * Transforms a ReadMe shorthand string to the corresponding API URL.\n *\n * @param input - ReadMe format string\n * @returns The ReadMe API Registry URL\n */\nexport function inputToReadmePath(input: string): Partial<Input> {\n const shorthand = input.slice(`${namespace}:`.length);\n const parsed = parseShorthand(shorthand);\n return {\n ...parsed,\n path: getRegistryUrl(parsed.uuid),\n registry: 'readme',\n };\n}\n","import type { Input } from '../../config/input/types';\n\n// Regular expression to match Scalar API Registry input formats:\n// - @{organization}/{project}\nconst registryRegExp = /^(@[\\w-]+)\\/([\\w.-]+)$/;\n\n/**\n * Creates a full Scalar API Registry URL.\n *\n * @param organization - Scalar organization slug\n * @param project - Scalar project slug\n * @returns The full Scalar API registry URL.\n */\nexport function getRegistryUrl(organization: string, project: string): string {\n return `https://registry.scalar.com/${organization}/apis/${project}/latest?format=json`;\n}\n\nexport type Parsed = {\n organization: string;\n project: string;\n};\n\nconst namespace = 'scalar';\n\n/**\n * Parses a Scalar input string and extracts components.\n *\n * @param shorthand - Scalar format string (@org/project)\n * @returns Parsed Scalar input components\n * @throws Error if the input format is invalid\n */\nexport function parseShorthand(shorthand: string): Parsed {\n const match = shorthand.match(registryRegExp);\n\n if (!match) {\n throw new Error(\n `Invalid Scalar shorthand format. Expected \"${namespace}:@organization/project\", received: ${namespace}:${shorthand}`,\n );\n }\n\n const [, organization, project] = match;\n\n if (!organization) {\n throw new Error('The Scalar organization cannot be empty.');\n }\n\n if (!project) {\n throw new Error('The Scalar project cannot be empty.');\n }\n\n const result: Parsed = {\n organization,\n project,\n };\n\n return result;\n}\n\n/**\n * Transforms a Scalar shorthand string to the corresponding API URL.\n *\n * @param input - Scalar format string\n * @returns The Scalar API Registry URL\n */\nexport function inputToScalarPath(input: string): Partial<Input> {\n const shorthand = input.slice(`${namespace}:`.length);\n const parsed = parseShorthand(shorthand);\n return {\n ...parsed,\n path: getRegistryUrl(parsed.organization, parsed.project),\n registry: 'scalar',\n };\n}\n","import type { Input } from '../../config/input/types';\nimport { heyApiRegistryBaseUrl, inputToHeyApiPath } from './heyApi';\nimport { inputToReadmePath } from './readme';\nimport { inputToScalarPath } from './scalar';\n\nexport function inputToApiRegistry(\n input: Input & {\n path: string;\n },\n) {\n if (input.path.startsWith('readme:')) {\n Object.assign(input, inputToReadmePath(input.path));\n return;\n }\n\n if (input.path.startsWith('scalar:')) {\n Object.assign(input, inputToScalarPath(input.path));\n return;\n }\n\n if (input.path.startsWith('.')) {\n return;\n }\n\n if (input.path.startsWith(heyApiRegistryBaseUrl)) {\n input.path = input.path.slice(heyApiRegistryBaseUrl.length + 1);\n Object.assign(input, inputToHeyApiPath(input as Input & { path: string }));\n return;\n }\n\n const parts = input.path.split('/');\n if (parts.length === 2 && parts.filter(Boolean).length === 2) {\n Object.assign(input, inputToHeyApiPath(input as Input & { path: string }));\n return;\n }\n}\n","import type { MaybeArray } from '@hey-api/types';\n\nimport { inputToApiRegistry } from '../../utils/input';\nimport { heyApiRegistryBaseUrl } from '../../utils/input/heyApi';\nimport type { Input, UserInput, UserWatch, Watch } from './types';\n\nconst defaultWatch: Watch = {\n enabled: false,\n interval: 1_000,\n timeout: 60_000,\n};\n\n// watch only remote files\nfunction getWatch(input: Pick<Input, 'path' | 'watch'>): Watch {\n let watch = { ...defaultWatch };\n\n // we cannot watch spec passed as an object\n if (typeof input.path !== 'string') {\n return watch;\n }\n\n if (typeof input.watch === 'boolean') {\n watch.enabled = input.watch;\n } else if (typeof input.watch === 'number') {\n watch.enabled = true;\n watch.interval = input.watch;\n } else if (input.watch) {\n watch = {\n ...watch,\n ...input.watch,\n };\n }\n\n return watch;\n}\n\nexport function getInput(userConfig: {\n input: MaybeArray<UserInput | Required<UserInput>['path']>;\n watch?: UserWatch;\n}): ReadonlyArray<Input> {\n const userInputs = userConfig.input instanceof Array ? userConfig.input : [userConfig.input];\n\n const inputs: Array<Input> = [];\n\n for (const userInput of userInputs) {\n let input: Input = {\n path: '',\n watch: defaultWatch,\n };\n\n if (typeof userInput === 'string') {\n input.path = userInput;\n } else if (\n userInput &&\n (userInput.path !== undefined || userInput.organization !== undefined)\n ) {\n // @ts-expect-error\n input = {\n ...input,\n path: heyApiRegistryBaseUrl,\n ...userInput,\n };\n\n if (input.watch !== undefined) {\n input.watch = getWatch(input);\n }\n } else {\n input = {\n ...input,\n path: userInput,\n };\n }\n\n if (typeof input.path === 'string') {\n inputToApiRegistry(input as Input & { path: string });\n }\n\n if (\n userConfig.watch !== undefined &&\n input.watch.enabled === defaultWatch.enabled &&\n input.watch.interval === defaultWatch.interval &&\n input.watch.timeout === defaultWatch.timeout\n ) {\n input.watch = getWatch({\n path: input.path,\n // @ts-expect-error\n watch: userConfig.watch,\n });\n }\n\n if (input.path) {\n inputs.push(input);\n }\n }\n\n return inputs;\n}\n","import colors from 'ansi-colors';\n\nimport type { Input } from './types';\n\nexport function compileInputPath(input: Omit<Input, 'watch'>) {\n const result: Pick<\n Partial<Input>,\n | 'api_key'\n | 'branch'\n | 'commit_sha'\n | 'organization'\n | 'project'\n | 'registry'\n | 'tags'\n | 'version'\n > &\n Pick<Input, 'path'> = {\n ...input,\n path: '',\n };\n\n if (input.path && (typeof input.path !== 'string' || input.registry !== 'hey-api')) {\n result.path = input.path;\n return result;\n }\n\n const [basePath, baseQuery] = input.path.split('?');\n const queryParts = (baseQuery || '').split('&');\n const queryPath = queryParts.map((part) => part.split('='));\n\n let path = basePath || '';\n if (path.endsWith('/')) {\n path = path.slice(0, path.length - 1);\n }\n\n const [, pathUrl] = path.split('://');\n const [baseUrl, organization, project] = (pathUrl || '').split('/');\n result.organization = organization || input.organization;\n result.project = project || input.project;\n\n const queryParams: Array<string> = [];\n\n const kApiKey = 'api_key';\n result.api_key =\n queryPath.find(([key]) => key === kApiKey)?.[1] || input.api_key || process.env.HEY_API_TOKEN;\n if (result.api_key) {\n queryParams.push(`${kApiKey}=${result.api_key}`);\n }\n\n const kBranch = 'branch';\n result.branch = queryPath.find(([key]) => key === kBranch)?.[1] || input.branch;\n if (result.branch) {\n queryParams.push(`${kBranch}=${result.branch}`);\n }\n\n const kCommitSha = 'commit_sha';\n result.commit_sha = queryPath.find(([key]) => key === kCommitSha)?.[1] || input.commit_sha;\n if (result.commit_sha) {\n queryParams.push(`${kCommitSha}=${result.commit_sha}`);\n }\n\n const kTags = 'tags';\n result.tags = queryPath.find(([key]) => key === kTags)?.[1]?.split(',') || input.tags;\n if (result.tags?.length) {\n queryParams.push(`${kTags}=${result.tags.join(',')}`);\n }\n\n const kVersion = 'version';\n result.version = queryPath.find(([key]) => key === kVersion)?.[1] || input.version;\n if (result.version) {\n queryParams.push(`${kVersion}=${result.version}`);\n }\n\n if (!result.organization) {\n throw new Error(\n 'missing organization - from which Hey API Platform organization do you want to generate your output?',\n );\n }\n\n if (!result.project) {\n throw new Error(\n 'missing project - from which Hey API Platform project do you want to generate your output?',\n );\n }\n\n const query = queryParams.join('&');\n const platformUrl = baseUrl || 'get.heyapi.dev';\n const isLocalhost = platformUrl.startsWith('localhost');\n const platformUrlWithProtocol = [isLocalhost ? 'http' : 'https', platformUrl].join('://');\n const compiledPath = isLocalhost\n ? [platformUrlWithProtocol, 'v1', 'get', result.organization, result.project].join('/')\n : [platformUrlWithProtocol, result.organization, result.project].join('/');\n result.path = query ? `${compiledPath}?${query}` : compiledPath;\n\n return result;\n}\n\nexport function logInputPaths(\n inputPaths: ReadonlyArray<ReturnType<typeof compileInputPath>>,\n jobIndex: number,\n): void {\n const lines: Array<string> = [];\n\n const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `);\n const count = inputPaths.length;\n const baseString = colors.cyan(`Generating from ${count} ${count === 1 ? 'input' : 'inputs'}:`);\n lines.push(`${jobPrefix}โณ ${baseString}`);\n\n inputPaths.forEach((inputPath, index) => {\n const itemPrefixStr = ` [${index + 1}] `;\n const itemPrefix = colors.cyan(itemPrefixStr);\n const detailIndent = ' '.repeat(itemPrefixStr.length);\n\n if (typeof inputPath.path !== 'string') {\n lines.push(`${jobPrefix}${itemPrefix}raw OpenAPI specification`);\n return;\n }\n\n switch (inputPath.registry) {\n case 'hey-api': {\n const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/');\n lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);\n if (inputPath.branch) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('branch:')} ${colors.green(\n inputPath.branch,\n )}`,\n );\n }\n if (inputPath.commit_sha) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('commit:')} ${colors.green(\n inputPath.commit_sha,\n )}`,\n );\n }\n if (inputPath.tags?.length) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('tags:')} ${colors.green(\n inputPath.tags.join(', '),\n )}`,\n );\n }\n if (inputPath.version) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('version:')} ${colors.green(\n inputPath.version,\n )}`,\n );\n }\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('Hey API')}`,\n );\n break;\n }\n case 'readme': {\n const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/');\n if (!baseInput) {\n lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`);\n } else {\n lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);\n }\n // @ts-expect-error\n if (inputPath.uuid) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('uuid:')} ${colors.green(\n // @ts-expect-error\n inputPath.uuid,\n )}`,\n );\n }\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('ReadMe')}`,\n );\n break;\n }\n case 'scalar': {\n const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/');\n lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('Scalar')}`,\n );\n break;\n }\n default:\n lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`);\n break;\n }\n });\n\n for (const line of lines) {\n console.log(line);\n }\n}\n","import type { Logs } from '../types/logs';\n\nexport function getLogs(userLogs: string | Logs | undefined): Logs {\n let logs: Logs = {\n file: true,\n level: 'info',\n path: process.cwd(),\n };\n\n if (typeof userLogs === 'string') {\n logs.path = userLogs;\n } else {\n logs = {\n ...logs,\n ...userLogs,\n };\n }\n\n return logs;\n}\n","import colors from 'ansi-colors';\nimport { sync } from 'cross-spawn';\n\ntype Output = {\n /**\n * The absolute path to the output folder.\n */\n path: string;\n /**\n * Post-processing commands to run on the output folder, executed in order.\n */\n postProcess: ReadonlyArray<string | UserPostProcessor>;\n};\n\nexport type UserPostProcessor = {\n /**\n * Arguments to pass to the command. Use `{{path}}` as a placeholder\n * for the output directory path.\n *\n * @example ['format', '--write', '{{path}}']\n */\n args: ReadonlyArray<string>;\n /**\n * The command to run (e.g., 'biome', 'prettier', 'eslint').\n */\n command: string;\n /**\n * Display name for logging. Defaults to the command name.\n */\n name?: string;\n};\n\nexport type PostProcessor = {\n /**\n * Arguments to pass to the command.\n */\n args: ReadonlyArray<string>;\n /**\n * The command to run.\n */\n command: string;\n /**\n * Display name for logging.\n */\n name: string;\n};\n\nexport function postprocessOutput(\n config: Output,\n postProcessors: Record<string, PostProcessor>,\n jobPrefix: string,\n): void {\n for (const processor of config.postProcess) {\n const resolved = typeof processor === 'string' ? postProcessors[processor] : processor;\n\n // TODO: show warning\n if (!resolved) continue;\n\n const name = resolved.name ?? resolved.command;\n const args = resolved.args.map((arg) => arg.replace('{{path}}', config.path));\n\n console.log(`${jobPrefix}๐Ÿงน Running ${colors.cyanBright(name)}`);\n sync(resolved.command, args);\n }\n}\n","type ObjectType<T> =\n Extract<T, Record<string, any>> extends never\n ? Record<string, any>\n : Extract<T, Record<string, any>>;\n\ntype NotArray<T> = T extends Array<any> ? never : T;\ntype NotFunction<T> = T extends (...args: Array<any>) => any ? never : T;\ntype PlainObject<T> = T extends object\n ? NotFunction<T> extends never\n ? never\n : NotArray<T> extends never\n ? never\n : T\n : never;\n\ntype MappersType<T> = {\n boolean: T extends boolean ? (value: boolean) => Partial<ObjectType<T>> : never;\n function: T extends (...args: Array<any>) => any\n ? (value: (...args: Array<any>) => any) => Partial<ObjectType<T>>\n : never;\n number: T extends number ? (value: number) => Partial<ObjectType<T>> : never;\n object?: PlainObject<T> extends never\n ? never\n : (value: Partial<PlainObject<T>>, defaultValue: PlainObject<T>) => Partial<ObjectType<T>>;\n string: T extends string ? (value: string) => Partial<ObjectType<T>> : never;\n} extends infer U\n ? { [K in keyof U as U[K] extends never ? never : K]: U[K] }\n : never;\n\ntype IsObjectOnly<T> = T extends Record<string, any> | undefined\n ? Extract<T, string | boolean | number | ((...args: Array<any>) => any)> extends never\n ? true\n : false\n : false;\n\nexport type ValueToObject = <\n T extends\n | undefined\n | string\n | boolean\n | number\n | ((...args: Array<any>) => any)\n | Record<string, any>,\n>(\n args: {\n defaultValue: ObjectType<T>;\n value: T;\n } & (IsObjectOnly<T> extends true\n ? {\n mappers?: MappersType<T>;\n }\n : {\n mappers: MappersType<T>;\n }),\n) => PlainObject<T>;\n\nconst isPlainObject = (value: unknown): value is Record<string, any> =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n typeof value !== 'function';\n\nconst mergeResult = <T>(result: ObjectType<T>, mapped: Record<string, any>): ObjectType<T> => {\n for (const [key, value] of Object.entries(mapped)) {\n if (value !== undefined && value !== '') {\n (result as Record<string, any>)[key] = value;\n }\n }\n return result;\n};\n\nexport const valueToObject: ValueToObject = ({ defaultValue, mappers, value }) => {\n let result = { ...defaultValue };\n\n switch (typeof value) {\n case 'boolean':\n if (mappers && 'boolean' in mappers) {\n const mapper = mappers.boolean as (value: boolean) => Record<string, any>;\n result = mergeResult(result, mapper(value));\n }\n break;\n case 'function':\n if (mappers && 'function' in mappers) {\n const mapper = mappers.function as (\n value: (...args: Array<any>) => any,\n ) => Record<string, any>;\n result = mergeResult(result, mapper(value as (...args: Array<any>) => any));\n }\n break;\n case 'number':\n if (mappers && 'number' in mappers) {\n const mapper = mappers.number as (value: number) => Record<string, any>;\n result = mergeResult(result, mapper(value));\n }\n break;\n case 'string':\n if (mappers && 'string' in mappers) {\n const mapper = mappers.string as (value: string) => Record<string, any>;\n result = mergeResult(result, mapper(value));\n }\n break;\n case 'object':\n if (isPlainObject(value)) {\n if (mappers && 'object' in mappers && typeof mappers.object === 'function') {\n const mapper = mappers.object as (\n value: Record<string, any>,\n defaultValue: ObjectType<any>,\n ) => Partial<ObjectType<any>>;\n result = mergeResult(result, mapper(value, defaultValue));\n } else {\n result = mergeResult(result, value);\n }\n }\n break;\n }\n\n return result as any;\n};\n","import { valueToObject } from '../../utils/config';\nimport type { SourceConfig, UserSourceConfig } from './types';\n\nexport function resolveSource(config: { source?: boolean | UserSourceConfig }): SourceConfig {\n const source = valueToObject({\n defaultValue: {\n enabled: Boolean(config.source),\n extension: 'json',\n fileName: 'source',\n serialize: (input) => JSON.stringify(input, null, 2),\n },\n mappers: {\n boolean: (enabled) => ({ enabled }),\n },\n value: config.source,\n });\n if (source.path === undefined || source.path === true) {\n source.path = '';\n } else if (source.path === false) {\n source.path = null;\n }\n return source as SourceConfig;\n}\n","import { valueToObject } from '../utils/config';\nimport type { Parser, UserParser } from './types';\n\nexport const defaultPaginationKeywords = [\n 'after',\n 'before',\n 'cursor',\n 'offset',\n 'page',\n 'start',\n] as const;\n\nexport function getParser(userConfig: { parser?: UserParser }): Parser {\n const parser = valueToObject({\n defaultValue: {\n hooks: {},\n pagination: {\n keywords: defaultPaginationKeywords,\n },\n transforms: {\n enums: {\n case: 'PascalCase',\n enabled: false,\n mode: 'root',\n name: '{{name}}Enum',\n },\n propertiesRequiredByDefault: false,\n readWrite: {\n enabled: true,\n requests: {\n case: 'preserve',\n name: '{{name}}Writable',\n },\n responses: {\n case: 'preserve',\n name: '{{name}}',\n },\n },\n schemaName: undefined,\n },\n validate_EXPERIMENTAL: false,\n },\n mappers: {\n object: (fields, defaultValue) => ({\n ...fields,\n pagination: valueToObject({\n defaultValue: {\n ...(defaultValue.pagination as Extract<\n typeof defaultValue.pagination,\n Record<string, unknown>\n >),\n },\n value: fields.pagination,\n }),\n transforms: valueToObject({\n defaultValue: {\n ...(defaultValue.transforms as Extract<\n typeof defaultValue.transforms,\n Record<string, unknown>\n >),\n },\n mappers: {\n object: (fields, defaultValue) => ({\n ...fields,\n enums: valueToObject({\n defaultValue: {\n ...(defaultValue.enums as Extract<\n typeof defaultValue.enums,\n Record<string, unknown>\n >),\n enabled:\n fields.enums !== undefined\n ? Boolean(fields.enums)\n : (\n defaultValue.enums as Extract<\n typeof defaultValue.enums,\n Record<string, unknown>\n >\n ).enabled,\n },\n mappers: {\n boolean: (enabled) => ({ enabled }),\n string: (mode) => ({ mode }),\n },\n value: fields.enums,\n }),\n propertiesRequiredByDefault:\n fields.propertiesRequiredByDefault !== undefined\n ? fields.propertiesRequiredByDefault\n : defaultValue.propertiesRequiredByDefault,\n readWrite: valueToObject({\n defaultValue: {\n ...(defaultValue.readWrite as Extract<\n typeof defaultValue.readWrite,\n Record<string, unknown>\n >),\n enabled:\n fields.readWrite !== undefined\n ? Boolean(fields.readWrite)\n : (\n defaultValue.readWrite as Extract<\n typeof defaultValue.readWrite,\n Record<string, unknown>\n >\n ).enabled,\n },\n mappers: {\n boolean: (enabled) => ({ enabled }),\n object: (fields, defaultValue) => ({\n ...fields,\n requests: valueToObject({\n defaultValue: {\n ...(defaultValue.requests as Extract<\n typeof defaultValue.requests,\n Record<string, unknown>\n >),\n },\n mappers: {\n function: (name) => ({ name }),\n string: (name) => ({ name }),\n },\n value: fields.requests,\n }),\n responses: valueToObject({\n defaultValue: {\n ...(defaultValue.responses as Extract<\n typeof defaultValue.responses,\n Record<string, unknown>\n >),\n },\n mappers: {\n function: (name) => ({ name }),\n string: (name) => ({ name }),\n },\n value: fields.responses,\n }),\n }),\n },\n value: fields.readWrite,\n }),\n schemaName:\n fields.schemaName !== undefined ? fields.schemaName : defaultValue.schemaName,\n }),\n },\n value: fields.transforms,\n }),\n validate_EXPERIMENTAL:\n fields.validate_EXPERIMENTAL === true ? 'warn' : fields.validate_EXPERIMENTAL,\n }),\n },\n value: userConfig.parser,\n });\n return parser as Parser;\n}\n","import type { RangeOptions, SemVer } from 'semver';\nimport * as semver from 'semver';\n\nexport type Dependency = {\n /**\n * Get the installed version of a package.\n * @param name The name of the package to get the version for.\n * @returns A SemVer object containing version information, or undefined if the package is not installed\n * or the version string is invalid.\n */\n getVersion: (name: string) => SemVer | undefined;\n /**\n * Check if a given package is installed in the project.\n * @param name The name of the package to check.\n */\n isInstalled: (name: string) => boolean;\n /**\n * Check if the installed version of a package or a given SemVer object satisfies a semver range.\n * @param nameOrVersion The name of the package to check, or a SemVer object.\n * @param range The semver range to check against.\n * @returns True if the version satisfies the range, false otherwise.\n */\n satisfies: (\n nameOrVersion: string | SemVer,\n range: string,\n optionsOrLoose?: boolean | RangeOptions,\n ) => boolean;\n};\n\nexport const satisfies: typeof semver.satisfies = (...args) => semver.satisfies(...args);\n\nexport function dependencyFactory(dependencies: Record<string, string>): Dependency {\n return {\n getVersion: (name) => {\n const version = dependencies[name];\n if (!version) return;\n try {\n let parsed = semver.parse(version);\n if (parsed) return parsed;\n\n const min = semver.minVersion(version);\n if (min) return min;\n\n parsed = semver.coerce(version);\n if (parsed) return parsed;\n } catch {\n // noop\n }\n return;\n },\n isInstalled: (name) => Boolean(dependencies[name]),\n satisfies: (nameOrVersion, range, optionsOrLoose) => {\n const version =\n typeof nameOrVersion === 'string' ? dependencies[nameOrVersion] : nameOrVersion;\n return version ? satisfies(version, range, optionsOrLoose) : false;\n },\n };\n}\n","import type { Graph } from '../graph';\n\nconst analyzeStructure = (graph: Graph) => {\n let maxDepth = 0;\n let maxChildren = 0;\n\n const computeDepth = (pointer: string, depth: number): void => {\n maxDepth = Math.max(maxDepth, depth);\n\n const children = Array.from(graph.nodes.entries())\n .filter(([, nodeInfo]) => nodeInfo.parentPointer === pointer)\n .map(([childPointer]) => childPointer);\n\n maxChildren = Math.max(maxChildren, children.length);\n\n for (const childPointer of children) {\n computeDepth(childPointer, depth + 1);\n }\n };\n\n const totalNodes = graph.nodes.size;\n if (graph.nodes.has('#')) {\n computeDepth('#', 1);\n }\n\n return { maxChildren, maxDepth, totalNodes };\n};\n\nconst exportForVisualization = (graph: Graph) => {\n const childrenMap = new Map<string, string[]>();\n\n for (const [pointer, nodeInfo] of graph.nodes) {\n if (!nodeInfo.parentPointer) continue;\n if (!childrenMap.has(nodeInfo.parentPointer)) {\n childrenMap.set(nodeInfo.parentPointer, []);\n }\n childrenMap.get(nodeInfo.parentPointer)!.push(pointer);\n }\n\n const nodes = Array.from(graph.nodes.keys()).map((pointer) => ({\n children: childrenMap.get(pointer)?.length ?? 0,\n childrenPointers: childrenMap.get(pointer) || [],\n pointer,\n }));\n\n return nodes;\n};\n\nexport const graph = {\n analyzeStructure,\n exportForVisualization,\n} as const;\n","import type { Context } from './context';\nimport type { Pagination } from './pagination';\nimport type { IR } from './types';\n\nconst getPaginationSchema = ({\n context,\n parameter,\n}: {\n context: Context;\n parameter: IR.ParameterObject;\n}): IR.SchemaObject | undefined => {\n if (!parameter.pagination) {\n return;\n }\n\n if (parameter.pagination === true) {\n return parameter.schema;\n }\n\n let schema = parameter.schema;\n if (schema.$ref) {\n schema = context.resolveIrRef<IR.SchemaObject>(schema.$ref);\n }\n\n return schema.properties![parameter.pagination]!;\n};\n\nexport const hasParameterGroupObjectRequired = (\n parameterGroup?: Record<string, IR.ParameterObject>,\n): boolean => {\n for (const name in parameterGroup) {\n if (parameterGroup[name]!.required) {\n return true;\n }\n }\n\n return false;\n};\n\nexport const hasParametersObjectRequired = (\n parameters: IR.ParametersObject | undefined,\n): boolean => {\n if (!parameters) {\n return false;\n }\n\n if (hasParameterGroupObjectRequired(parameters.cookie)) {\n return true;\n }\n\n if (hasParameterGroupObjectRequired(parameters.header)) {\n return true;\n }\n\n if (hasParameterGroupObjectRequired(parameters.path)) {\n return true;\n }\n\n if (hasParameterGroupObjectRequired(parameters.query)) {\n return true;\n }\n\n return false;\n};\n\nexport const parameterWithPagination = ({\n context,\n parameters,\n}: {\n context: Context;\n parameters: IR.ParametersObject | undefined;\n}): Pagination | undefined => {\n if (!parameters) {\n return;\n }\n\n for (const name in parameters.cookie) {\n const parameter = parameters.cookie[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n for (const name in parameters.header) {\n const parameter = parameters.header[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n for (const name in parameters.path) {\n const parameter = parameters.path[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n for (const name in parameters.query) {\n const parameter = parameters.query[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n return;\n};\n","import type { IR } from './types';\n\n/**\n * Ensure we don't produce redundant types, e.g. string | string.\n */\nexport function deduplicateSchema<T extends IR.SchemaObject>({\n detectFormat = true,\n schema,\n}: {\n detectFormat?: boolean;\n schema: T;\n}): T {\n if (!schema.items) {\n return schema;\n }\n\n const uniqueItems: Array<IR.SchemaObject> = [];\n const typeIds: Array<string> = [];\n\n for (const item of schema.items) {\n // skip nested schemas for now, handle if necessary\n if ((!item.type && item.items) || schema.type === 'tuple') {\n uniqueItems.push(item);\n continue;\n }\n\n if (\n // no `type` might still include `$ref` or `const`\n !item.type ||\n item.type === 'boolean' ||\n item.type === 'integer' ||\n item.type === 'null' ||\n item.type === 'number' ||\n item.type === 'string' ||\n item.type === 'unknown' ||\n item.type === 'void'\n ) {\n // const needs namespace to handle empty string values, otherwise\n // fallback would equal an actual value and we would skip an item\n const constant = item.const !== undefined ? `const-${item.const}` : '';\n const format = item.format !== undefined && detectFormat ? `format-${item.format}` : '';\n\n // Include validation constraints in the type ID to avoid incorrect deduplication\n const constraints = [\n item.minLength !== undefined ? `minLength-${item.minLength}` : '',\n item.maxLength !== undefined ? `maxLength-${item.maxLength}` : '',\n item.minimum !== undefined ? `minimum-${item.minimum}` : '',\n item.maximum !== undefined ? `maximum-${item.maximum}` : '',\n item.exclusiveMinimum !== undefined ? `exclusiveMinimum-${item.exclusiveMinimum}` : '',\n item.exclusiveMaximum !== undefined ? `exclusiveMaximum-${item.exclusiveMaximum}` : '',\n item.minItems !== undefined ? `minItems-${item.minItems}` : '',\n item.maxItems !== undefined ? `maxItems-${item.maxItems}` : '',\n item.pattern !== undefined ? `pattern-${item.pattern}` : '',\n ].join('');\n\n const typeId = `${item.$ref ?? ''}${item.type ?? ''}${constant}${format}${constraints}`;\n if (!typeIds.includes(typeId)) {\n typeIds.push(typeId);\n uniqueItems.push(item);\n }\n continue;\n }\n\n uniqueItems.push(item);\n }\n\n let result = { ...schema };\n result.items = uniqueItems;\n\n if (\n result.items.length <= 1 &&\n result.type !== 'array' &&\n result.type !== 'enum' &&\n result.type !== 'tuple'\n ) {\n // bring the only item up to clean up the schema\n const liftedSchema = result.items[0];\n delete result.logicalOperator;\n delete result.items;\n result = {\n ...result,\n ...liftedSchema,\n };\n }\n\n // exclude unknown if it's the only type left\n if (result.type === 'unknown') {\n return {} as T;\n }\n\n return result;\n}\n","import type { IR } from './types';\n\n/**\n * Simply adds `items` to the schema. Also handles setting the logical operator\n * and avoids setting it for a single item or tuples.\n */\nexport function addItemsToSchema({\n items,\n logicalOperator = 'or',\n mutateSchemaOneItem = false,\n schema,\n}: {\n items: Array<IR.SchemaObject>;\n logicalOperator?: IR.SchemaObject['logicalOperator'];\n mutateSchemaOneItem?: boolean;\n schema: IR.SchemaObject;\n}): IR.SchemaObject {\n if (!items.length) {\n return schema;\n }\n\n if (schema.type === 'tuple') {\n schema.items = items;\n return schema;\n }\n\n if (items.length !== 1) {\n schema.items = items;\n schema.logicalOperator = logicalOperator;\n return schema;\n }\n\n if (mutateSchemaOneItem) {\n // bring composition up to avoid extraneous brackets\n schema = {\n ...schema,\n ...items[0],\n };\n return schema;\n }\n\n schema.items = items;\n return schema;\n}\n","import type { Context } from './context';\nimport type { Pagination } from './pagination';\nimport { hasParametersObjectRequired, parameterWithPagination } from './parameter';\nimport { deduplicateSchema } from './schema';\nimport type { IR } from './types';\nimport { addItemsToSchema } from './utils';\n\nexport const hasOperationDataRequired = (operation: IR.OperationObject): boolean => {\n if (hasParametersObjectRequired(operation.parameters)) {\n return true;\n }\n\n if (operation.body?.required) {\n return true;\n }\n\n return false;\n};\n\nexport const createOperationKey = ({ method, path }: { method: string; path: string }) =>\n `${method.toUpperCase()} ${path}`;\n\nexport const operationPagination = ({\n context,\n operation,\n}: {\n context: Context;\n operation: IR.OperationObject;\n}): Pagination | undefined => {\n const body = operation.body;\n\n if (!body || !body.pagination) {\n return parameterWithPagination({\n context,\n parameters: operation.parameters,\n });\n }\n\n if (body.pagination === true) {\n return {\n in: 'body',\n name: 'body',\n schema: body.schema,\n };\n }\n\n const schema = body.schema;\n const resolvedSchema = schema.$ref\n ? context.resolveIrRef<IR.RequestBodyObject | IR.SchemaObject>(schema.$ref)\n : schema;\n\n const finalSchema = 'schema' in resolvedSchema ? resolvedSchema.schema : resolvedSchema;\n const paginationProp = finalSchema?.properties?.[body.pagination];\n\n if (!paginationProp) {\n return parameterWithPagination({\n context,\n parameters: operation.parameters,\n });\n }\n\n return {\n in: 'body',\n name: body.pagination,\n schema: paginationProp,\n };\n};\n\ntype StatusGroup = '1XX' | '2XX' | '3XX' | '4XX' | '5XX' | 'default';\n\nexport const statusCodeToGroup = ({ statusCode }: { statusCode: string }): StatusGroup => {\n switch (statusCode) {\n case '1XX':\n return '1XX';\n case '2XX':\n return '2XX';\n case '3XX':\n return '3XX';\n case '4XX':\n return '4XX';\n case '5XX':\n return '5XX';\n case 'default':\n return 'default';\n default:\n return `${statusCode[0]}XX` as StatusGroup;\n }\n};\n\ninterface OperationResponsesMap {\n /**\n * A deduplicated union of all error types. Unknown types are omitted.\n */\n error?: IR.SchemaObject;\n /**\n * An object containing a map of status codes for each error type.\n */\n errors?: IR.SchemaObject;\n /**\n * A deduplicated union of all response types. Unknown types are omitted.\n */\n response?: IR.SchemaObject;\n /**\n * An object containing a map of status codes for each response type.\n */\n responses?: IR.SchemaObject;\n}\n\nexport const operationResponsesMap = (operation: IR.OperationObject): OperationResponsesMap => {\n const result: OperationResponsesMap = {};\n\n if (!operation.responses) {\n return result;\n }\n\n const errors: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'> = {\n properties: {},\n type: 'object',\n };\n\n const responses: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'> = {\n properties: {},\n type: 'object',\n };\n\n // store default response to be evaluated last\n let defaultResponse: IR.ResponseObject | undefined;\n\n for (const name in operation.responses) {\n const response = operation.responses[name]!;\n\n switch (statusCodeToGroup({ statusCode: name })) {\n case '1XX':\n case '3XX':\n // TODO: parser - handle informational and redirection status codes\n break;\n case '2XX':\n responses.properties[name] = response.schema;\n break;\n case '4XX':\n case '5XX':\n errors.properties[name] = response.schema;\n break;\n case 'default':\n defaultResponse = response;\n break;\n }\n }\n\n // infer default response type\n if (defaultResponse) {\n let inferred = false;\n\n // assume default is intended for success if none exists yet\n if (!Object.keys(responses.properties).length) {\n responses.properties.default = defaultResponse.schema;\n inferred = true;\n }\n\n const description = (defaultResponse.schema.description ?? '').toLocaleLowerCase();\n const $ref = (defaultResponse.schema.$ref ?? '').toLocaleLowerCase();\n\n // TODO: parser - this could be rewritten using regular expressions\n const successKeywords = ['success'];\n if (\n successKeywords.some((keyword) => description.includes(keyword) || $ref.includes(keyword))\n ) {\n responses.properties.default = defaultResponse.schema;\n inferred = true;\n }\n\n // TODO: parser - this could be rewritten using regular expressions\n const errorKeywords = ['error', 'problem'];\n if (errorKeywords.some((keyword) => description.includes(keyword) || $ref.includes(keyword))) {\n errors.properties.default = defaultResponse.schema;\n inferred = true;\n }\n\n // if no keyword match, assume default schema is intended for error\n if (!inferred) {\n errors.properties.default = defaultResponse.schema;\n }\n }\n\n const errorKeys = Object.keys(errors.properties);\n if (errorKeys.length) {\n errors.required = errorKeys;\n result.errors = errors;\n\n let errorUnion = addItemsToSchema({\n items: Object.values(errors.properties),\n mutateSchemaOneItem: true,\n schema: {},\n });\n errorUnion = deduplicateSchema({ schema: errorUnion });\n if (Object.keys(errorUnion).length && errorUnion.type !== 'unknown') {\n result.error = errorUnion;\n }\n }\n\n const responseKeys = Object.keys(responses.properties);\n if (responseKeys.length) {\n responses.required = responseKeys;\n result.responses = responses;\n\n let responseUnion = addItemsToSchema({\n items: Object.values(responses.properties),\n mutateSchemaOneItem: true,\n schema: {},\n });\n responseUnion = deduplicateSchema({ schema: responseUnion });\n if (Object.keys(responseUnion).length && responseUnion.type !== 'unknown') {\n result.response = responseUnion;\n }\n }\n\n return result;\n};\n","import type { Casing, NamingConfig, NamingRule } from './types';\n\nconst uppercaseRegExp = /[\\p{Lu}]/u;\nconst lowercaseRegExp = /[\\p{Ll}]/u;\nconst identifierRegExp = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst separatorsRegExp = /[_.$+:\\- `\\\\[\\](){}\\\\/]+/;\n\nconst leadingSeparatorsRegExp = new RegExp(`^${separatorsRegExp.source}`);\nconst separatorsAndIdentifierRegExp = new RegExp(\n `${separatorsRegExp.source}${identifierRegExp.source}`,\n 'gu',\n);\nconst numbersAndIdentifierRegExp = new RegExp(`\\\\d+${identifierRegExp.source}`, 'gu');\n\nconst preserveCase = (value: string, casing: Casing) => {\n let isLastCharLower = false;\n let isLastCharUpper = false;\n let isLastLastCharUpper = false;\n let isLastLastCharPreserved = false;\n\n const separator = casing === 'snake_case' || casing === 'SCREAMING_SNAKE_CASE' ? '_' : '-';\n\n for (let index = 0; index < value.length; index++) {\n const character = value[index]!;\n isLastLastCharPreserved = index > 2 ? value[index - 3] === separator : true;\n\n let nextIndex = index + 1;\n let nextCharacter = value[nextIndex];\n separatorsRegExp.lastIndex = 0;\n while (nextCharacter && separatorsRegExp.test(nextCharacter)) {\n nextIndex += 1;\n nextCharacter = value[nextIndex];\n }\n const isSeparatorBeforeNextCharacter = nextIndex !== index + 1;\n\n lowercaseRegExp.lastIndex = 0;\n uppercaseRegExp.lastIndex = 0;\n if (\n uppercaseRegExp.test(character) &&\n (isLastCharLower ||\n (nextCharacter &&\n !isSeparatorBeforeNextCharacter &&\n nextCharacter !== 's' &&\n lowercaseRegExp.test(nextCharacter)))\n ) {\n // insert separator behind character\n value = `${value.slice(0, index)}${separator}${value.slice(index)}`;\n index++;\n isLastLastCharUpper = isLastCharUpper;\n isLastCharLower = false;\n isLastCharUpper = true;\n } else if (\n isLastCharUpper &&\n isLastLastCharUpper &&\n lowercaseRegExp.test(character) &&\n !isLastLastCharPreserved &&\n // naive detection of plurals\n !(\n character === 's' &&\n (!nextCharacter || nextCharacter.toLocaleLowerCase() !== nextCharacter)\n )\n ) {\n // insert separator 2 characters behind\n value = `${value.slice(0, index - 1)}${separator}${value.slice(index - 1)}`;\n isLastLastCharUpper = isLastCharUpper;\n isLastCharLower = true;\n isLastCharUpper = false;\n } else {\n const characterLower = character.toLocaleLowerCase();\n const characterUpper = character.toLocaleUpperCase();\n isLastLastCharUpper = isLastCharUpper;\n isLastCharLower = characterLower === character && characterUpper !== character;\n isLastCharUpper = characterUpper === character && characterLower !== character;\n }\n }\n\n return value;\n};\n\n/**\n * Convert a string to the specified casing.\n *\n * @param value - The string to convert\n * @param casing - The target casing\n * @param options - Additional options\n * @returns The converted string\n */\nexport function toCase(\n value: string,\n casing: Casing | undefined,\n options: {\n /**\n * If leading separators have a semantic meaning, we might not want to\n * remove them.\n */\n stripLeadingSeparators?: boolean;\n } = {},\n): string {\n const stripLeadingSeparators = options.stripLeadingSeparators ?? true;\n\n let result = value.trim();\n\n if (!result.length || !casing || casing === 'preserve') {\n return result;\n }\n\n if (result.length === 1) {\n separatorsRegExp.lastIndex = 0;\n if (separatorsRegExp.test(result)) {\n return '';\n }\n\n return casing === 'PascalCase' || casing === 'SCREAMING_SNAKE_CASE'\n ? result.toLocaleUpperCase()\n : result.toLocaleLowerCase();\n }\n\n const hasUpperCase = result !== result.toLocaleLowerCase();\n\n if (hasUpperCase) {\n result = preserveCase(result, casing);\n }\n\n if (stripLeadingSeparators || result[0] !== value[0]) {\n result = result.replace(leadingSeparatorsRegExp, '');\n }\n\n result =\n casing === 'SCREAMING_SNAKE_CASE' ? result.toLocaleUpperCase() : result.toLocaleLowerCase();\n\n if (casing === 'PascalCase') {\n result = `${result.charAt(0).toLocaleUpperCase()}${result.slice(1)}`;\n }\n\n if (casing === 'snake_case' || casing === 'SCREAMING_SNAKE_CASE') {\n result = result.replaceAll(separatorsAndIdentifierRegExp, (match, identifier, offset) => {\n if (offset === 0 && !stripLeadingSeparators) {\n return match;\n }\n return `_${identifier}`;\n });\n\n if (result[result.length - 1] === '_') {\n // strip trailing underscore\n result = result.slice(0, result.length - 1);\n }\n } else {\n separatorsAndIdentifierRegExp.lastIndex = 0;\n numbersAndIdentifierRegExp.lastIndex = 0;\n\n result = result.replaceAll(numbersAndIdentifierRegExp, (match, _, offset) => {\n if (['_', '-', '.'].includes(result.charAt(offset + match.length))) {\n return match;\n }\n\n return match.toLocaleUpperCase();\n });\n\n result = result.replaceAll(separatorsAndIdentifierRegExp, (match, identifier, offset) => {\n if (offset === 0 && !stripLeadingSeparators && match[0] && value.startsWith(match[0])) {\n return match;\n }\n return identifier.toLocaleUpperCase();\n });\n }\n\n return result;\n}\n\n/**\n * Normalize a NamingRule to NamingConfig.\n */\nexport function resolveNaming(rule: NamingRule | undefined): NamingConfig {\n if (!rule) {\n return {};\n }\n if (typeof rule === 'string' || typeof rule === 'function') {\n return { name: rule };\n }\n return rule;\n}\n\n/**\n * Apply naming configuration to a value.\n *\n * Casing is applied first, then transformation.\n */\nexport function applyNaming(value: string, config: NamingConfig): string {\n let result = value;\n\n const casing = config.casing ?? config.case;\n\n if (config.name) {\n if (typeof config.name === 'function') {\n result = config.name(result);\n } else {\n // TODO: refactor so there's no need for separators?\n const separator = !casing || casing === 'preserve' ? '' : '-';\n result = config.name.replace('{{name}}', `${separator}${result}${separator}`);\n }\n }\n\n // TODO: apply case before name?\n return toCase(result, casing);\n}\n","import type { Context } from '../../../ir/context';\nimport { createOperationKey } from '../../../ir/operation';\nimport { toCase } from '../../../utils/naming/naming';\nimport type { State } from '../types/state';\n\nexport const httpMethods = [\n 'delete',\n 'get',\n 'head',\n 'options',\n 'patch',\n 'post',\n 'put',\n 'trace',\n] as const;\n\n/**\n * Sanitizes namespace identifiers so they are valid TypeScript identifiers of a certain form.\n *\n * 1: Remove any leading characters that are illegal as starting character of a typescript identifier.\n * 2: Replace illegal characters in remaining part of type name with hyphen (-).\n *\n * Step 1 should perhaps instead also replace illegal characters with underscore, or prefix with it, like sanitizeEnumName\n * does. The way this is now one could perhaps end up removing all characters, if all are illegal start characters. It\n * would be sort of a breaking change to do so, though, previously generated code might change then.\n *\n * JavaScript identifier regexp pattern retrieved from https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers\n *\n * The output of this is expected to be converted to PascalCase\n *\n * @deprecated\n */\nexport const sanitizeNamespaceIdentifier = (name: string) =>\n name\n .replace(/^[^\\p{ID_Start}]+/u, '')\n .replace(/[^$\\u200c\\u200d\\p{ID_Continue}]/gu, '-')\n .replace(/[$+]/g, '-');\n\n/**\n * Returns an operation ID to use across the application. By default, we try\n * to use the provided ID. If it's not provided or the SDK is configured\n * to exclude it, we generate operation ID from its location.\n *\n * @deprecated\n */\nexport function operationToId({\n context,\n count = 1,\n id,\n method,\n path,\n state,\n}: {\n context: Context;\n count?: number;\n id: string | undefined;\n method: string;\n path: string;\n state: Pick<State, 'ids'>;\n}): string {\n let result: string;\n\n const { output } = context.config;\n const targetCase =\n (output !== undefined && typeof output === 'object' && 'case' in output\n ? output.case\n : undefined) ?? 'camelCase';\n\n if (\n id &&\n (!context.config.plugins['@hey-api/sdk'] ||\n // TODO: needs to be refactored...\n // @ts-expect-error\n (context.config.plugins['@hey-api/sdk'].config.operations &&\n // @ts-expect-error\n typeof context.config.plugins['@hey-api/sdk'].config.operations !== 'function' &&\n // @ts-expect-error\n typeof context.config.plugins['@hey-api/sdk'].config.operations === 'object' &&\n // @ts-expect-error\n context.config.plugins['@hey-api/sdk'].config.operations.nesting === 'operationId'))\n ) {\n result = toCase(sanitizeNamespaceIdentifier(id), targetCase);\n } else {\n const pathWithoutPlaceholders = path\n .replace(/{(.*?)}/g, 'by-$1')\n // replace slashes with hyphens for camelcase method at the end\n .replace(/[/:+]/g, '-');\n\n result = toCase(`${method}-${pathWithoutPlaceholders}`, targetCase);\n }\n\n if (count > 1) {\n result = `${result}${count}`;\n }\n\n if (state.ids.has(result)) {\n return operationToId({\n context,\n count: count + 1,\n id,\n method,\n path,\n state,\n });\n }\n\n state.ids.set(result, createOperationKey({ method, path }));\n\n return result;\n}\n","import colors from 'ansi-colors';\n\nimport type { IR } from '../ir/types';\nimport { httpMethods } from '../openApi/shared/utils/operation';\n\nexport interface PrintOptions {\n /**\n * Indentation depth for `JSON.stringify()` when printing objects.\n *\n * @default 2\n */\n depth?: number;\n /**\n * Which section of the IR to print. Use 'all' to print every section.\n *\n * @default 'all'\n */\n section?: keyof IR.Model | 'all';\n /**\n * How much detail to print.\n *\n * - `summary` โ†’ only keys, names, operationIds, status codes\n * - `full` โ†’ dump full JSON structures\n *\n * @default 'summary'\n */\n verbosity?: 'full' | 'summary';\n}\n\nconst indent = (level: number) => ' '.repeat(level);\n\nconst log = (message: string, level?: number) => console.log(`${indent(level ?? 0)}${message}`);\n\nconst print = (ir: IR.Model, options: PrintOptions = {}) => {\n const { depth = 2, section = 'all', verbosity = 'summary' } = options;\n\n const printObject = (\n obj: unknown,\n level: number,\n kind: 'responses' | 'requestBody' | 'schema' | 'generic' = 'generic',\n ) => {\n if (verbosity === 'summary' && obj && typeof obj === 'object') {\n if (kind === 'responses') {\n const count = Object.keys(obj).length;\n const noun = count === 1 ? 'code' : 'codes';\n log(`responses: ${colors.yellow(`${count} ${noun}`)}`, level);\n } else if (kind === 'requestBody') {\n log(`requestBody: ${Object.keys(obj).join(', ')}`, level);\n } else if (kind === 'schema') {\n log(`schema keys: ${Object.keys(obj).join(', ')}`, level);\n } else {\n log(`keys: ${Object.keys(obj).join(', ')}`, level);\n }\n } else {\n log(JSON.stringify(obj, null, depth), level);\n }\n };\n\n const printPathItem = (\n key: string,\n item: IR.PathItemObject | IR.ReferenceObject,\n base: number = 1,\n ) => {\n if ('$ref' in item) {\n log(`${colors.cyan(key)} is a $ref โ†’ ${colors.yellow(item.$ref)}`, base);\n return;\n }\n\n for (const method of Object.keys(item) as Array<keyof IR.PathItemObject>) {\n if (!httpMethods.includes(method)) continue;\n\n const operation = item[method]!;\n log(\n `${colors.green(method.toUpperCase())} ${colors.cyan(key)} (${colors.magenta(operation.operationId ?? '')})`,\n base,\n );\n\n if (operation.body) printObject(operation.body, base + 1, 'requestBody');\n if (operation.responses) printObject(operation.responses, base + 1, 'responses');\n }\n };\n\n const sections =\n section === 'all' ? (Object.keys(ir) as unknown as ReadonlyArray<keyof IR.Model>) : [section];\n\n for (const section of sections) {\n switch (section) {\n case 'components':\n if (ir.components?.schemas) {\n log(`Components: ${Object.keys(ir.components.schemas).length} schemas`);\n for (const [, schema] of Object.entries(ir.components.schemas)) {\n printObject(schema, 1, 'schema');\n }\n }\n break;\n case 'paths': {\n const paths = ir.paths || {};\n log(`paths (${Object.keys(paths).length} items):`);\n for (const [path, item] of Object.entries(paths)) {\n printPathItem(path, item);\n }\n break;\n }\n case 'servers':\n break;\n case 'webhooks': {\n const webhooks = ir.webhooks || {};\n log(`webhooks (${Object.keys(webhooks).length} items):`);\n for (const [path, item] of Object.entries(webhooks)) {\n printPathItem(path, item);\n }\n break;\n }\n }\n }\n};\n\nexport const ir = {\n print,\n} as const;\n","import { graph } from './graph';\nimport { ir } from './ir';\n\nexport const debugTools = {\n graph,\n ir,\n};\n","import { getResolvedInput, sendRequest } from '@hey-api/json-schema-ref-parser';\nimport type { MaybeArray } from '@hey-api/types';\n\nimport type { Input } from './config/input/types';\nimport type { WatchValues } from './types/watch';\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nconst mergeHeaders = (\n ...headers: Array<\n | RequestInit['headers']\n | Record<string, MaybeArray<string | number | boolean> | null | undefined | unknown>\n | undefined\n >\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e. their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype SpecResponse = {\n arrayBuffer: ArrayBuffer | undefined;\n error?: never;\n resolvedInput: ReturnType<typeof getResolvedInput>;\n response?: never;\n};\n\ntype SpecError = {\n arrayBuffer?: never;\n error: 'not-modified' | 'not-ok';\n resolvedInput?: never;\n response: Response;\n};\n\n/**\n * @internal\n */\nexport async function getSpec({\n fetchOptions,\n inputPath,\n timeout,\n watch,\n}: {\n fetchOptions?: RequestInit;\n inputPath: Input['path'];\n timeout: number | undefined;\n watch: WatchValues;\n}): Promise<SpecResponse | SpecError> {\n const resolvedInput = getResolvedInput({ pathOrUrlOrSchema: inputPath });\n\n let arrayBuffer: ArrayBuffer | undefined;\n // boolean signals whether the file has **definitely** changed\n let hasChanged: boolean | undefined;\n let response: Response | undefined;\n\n if (resolvedInput.type === 'url') {\n // do NOT send HEAD request on first run or if unsupported\n if (watch.lastValue && watch.isHeadMethodSupported !== false) {\n try {\n const request = await sendRequest({\n fetchOptions: {\n method: 'HEAD',\n ...fetchOptions,\n headers: mergeHeaders(fetchOptions?.headers, watch.headers),\n },\n timeout,\n url: resolvedInput.path,\n });\n\n if (request.response.status >= 300) {\n return {\n error: 'not-ok',\n response: request.response,\n };\n }\n\n response = request.response;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: 'not-ok',\n response: new Response(message, { status: 500 }),\n };\n }\n\n if (!response.ok && watch.isHeadMethodSupported) {\n // assume the server is no longer running\n // do nothing, it might be restarted later\n return {\n error: 'not-ok',\n response,\n };\n }\n\n if (watch.isHeadMethodSupported === undefined) {\n watch.isHeadMethodSupported = response.ok;\n }\n\n if (response.status === 304) {\n return {\n error: 'not-modified',\n response,\n };\n }\n\n if (hasChanged === undefined) {\n const eTag = response.headers.get('ETag');\n if (eTag) {\n hasChanged = eTag !== watch.headers.get('If-None-Match');\n\n if (hasChanged) {\n watch.headers.set('If-None-Match', eTag);\n }\n }\n }\n\n if (hasChanged === undefined) {\n const lastModified = response.headers.get('Last-Modified');\n if (lastModified) {\n hasChanged = lastModified !== watch.headers.get('If-Modified-Since');\n\n if (hasChanged) {\n watch.headers.set('If-Modified-Since', lastModified);\n }\n }\n }\n\n // we definitely know the input has not changed\n if (hasChanged === false) {\n return {\n error: 'not-modified',\n response,\n };\n }\n }\n\n try {\n const request = await sendRequest({\n fetchOptions: {\n method: 'GET',\n ...fetchOptions,\n },\n timeout,\n url: resolvedInput.path,\n });\n\n if (request.response.status >= 300) {\n return {\n error: 'not-ok',\n response: request.response,\n };\n }\n\n response = request.response;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: 'not-ok',\n response: new Response(message, { status: 500 }),\n };\n }\n\n if (!response.ok) {\n // assume the server is no longer running\n // do nothing, it might be restarted later\n return {\n error: 'not-ok',\n response,\n };\n }\n\n arrayBuffer = response.body ? await response.arrayBuffer() : new ArrayBuffer(0);\n\n if (hasChanged === undefined) {\n const content = new TextDecoder().decode(arrayBuffer);\n hasChanged = content !== watch.lastValue;\n watch.lastValue = content;\n }\n } else {\n // we do not support watch mode for files or raw spec data\n if (!watch.lastValue) {\n watch.lastValue = resolvedInput.type;\n } else {\n hasChanged = false;\n }\n }\n\n if (hasChanged === false) {\n return {\n error: 'not-modified',\n response: response!,\n };\n }\n\n return {\n arrayBuffer,\n resolvedInput,\n };\n}\n","export class MinHeap {\n private heap: Array<string> = [];\n\n constructor(public declIndex: Map<string, number>) {}\n\n isEmpty(): boolean {\n return !this.heap.length;\n }\n\n pop(): string | undefined {\n const [top] = this.heap;\n if (!this.heap.length) return;\n const last = this.heap.pop()!;\n if (!this.heap.length) return top;\n this.heap[0] = last;\n this.sinkDown(0);\n return top;\n }\n\n push(item: string): void {\n this.heap.push(item);\n this.bubbleUp(this.heap.length - 1);\n }\n\n private bubbleUp(index: number): void {\n const heap = this.heap;\n while (index > 0) {\n const parent = Math.floor((index - 1) / 2);\n const parentVal = heap[parent]!;\n const curVal = heap[index]!;\n if (this.declIndex.get(parentVal)! <= this.declIndex.get(curVal)!) break;\n heap[parent] = curVal;\n heap[index] = parentVal;\n index = parent;\n }\n }\n\n private sinkDown(index: number): void {\n const heap = this.heap;\n const len = heap.length;\n while (true) {\n const left = 2 * index + 1;\n const right = 2 * index + 2;\n let smallest = index;\n if (left < len) {\n const leftVal = heap[left]!;\n const smallestVal = heap[smallest]!;\n if (this.declIndex.get(leftVal)! < this.declIndex.get(smallestVal)!) smallest = left;\n }\n if (right < len) {\n const rightVal = heap[right]!;\n const smallestVal = heap[smallest]!;\n if (this.declIndex.get(rightVal)! < this.declIndex.get(smallestVal)!) smallest = right;\n }\n if (smallest === index) break;\n const tmp = heap[smallest]!;\n heap[smallest] = heap[index]!;\n heap[index] = tmp;\n index = smallest;\n }\n }\n}\n","import { MinHeap } from '../utils/minHeap';\nimport type { GetPointerPriorityFn, WalkFn } from './types/walk';\n\n/**\n * Walk the nodes of the graph in declaration (insertion) order.\n * This is a cheap alternative to `walkTopological` when dependency ordering\n * is not required and the caller only wants nodes in the order they were\n * added to the graph.\n */\nconst walkDeclarations: WalkFn = (graph, callback, options) => {\n const pointers = Array.from(graph.nodes.keys());\n\n if (options?.preferGroups && options.preferGroups.length > 0) {\n // emit nodes that match each preferred group in order, preserving insertion order\n const emitted = new Set<string>();\n if (options.matchPointerToGroup) {\n for (const kind of options.preferGroups) {\n for (const pointer of pointers) {\n const result = options.matchPointerToGroup(pointer);\n if (!result.matched) continue;\n if (result.kind === kind) {\n emitted.add(pointer);\n callback(pointer, graph.nodes.get(pointer)!);\n }\n }\n }\n }\n\n // emit anything not covered by the preferGroups (in declaration order)\n for (const pointer of pointers) {\n if (emitted.has(pointer)) continue;\n callback(pointer, graph.nodes.get(pointer)!);\n }\n return;\n }\n\n // fallback: simple declaration order\n for (const pointer of pointers) {\n callback(pointer, graph.nodes.get(pointer)!);\n }\n};\n\n/**\n * Walks the nodes of the graph in topological order (dependencies before dependents).\n * Calls the callback for each node pointer in order.\n * Nodes in cycles are grouped together and emitted in arbitrary order within the group.\n *\n * @param graph - The dependency graph\n * @param callback - Function to call for each node pointer\n */\nconst walkTopological: WalkFn = (graph, callback, options) => {\n // stable Kahn's algorithm that respects declaration order as a tiebreaker.\n const pointers = Array.from(graph.nodes.keys());\n // base insertion order\n const baseIndex = new Map<string, number>();\n pointers.forEach((pointer, index) => baseIndex.set(pointer, index));\n\n // composite decl index: group priority then base insertion order\n const declIndex = new Map<string, number>();\n for (const pointer of pointers) {\n const priority = options?.getPointerPriority?.(pointer) ?? 10;\n const composite = priority * 1_000_000 + (baseIndex.get(pointer) ?? 0);\n declIndex.set(pointer, composite);\n }\n\n // build dependency sets for each pointer\n const depsOf = new Map<string, Set<string>>();\n for (const pointer of pointers) {\n const raw = graph.subtreeDependencies?.get(pointer) ?? new Set();\n const filtered = new Set<string>();\n for (const rawPointer of raw) {\n if (rawPointer === pointer) continue; // ignore self-dependencies for ordering\n if (graph.nodes.has(rawPointer)) {\n filtered.add(rawPointer);\n }\n }\n depsOf.set(pointer, filtered);\n }\n\n // build inDegree and dependents adjacency\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n for (const pointer of pointers) {\n inDegree.set(pointer, 0);\n }\n for (const [pointer, deps] of depsOf) {\n inDegree.set(pointer, deps.size);\n for (const d of deps) {\n if (!dependents.has(d)) {\n dependents.set(d, new Set());\n }\n dependents.get(d)!.add(pointer);\n }\n }\n\n // sort pointers by declaration order\n const sortByDecl = (arr: Array<string>) =>\n arr.sort((a, b) => declIndex.get(a)! - declIndex.get(b)!);\n\n // initialize queue with zero-inDegree nodes in declaration order\n // use min-heap prioritized by declaration index to avoid repeated full sorts\n const heap = new MinHeap(declIndex);\n for (const pointer of pointers) {\n if ((inDegree.get(pointer) ?? 0) === 0) {\n heap.push(pointer);\n }\n }\n\n const emitted = new Set<string>();\n const order: Array<string> = [];\n\n while (!heap.isEmpty()) {\n const cur = heap.pop()!;\n if (emitted.has(cur)) continue;\n emitted.add(cur);\n order.push(cur);\n\n const deps = dependents.get(cur);\n if (!deps) continue;\n\n for (const dep of deps) {\n const v = (inDegree.get(dep) ?? 0) - 1;\n inDegree.set(dep, v);\n if (v === 0) {\n heap.push(dep);\n }\n }\n }\n\n // emit remaining nodes (cycles) in declaration order\n const remaining = pointers.filter((pointer) => !emitted.has(pointer));\n sortByDecl(remaining);\n for (const pointer of remaining) {\n emitted.add(pointer);\n order.push(pointer);\n }\n\n // prefer specified groups when safe\n let finalOrder = order;\n if (options?.preferGroups && options.preferGroups.length > 0) {\n // build group priority map (lower = earlier)\n const groupPriority = new Map<string, number>();\n for (let i = 0; i < options.preferGroups.length; i++) {\n const k = options.preferGroups[i];\n if (k) {\n groupPriority.set(k, i);\n }\n }\n\n const getGroup: GetPointerPriorityFn = (pointer) => {\n if (options.matchPointerToGroup) {\n const result = options.matchPointerToGroup(pointer);\n if (result.matched) {\n return groupPriority.has(result.kind)\n ? groupPriority.get(result.kind)!\n : options.preferGroups!.length;\n }\n }\n return options.preferGroups!.length;\n };\n\n // proposed order: sort by (groupPriority, originalIndex)\n const proposed = [...order].sort((a, b) => {\n const ga = getGroup(a);\n const gb = getGroup(b);\n return ga !== gb ? ga - gb : order.indexOf(a) - order.indexOf(b);\n });\n\n // build quick lookup of original index and proposed index\n const proposedIndex = new Map<string, number>();\n for (let i = 0; i < proposed.length; i++) {\n proposedIndex.set(proposed[i]!, i);\n }\n\n // only validate edges where group(dep) > group(node)\n const violated = (() => {\n for (const [node, deps] of depsOf) {\n for (const dep of deps) {\n const gDep = getGroup(dep);\n const gNode = getGroup(node);\n if (gDep <= gNode) continue; // not a crossing edge, cannot be violated by grouping\n const pDep = proposedIndex.get(dep)!;\n const pNode = proposedIndex.get(node)!;\n if (pDep >= pNode) {\n return true;\n }\n }\n }\n return false;\n })();\n\n if (!violated) {\n finalOrder = proposed;\n }\n }\n\n for (const pointer of finalOrder) {\n callback(pointer, graph.nodes.get(pointer)!);\n }\n};\n\nexport const walk: WalkFn = (graph, callback, options) => {\n if (options?.order === 'topological') {\n return walkTopological(graph, callback, options);\n }\n return walkDeclarations(graph, callback, options);\n};\n","import type { GetPointerPriorityFn, MatchPointerToGroupFn } from '../graph';\n\nexport const irTopLevelKinds = [\n 'operation',\n 'parameter',\n 'requestBody',\n 'schema',\n 'server',\n 'webhook',\n] as const;\n\nexport type IrTopLevelKind = (typeof irTopLevelKinds)[number];\n\n/**\n * Checks if a pointer matches a known top-level IR component (schema, parameter, etc) and returns match info.\n *\n * @param pointer - The IR pointer string (e.g. '#/components/schemas/Foo')\n * @param kind - (Optional) The component kind to check\n * @returns { matched: true, kind: IrTopLevelKind } | { matched: false } - Whether it matched, and the matched kind if so\n */\nexport const matchIrPointerToGroup: MatchPointerToGroupFn<IrTopLevelKind> = (pointer, kind) => {\n const patterns: Record<IrTopLevelKind, RegExp> = {\n operation: /^#\\/paths\\/[^/]+\\/(get|put|post|delete|options|head|patch|trace)$/,\n parameter: /^#\\/components\\/parameters\\/[^/]+$/,\n requestBody: /^#\\/components\\/requestBodies\\/[^/]+$/,\n schema: /^#\\/components\\/schemas\\/[^/]+$/,\n server: /^#\\/servers\\/(\\d+|[^/]+)$/,\n webhook: /^#\\/webhooks\\/[^/]+\\/(get|put|post|delete|options|head|patch|trace)$/,\n };\n if (kind) {\n return patterns[kind].test(pointer) ? { kind, matched: true } : { matched: false };\n }\n for (const key of Object.keys(patterns)) {\n const kind = key as IrTopLevelKind;\n if (patterns[kind].test(pointer)) {\n return { kind, matched: true };\n }\n }\n return { matched: false };\n};\n\n// default grouping preference (earlier groups emitted first when safe)\nexport const preferGroups = [\n 'server',\n 'schema',\n 'parameter',\n 'requestBody',\n 'operation',\n 'webhook',\n] satisfies ReadonlyArray<IrTopLevelKind>;\n\ntype KindPriority = Record<IrTopLevelKind, number>;\n\n// default group priority (lower = earlier)\n// built from `preferGroups` so the priority order stays in sync with the prefer-groups array.\nconst kindPriority: KindPriority = (() => {\n const partial: Partial<KindPriority> = {};\n for (let i = 0; i < preferGroups.length; i++) {\n const k = preferGroups[i];\n if (k) partial[k] = i;\n }\n // Ensure all known kinds exist in the map (fall back to a high index).\n for (const k of irTopLevelKinds) {\n if (partial[k] === undefined) {\n partial[k] = preferGroups.length;\n }\n }\n return partial as KindPriority;\n})();\n\nconst defaultPriority = 10;\n\nexport const getIrPointerPriority: GetPointerPriorityFn = (pointer) => {\n const result = matchIrPointerToGroup(pointer);\n if (result.matched) {\n return kindPriority[result.kind] ?? defaultPriority;\n }\n return defaultPriority;\n};\n","const jsonPointerSlash = /~1/g;\nconst jsonPointerTilde = /~0/g;\n\n/**\n * Returns the reusable component name from `$ref`.\n */\nexport function refToName($ref: string): string {\n const path = jsonPointerToPath($ref);\n const name = path[path.length - 1]!;\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n return decodeURI(name);\n}\n\n/**\n * Encodes a path segment for use in a JSON Pointer (RFC 6901).\n *\n * - Replaces all '~' with '~0'.\n * - Replaces all '/' with '~1'.\n *\n * This ensures that path segments containing these characters are safely\n * represented in JSON Pointer strings.\n *\n * @param segment - The path segment (string or number) to encode.\n * @returns The encoded segment as a string.\n */\nexport function encodeJsonPointerSegment(segment: string | number): string {\n return String(segment).replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * Converts a JSON Pointer string (RFC 6901) to an array of path segments.\n *\n * - Removes the leading '#' if present.\n * - Splits the pointer on '/'.\n * - Decodes '~1' to '/' and '~0' to '~' in each segment.\n * - Returns an empty array for the root pointer ('#' or '').\n *\n * @param pointer - The JSON Pointer string to convert (e.g., '#/components/schemas/Foo').\n * @returns An array of decoded path segments.\n */\nexport function jsonPointerToPath(pointer: string): ReadonlyArray<string> {\n let clean = pointer.trim();\n if (clean.startsWith('#')) {\n clean = clean.slice(1);\n }\n if (clean.startsWith('/')) {\n clean = clean.slice(1);\n }\n if (!clean) {\n return [];\n }\n return clean\n .split('/')\n .map((part) => part.replace(jsonPointerSlash, '/').replace(jsonPointerTilde, '~'));\n}\n\n/**\n * Normalizes a JSON Pointer string to a canonical form.\n *\n * - Ensures the pointer starts with '#'.\n * - Removes trailing slashes (except for root).\n * - Collapses multiple consecutive slashes into one.\n * - Trims whitespace from the input.\n *\n * @param pointer - The JSON Pointer string to normalize.\n * @returns The normalized JSON Pointer string.\n */\nexport function normalizeJsonPointer(pointer: string): string {\n let normalized = pointer.trim();\n if (!normalized.startsWith('#')) {\n normalized = `#${normalized}`;\n }\n // Remove trailing slashes (except for root)\n if (normalized.length > 1 && normalized.endsWith('/')) {\n normalized = normalized.slice(0, -1);\n }\n // Collapse multiple slashes\n normalized = normalized.replace(/\\/+/g, '/');\n return normalized;\n}\n\n/**\n * Encode path as JSON Pointer (RFC 6901).\n *\n * @param path\n * @returns\n */\nexport function pathToJsonPointer(path: ReadonlyArray<string | number>): string {\n const segments = path.map(encodeJsonPointerSegment).join('/');\n return '#' + (segments ? `/${segments}` : '');\n}\n\n/**\n * Checks if a $ref or path points to a top-level component (not a deep path reference).\n *\n * Top-level component references:\n * - OpenAPI 3.x: #/components/{type}/{name} (3 segments)\n * - OpenAPI 2.0: #/definitions/{name} (2 segments)\n *\n * Deep path references (4+ segments for 3.x, 3+ for 2.0) should be inlined\n * because they don't have corresponding registered symbols.\n *\n * @param refOrPath - The $ref string or path array to check\n * @returns true if the ref points to a top-level component, false otherwise\n */\nexport function isTopLevelComponent(refOrPath: string | ReadonlyArray<string | number>): boolean {\n const path = refOrPath instanceof Array ? refOrPath : jsonPointerToPath(refOrPath);\n\n // OpenAPI 3.x: #/components/{type}/{name} = 3 segments\n if (path[0] === 'components') {\n return path.length === 3;\n }\n\n // OpenAPI 2.0: #/definitions/{name} = 2 segments\n if (path[0] === 'definitions') {\n return path.length === 2;\n }\n\n return false;\n}\n\nexport function resolveRef<T>({ $ref, spec }: { $ref: string; spec: Record<string, any> }): T {\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n const path = jsonPointerToPath(decodeURI($ref));\n\n let current = spec;\n\n for (const part of path) {\n const segment = part as keyof typeof current;\n if (current[segment] === undefined) {\n throw new Error(`Reference not found: ${$ref}`);\n }\n current = current[segment];\n }\n\n return current as T;\n}\n","import path from 'node:path';\n\nimport type {\n IProject,\n Node,\n Symbol,\n SymbolIdentifier,\n SymbolIn,\n SymbolMeta,\n} from '@hey-api/codegen-core';\n\nimport type { Dependency } from '../../../config/utils/dependencies';\nimport { HeyApiError } from '../../../error';\nimport type { MatchPointerToGroupFn, WalkOptions } from '../../../graph';\nimport { walk } from '../../../graph';\nimport type { Context } from '../../../ir/context';\nimport type { IrTopLevelKind } from '../../../ir/graph';\nimport {\n getIrPointerPriority,\n irTopLevelKinds,\n matchIrPointerToGroup,\n preferGroups,\n} from '../../../ir/graph';\nimport type { ExampleIntent } from '../../../ir/intents';\nimport type { IR } from '../../../ir/types';\nimport type { Hooks } from '../../../parser/hooks';\nimport type { Plugin, PluginConfigMap } from '../../../plugins/types';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport type { BaseEvent, WalkEvent } from '../types/instance';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface PluginInstanceTypes {}\n\n/**\n * Resolves the Node type, falling back to base Node if not augmented.\n */\ntype ResolvedNode = 'Node' extends keyof PluginInstanceTypes\n ? // @ts-expect-error ts cannot resolve conditional types properly here\n PluginInstanceTypes['Node']\n : Node;\n\nconst defaultGetFilePath = (symbol: Symbol): string | undefined => {\n if (!symbol.meta?.pluginName || typeof symbol.meta.pluginName !== 'string') {\n return;\n }\n if (symbol.meta.pluginName.startsWith('@hey-api/client-')) {\n return 'client';\n }\n if (symbol.meta.pluginName === '@hey-api/typescript') {\n return 'types';\n }\n if (symbol.meta.pluginName.startsWith('@hey-api/')) {\n return symbol.meta.pluginName.split('/')[1];\n }\n return symbol.meta.pluginName;\n};\n\nconst defaultGetKind: Required<Required<Hooks>['operations']>['getKind'] = (operation) => {\n switch (operation.method) {\n case 'delete':\n case 'patch':\n case 'post':\n case 'put':\n return ['mutation'];\n case 'get':\n return ['query'];\n default:\n return;\n }\n};\n\ntype EventHooks = {\n [K in keyof Required<NonNullable<Hooks['events']>>]: Array<\n NonNullable<NonNullable<Hooks['events']>[K]>\n >;\n};\n\nexport class PluginInstance<T extends Plugin.Types = Plugin.Types> {\n api: T['api'];\n config: Omit<T['resolvedConfig'], 'name'>;\n context: Context;\n dependencies: Required<Plugin.Config<T>>['dependencies'] = [];\n private eventHooks: EventHooks;\n gen: IProject;\n private handler: Plugin.Config<T>['handler'];\n name: T['resolvedConfig']['name'];\n /**\n * The package metadata and utilities for the current context, constructed\n * from the provided dependencies. Used for managing package-related\n * information such as name, version, and dependency resolution during\n * code generation.\n */\n package: Dependency;\n\n constructor(\n props: Pick<Required<Plugin.Config<T>>, 'config' | 'dependencies' | 'handler'> & {\n api?: T['api'];\n context: Context;\n gen: IProject;\n name: string;\n },\n ) {\n this.api = props.api ?? {};\n this.config = props.config;\n this.context = props.context;\n this.dependencies = props.dependencies;\n this.eventHooks = this.buildEventHooks();\n this.gen = props.gen;\n this.handler = props.handler;\n this.name = props.name;\n this.package = props.context.package;\n }\n\n external(\n resource: Required<SymbolMeta>['resource'],\n meta?: Omit<SymbolMeta, 'category' | 'resource'>,\n ): Symbol {\n return this.gen.symbols.reference({\n ...meta,\n category: 'external',\n resource,\n });\n }\n\n /**\n * Iterates over various input elements as specified by the event types, in\n * a specific order: servers, schemas, parameters, request bodies, then\n * operations.\n *\n * This ensures, for example, that schemas are always processed before\n * operations, which may reference them.\n *\n * @template TKind - The event type(s) to yield. Defaults to all event types.\n * @param events - The event types to walk over. If none are provided, all event types are included.\n * @param callback - Function to execute for each event.\n *\n * @example\n * // Iterate over all operations and schemas\n * plugin.forEach('operation', 'schema', (event) => {\n * if (event.type === 'operation') {\n * // handle operation\n * } else if (event.type === 'schema') {\n * // handle schema\n * }\n * });\n */\n forEach<TKind extends IrTopLevelKind = IrTopLevelKind>(\n ...args: [...events: ReadonlyArray<TKind>, callback: (event: WalkEvent<TKind>) => void]\n ): void;\n forEach<TKind extends IrTopLevelKind = IrTopLevelKind>(\n ...args: [\n ...events: ReadonlyArray<TKind>,\n callback: (event: WalkEvent<TKind>) => void,\n options: WalkOptions<TKind>,\n ]\n ): void;\n forEach<TKind extends IrTopLevelKind = IrTopLevelKind>(\n ...args: [\n ...events: ReadonlyArray<TKind>,\n callback: (event: WalkEvent<TKind>) => void,\n options: any,\n ]\n ): void {\n if (!this.context.graph) {\n throw new Error('No graph available in context');\n }\n\n let callback: (event: WalkEvent<TKind>) => void;\n let events: ReadonlyArray<TKind>;\n let options: WalkOptions<TKind> = {\n getPointerPriority: getIrPointerPriority,\n // default functions operate on the full union of kinds; cast them\n // to the WalkOptions generic to keep strict typing for callers.\n matchPointerToGroup: matchIrPointerToGroup as unknown as MatchPointerToGroupFn<TKind>,\n order: 'topological',\n preferGroups: preferGroups as unknown as ReadonlyArray<TKind>,\n };\n if (typeof args[args.length - 1] === 'function') {\n events = args.slice(0, -1);\n callback = args[args.length - 1];\n } else {\n events = args.slice(0, -2);\n callback = args[args.length - 2];\n options = {\n ...options,\n ...args[args.length - 1],\n };\n }\n const eventSet = new Set(events.length ? events : irTopLevelKinds);\n\n walk(\n this.context.graph,\n (pointer, nodeInfo) => {\n const result = matchIrPointerToGroup(pointer);\n if (!result.matched || !eventSet.has(result.kind)) return;\n let event: WalkEvent | undefined;\n const baseEvent: BaseEvent = {\n _path: jsonPointerToPath(pointer),\n pointer,\n tags: nodeInfo.tags ? Array.from(nodeInfo.tags) : undefined,\n };\n switch (result.kind) {\n case 'operation':\n event = {\n ...baseEvent,\n method: nodeInfo.key as keyof IR.PathItemObject,\n operation: nodeInfo.node as IR.OperationObject,\n path: baseEvent._path[1] as string,\n type: result.kind,\n } satisfies WalkEvent<'operation'>;\n break;\n case 'parameter':\n event = {\n ...baseEvent,\n name: nodeInfo.key as string,\n parameter: nodeInfo.node as IR.ParameterObject,\n type: result.kind,\n } satisfies WalkEvent<'parameter'>;\n break;\n case 'requestBody':\n event = {\n ...baseEvent,\n name: nodeInfo.key as string,\n requestBody: nodeInfo.node as IR.RequestBodyObject,\n type: result.kind,\n } satisfies WalkEvent<'requestBody'>;\n break;\n case 'schema':\n event = {\n ...baseEvent,\n name: nodeInfo.key as string,\n schema: nodeInfo.node as IR.SchemaObject,\n type: result.kind,\n } satisfies WalkEvent<'schema'>;\n break;\n case 'server':\n event = {\n ...baseEvent,\n server: nodeInfo.node as IR.ServerObject,\n type: result.kind,\n } satisfies WalkEvent<'server'>;\n break;\n case 'webhook':\n event = {\n ...baseEvent,\n key: baseEvent._path[1] as string,\n method: nodeInfo.key as keyof IR.PathItemObject,\n operation: nodeInfo.node as IR.OperationObject,\n type: result.kind,\n } satisfies WalkEvent<'webhook'>;\n break;\n }\n if (event) {\n try {\n callback(event as WalkEvent<TKind>);\n } catch (error) {\n this.forEachError(error, event);\n }\n }\n },\n options,\n );\n }\n\n /**\n * Retrieves a registered plugin instance by its name from the context. This\n * allows plugins to access other plugins that have been registered in the\n * same context, enabling cross-plugin communication and dependencies.\n *\n * @param name Plugin name as defined in the configuration.\n * @returns The plugin instance if found, undefined otherwise.\n */\n getPlugin<TName extends keyof PluginConfigMap>(\n name: TName,\n ): TName extends any ? PluginInstance<PluginConfigMap[TName]> | undefined : never {\n return this.context.plugins[name] as any;\n }\n\n /**\n * Retrieves a registered plugin instance by its name from the context. This\n * allows plugins to access other plugins that have been registered in the\n * same context, enabling cross-plugin communication and dependencies.\n *\n * @param name Plugin name as defined in the configuration.\n * @returns The plugin instance if found, throw otherwise.\n */\n getPluginOrThrow<TName extends keyof PluginConfigMap>(\n name: TName,\n ): TName extends any ? PluginInstance<PluginConfigMap[TName]> : never {\n const plugin = this.getPlugin(name);\n if (!plugin) throw new Error(`plugin not found ${name}`);\n return plugin as any;\n }\n\n getSymbol(identifier: SymbolIdentifier): Symbol | undefined {\n return this.gen.symbols.get(identifier);\n }\n\n hooks = {\n operation: {\n isMutation: (operation: IR.OperationObject): boolean =>\n this.isOperationKind(operation, 'mutation'),\n isQuery: (operation: IR.OperationObject): boolean => this.isOperationKind(operation, 'query'),\n },\n };\n\n /**\n * Registers an intent in the context's intent list.\n *\n * @param intent The intent to be registered.\n * @returns void\n */\n intent(intent: ExampleIntent): void {\n this.context.intents.push(intent);\n }\n\n isSymbolRegistered(identifier: SymbolIdentifier): boolean {\n return this.gen.symbols.isRegistered(identifier);\n }\n\n /**\n * Sets or adds a node to the project graph.\n *\n * @param node The node to be added or updated in the project graph.\n * @param index The index at which to update the node. If undefined, the node will be added.\n * @returns The index of the added node or void if updated.\n */\n node<T extends number | undefined = undefined>(\n node: Node | null,\n index?: T,\n ): T extends number ? void : number {\n for (const hook of this.eventHooks['node:set:before']) {\n hook({ node, plugin: this as any });\n }\n const result =\n index !== undefined ? this.gen.nodes.update(index, node) : this.gen.nodes.add(node);\n for (const hook of this.eventHooks['node:set:after']) {\n hook({ node, plugin: this as any });\n }\n return result as T extends number ? void : number;\n }\n\n querySymbol(filter: SymbolMeta): Symbol<ResolvedNode> | undefined {\n return this.gen.symbols.query(filter)[0] as Symbol<ResolvedNode> | undefined;\n }\n\n referenceSymbol(meta: SymbolMeta): Symbol<ResolvedNode> {\n return this.gen.symbols.reference(meta) as Symbol<ResolvedNode>;\n }\n\n /**\n * @deprecated use `plugin.symbol()` instead\n */\n registerSymbol(symbol: SymbolIn): Symbol<ResolvedNode> {\n return this.symbol(symbol.name, symbol) as Symbol<ResolvedNode>;\n }\n\n /**\n * Executes plugin's handler function.\n */\n async run(): Promise<void> {\n for (const hook of this.eventHooks['plugin:handler:before']) {\n hook({ plugin: this as any });\n }\n await this.handler({ plugin: this });\n for (const hook of this.eventHooks['plugin:handler:after']) {\n hook({ plugin: this as any });\n }\n }\n\n symbol(name: SymbolIn['name'], symbol?: Omit<SymbolIn, 'name'>): Symbol<ResolvedNode> {\n const symbolIn: SymbolIn = {\n ...symbol,\n meta: {\n pluginName: path.isAbsolute(this.name) ? 'custom' : this.name,\n ...symbol?.meta,\n },\n name,\n };\n if (symbolIn.getExportFromFilePath === undefined) {\n symbolIn.getExportFromFilePath = this.getSymbolExportFromFilePath.bind(this);\n }\n if (symbolIn.getFilePath === undefined) {\n symbolIn.getFilePath = this.getSymbolFilePath.bind(this);\n }\n for (const hook of this.eventHooks['symbol:register:before']) {\n hook({ plugin: this as any, symbol: symbolIn });\n }\n const symbolOut = this.gen.symbols.register(symbolIn);\n for (const hook of this.eventHooks['symbol:register:after']) {\n hook({ plugin: this as any, symbol: symbolOut });\n }\n return symbolOut as Symbol<ResolvedNode>;\n }\n\n /**\n * Registers a symbol only if it does not already exist based on the provided\n * metadata. This prevents duplicate symbols from being created in the project.\n */\n symbolOnce(name: SymbolIn['name'], symbol?: Omit<SymbolIn, 'name'>): Symbol {\n const meta = {\n ...symbol?.meta,\n };\n if (symbol?.external) {\n meta.category = 'external';\n meta.resource = symbol.external;\n }\n const existing = this.querySymbol(meta);\n if (existing) return existing;\n return this.symbol(name, { ...symbol, meta });\n }\n\n private buildEventHooks(): EventHooks {\n const result: EventHooks = {\n 'node:set:after': [],\n 'node:set:before': [],\n 'plugin:handler:after': [],\n 'plugin:handler:before': [],\n 'symbol:register:after': [],\n 'symbol:register:before': [],\n };\n const scopes = [this.config['~hooks']?.events, this.context.config.parser.hooks.events];\n for (const scope of scopes) {\n if (!scope) continue;\n for (const [key, value] of Object.entries(scope)) {\n if (value) {\n result[key as keyof typeof result].push(value.bind(scope) as any);\n }\n }\n }\n return result;\n }\n\n private forEachError(error: unknown, event: WalkEvent) {\n const originalError = error instanceof Error ? error : new Error(String(error));\n throw new HeyApiError({\n args: [event],\n error: originalError,\n event: event.type,\n name: 'Error',\n pluginName: this.name,\n });\n }\n\n private getSymbolExportFromFilePath(symbol: Symbol): ReadonlyArray<string> | undefined {\n const hooks = [this.config['~hooks']?.symbols, this.context.config.parser.hooks.symbols];\n for (const hook of hooks) {\n const result = hook?.getExportFromFilePath?.(symbol);\n if (result !== undefined) return result;\n }\n\n // default logic below\n const entryFile = this.context.config.output.indexFile ?? this.context.config.output.entryFile;\n if (symbol.external || !entryFile) return;\n\n const includeInEntry = this.config.exportFromIndex ?? this.config.includeInEntry;\n if (\n (typeof includeInEntry === 'boolean' && !includeInEntry) ||\n (typeof includeInEntry === 'function' && !includeInEntry(symbol))\n ) {\n return;\n }\n\n const language = symbol.node?.language;\n if (!language) return;\n\n const moduleEntryName = this.gen.moduleEntryNames[language];\n if (!moduleEntryName) return;\n\n return [moduleEntryName];\n }\n\n private getSymbolFilePath(symbol: Symbol): string | undefined {\n const hooks = [this.config['~hooks']?.symbols, this.context.config.parser.hooks.symbols];\n for (const hook of hooks) {\n const result = hook?.getFilePath?.(symbol);\n if (result !== undefined) return result;\n }\n return defaultGetFilePath(symbol);\n }\n\n private isOperationKind(operation: IR.OperationObject, kind: 'mutation' | 'query'): boolean {\n const method = kind === 'query' ? 'isQuery' : 'isMutation';\n const hooks = [\n this.config['~hooks']?.operations?.[method],\n this.config['~hooks']?.operations?.getKind,\n this.context.config.parser.hooks.operations?.[method],\n this.context.config.parser.hooks.operations?.getKind,\n defaultGetKind,\n ];\n for (const hook of hooks) {\n if (hook) {\n const result = hook(operation);\n if (result !== undefined) {\n return typeof result === 'boolean' ? result : result.includes(kind);\n }\n }\n }\n return false;\n }\n}\n","import type { Logger, Project } from '@hey-api/codegen-core';\n\nimport type { AnyConfig } from '../config/shared';\nimport type { Dependency } from '../config/utils/dependencies';\nimport { dependencyFactory } from '../config/utils/dependencies';\nimport type { Graph } from '../graph';\nimport { PluginInstance } from '../plugins/shared/utils/instance';\nimport type { Plugin, PluginConfigMap, PluginNames } from '../plugins/types';\nimport { resolveRef } from '../utils/ref';\nimport type { ExampleIntent } from './intents';\nimport type { IR } from './types';\n\nexport class Context<Spec extends Record<string, any> = any, Config extends AnyConfig = AnyConfig> {\n /**\n * Configuration for parsing and generating the output. This\n * is a mix of user-provided and default values.\n */\n config: Config;\n /**\n * The code generation project instance used to manage files, symbols,\n */\n gen: Project;\n /**\n * The dependency graph built from the intermediate representation.\n */\n graph: Graph | undefined;\n /**\n * Intents declared by plugins.\n */\n intents: Array<ExampleIntent> = [];\n /**\n * Intermediate representation model obtained from `spec`.\n */\n ir: IR.Model = {};\n /**\n * Logger instance.\n */\n logger: Logger;\n /**\n * The package metadata and utilities for the current context, constructed\n * from the provided dependencies. Used for managing package-related\n * information such as name, version, and dependency resolution during\n * code generation.\n */\n package: Dependency;\n /**\n * A map of registered plugin instances, keyed by plugin name. Plugins are\n * registered through the `registerPlugin` method and can be accessed by\n * their configured name from the config.\n */\n plugins: Partial<Record<PluginNames, PluginInstance<PluginConfigMap[keyof PluginConfigMap]>>> =\n {};\n /**\n * Resolved specification from `input`.\n */\n spec: Spec;\n\n constructor({\n config,\n dependencies,\n logger,\n project,\n spec,\n }: {\n config: Config;\n dependencies: Record<string, string>;\n logger: Logger;\n project: Project;\n spec: Spec;\n }) {\n this.config = config;\n this.gen = project;\n this.logger = logger;\n this.package = dependencyFactory(dependencies);\n this.spec = spec;\n }\n\n /**\n * Returns a resolved and dereferenced schema from `spec`.\n */\n dereference<T>(schema: { $ref: string }) {\n const resolved = this.resolveRef<T>(schema.$ref);\n const dereferenced = {\n ...schema,\n ...resolved,\n } as T;\n // @ts-expect-error\n delete dereferenced.$ref;\n return dereferenced;\n }\n\n /**\n * Registers a new plugin to the global context.\n *\n * @param name Plugin name.\n * @returns Registered plugin instance.\n */\n private registerPlugin<T extends PluginNames>(\n name: T,\n ): T extends keyof PluginConfigMap ? PluginInstance<PluginConfigMap[T]> : PluginInstance {\n const plugin = (this.config.plugins as Record<string, Plugin.Config<Plugin.Types>>)[name]!;\n const instance = new PluginInstance({\n api: plugin.api,\n config: plugin.config as any,\n context: this as any,\n dependencies: plugin.dependencies ?? [],\n gen: this.gen,\n handler: plugin.handler,\n name: plugin.name,\n });\n (this.plugins as Record<string, any>)[instance.name] = instance;\n return instance as T extends keyof PluginConfigMap\n ? PluginInstance<PluginConfigMap[T]>\n : PluginInstance;\n }\n\n /**\n * Registers all plugins in the order specified by the configuration and returns\n * an array of the registered PluginInstance objects. Each plugin is instantiated\n * and added to the context's plugins map.\n *\n * @returns {ReadonlyArray<PluginInstance>} An array of registered plugin instances in order.\n */\n registerPlugins(): ReadonlyArray<PluginInstance> {\n return this.config.pluginOrder.map((name) => this.registerPlugin(name));\n }\n\n // TODO: parser - works the same as resolveRef, but for IR schemas.\n // for now, they map 1:1, but if they diverge (like with OpenAPI 2.0),\n // we will want to rewrite $refs at parse time, so they continue pointing\n // to the correct IR location\n resolveIrRef<T>($ref: string) {\n return resolveRef<T>({\n $ref,\n spec: this.ir,\n });\n }\n\n /**\n * Returns a resolved reference from `spec`.\n */\n resolveRef<T>($ref: string) {\n return resolveRef<T>({\n $ref,\n spec: this.spec,\n });\n }\n}\n","import type { MaybePromise } from '@hey-api/types';\n\nimport type { CodeSampleObject } from '..//openApi/shared/types';\nimport type { IR } from './types';\n\nexport interface ExampleIntent {\n run(ctx: IntentContext): MaybePromise<void>;\n}\n\nexport class IntentContext<Spec extends Record<string, any> = any> {\n private spec: Spec;\n\n constructor(spec: Spec) {\n this.spec = spec;\n }\n\n private getOperation(path: string, method: string): Record<string, any> | undefined {\n const paths = (this.spec as any).paths;\n if (!paths) return;\n return paths[path]?.[method];\n }\n\n setExample(operation: IR.OperationObject, example: CodeSampleObject): void {\n const source = this.getOperation(operation.path, operation.method);\n if (!source) return;\n source['x-codeSamples'] ||= [];\n source['x-codeSamples'].push(example);\n }\n}\n","import { pathToJsonPointer } from '../utils/ref';\nimport type { IR } from './types';\n\nexport interface SchemaProcessor {\n /** Current inherited context (set by withContext) */\n readonly context: {\n readonly anchor: string | undefined;\n readonly tags: ReadonlyArray<string> | undefined;\n };\n /** Check if pointer was already emitted */\n hasEmitted: (path: ReadonlyArray<string | number>) => boolean;\n /** Mark pointer as emitted. Returns false if already emitted. */\n markEmitted: (path: ReadonlyArray<string | number>) => boolean;\n /** Execute with inherited context for nested extractions */\n withContext: <T>(ctx: { anchor?: string; tags?: ReadonlyArray<string> }, fn: () => T) => T;\n}\n\nexport interface SchemaProcessorContext {\n meta: { resource: string; resourceId: string; role?: string };\n namingAnchor?: string;\n path: ReadonlyArray<string | number>;\n schema: IR.SchemaObject;\n tags?: ReadonlyArray<string>;\n}\n\nexport interface SchemaProcessorResult<\n Context extends SchemaProcessorContext = SchemaProcessorContext,\n> {\n process: (ctx: Context) => void;\n}\n\nexport type SchemaExtractor<Context extends SchemaProcessorContext = SchemaProcessorContext> = (\n ctx: Context,\n) => IR.SchemaObject;\n\nexport function createSchemaProcessor(): SchemaProcessor {\n const emitted = new Set<string>();\n let contextTags: ReadonlyArray<string> | undefined;\n let contextAnchor: string | undefined;\n\n return {\n get context() {\n return {\n anchor: contextAnchor,\n tags: contextTags,\n };\n },\n hasEmitted(path) {\n return emitted.has(pathToJsonPointer(path));\n },\n markEmitted(path) {\n const pointer = pathToJsonPointer(path);\n if (emitted.has(pointer)) return false;\n emitted.add(pointer);\n return true;\n },\n withContext(ctx, fn) {\n const prevTags = contextTags;\n const prevAnchor = contextAnchor;\n contextTags = ctx.tags;\n contextAnchor = ctx.anchor;\n try {\n return fn();\n } finally {\n contextTags = prevTags;\n contextAnchor = prevAnchor;\n }\n },\n };\n}\n","import type { Ref } from '@hey-api/codegen-core';\nimport { fromRef, ref } from '@hey-api/codegen-core';\n\nimport type { SchemaWithType } from '../plugins/shared/types/schema';\nimport { deduplicateSchema } from './schema';\nimport type { IR } from './types';\n\n/**\n * Context passed to all visitor methods.\n */\nexport interface SchemaVisitorContext<TPlugin = unknown> {\n /** Current path in the schema tree. */\n path: Ref<ReadonlyArray<string | number>>;\n /** The plugin instance. */\n plugin: TPlugin;\n}\n\n/**\n * The walk function signature. Fully generic over TResult.\n */\nexport type Walker<TResult, TPlugin = unknown> = (\n schema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n) => TResult;\n\n/**\n * The visitor interface. Plugins define their own TResult type.\n *\n * The walker handles orchestration (dispatch, deduplication, path tracking).\n * Result shape and semantics are entirely plugin-defined.\n */\nexport interface SchemaVisitor<TResult, TPlugin = unknown> {\n /**\n * Apply modifiers to a result.\n */\n applyModifiers(\n result: TResult,\n ctx: SchemaVisitorContext<TPlugin>,\n context?: {\n /** Is this property optional? */\n optional?: boolean;\n },\n ): unknown;\n array(\n schema: SchemaWithType<'array'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n boolean(schema: SchemaWithType<'boolean'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n enum(\n schema: SchemaWithType<'enum'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n integer(schema: SchemaWithType<'integer'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n /**\n * Called before any dispatch logic. Return a result to short-circuit,\n * or undefined to continue normal dispatch.\n */\n intercept?(\n schema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult | undefined;\n /**\n * Handle intersection types. Receives already-walked child results.\n */\n intersection(\n items: Array<TResult>,\n schemas: ReadonlyArray<IR.SchemaObject>,\n parentSchema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n ): TResult;\n never(schema: SchemaWithType<'never'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n null(schema: SchemaWithType<'null'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n number(schema: SchemaWithType<'number'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n object(\n schema: SchemaWithType<'object'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n /**\n * Called after each typed schema visitor returns.\n */\n postProcess?(\n result: TResult,\n schema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n ): TResult;\n /**\n * Handle $ref to another schema.\n */\n reference($ref: string, schema: IR.SchemaObject, ctx: SchemaVisitorContext<TPlugin>): TResult;\n string(schema: SchemaWithType<'string'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n tuple(\n schema: SchemaWithType<'tuple'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n undefined(schema: SchemaWithType<'undefined'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n /**\n * Handle union types. Receives already-walked child results.\n */\n union(\n items: Array<TResult>,\n schemas: ReadonlyArray<IR.SchemaObject>,\n parentSchema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n ): TResult;\n unknown(schema: SchemaWithType<'unknown'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n void(schema: SchemaWithType<'void'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n}\n\n/**\n * Create a schema walker from a visitor.\n *\n * The walker handles:\n * - Dispatch order ($ref โ†’ type โ†’ items โ†’ fallback)\n * - Deduplication of union/intersection schemas\n * - Path tracking for child schemas\n */\nexport function createSchemaWalker<TResult, TPlugin = unknown>(\n visitor: SchemaVisitor<TResult, TPlugin>,\n): Walker<TResult, TPlugin> {\n const walk: Walker<TResult, TPlugin> = (schema, ctx) => {\n // escape hatch\n if (visitor.intercept) {\n const intercepted = visitor.intercept(schema, ctx, walk);\n if (intercepted !== undefined) {\n return intercepted;\n }\n }\n\n if (schema.$ref) {\n return visitor.reference(schema.$ref, schema, ctx);\n }\n\n if (schema.type) {\n let result = visitTyped(schema as SchemaWithType, ctx, visitor, walk);\n if (visitor.postProcess) {\n result = visitor.postProcess(result, schema, ctx);\n }\n return result;\n }\n\n if (schema.items) {\n const deduplicated = deduplicateSchema({ schema });\n\n // deduplication might collapse to a single schema\n if (!deduplicated.items) {\n return walk(deduplicated, ctx);\n }\n\n const itemResults = deduplicated.items.map((item, index) =>\n walk(item, {\n ...ctx,\n path: ref([...fromRef(ctx.path), 'items', index]),\n }),\n );\n\n return deduplicated.logicalOperator === 'and'\n ? visitor.intersection(itemResults, deduplicated.items, schema, ctx)\n : visitor.union(itemResults, deduplicated.items, schema, ctx);\n }\n\n // fallback\n return visitor.unknown({ type: 'unknown' }, ctx);\n };\n\n return walk;\n}\n\n/**\n * Dispatch to the appropriate visitor method based on schema type.\n */\nfunction visitTyped<TResult, TPlugin>(\n schema: SchemaWithType,\n ctx: SchemaVisitorContext<TPlugin>,\n visitor: SchemaVisitor<TResult, TPlugin>,\n walk: Walker<TResult, TPlugin>,\n): TResult {\n switch (schema.type) {\n case 'array':\n return visitor.array(schema as SchemaWithType<'array'>, ctx, walk);\n case 'boolean':\n return visitor.boolean(schema as SchemaWithType<'boolean'>, ctx);\n case 'enum':\n return visitor.enum(schema as SchemaWithType<'enum'>, ctx, walk);\n case 'integer':\n return visitor.integer(schema as SchemaWithType<'integer'>, ctx);\n case 'never':\n return visitor.never(schema as SchemaWithType<'never'>, ctx);\n case 'null':\n return visitor.null(schema as SchemaWithType<'null'>, ctx);\n case 'number':\n return visitor.number(schema as SchemaWithType<'number'>, ctx);\n case 'object':\n return visitor.object(schema as SchemaWithType<'object'>, ctx, walk);\n case 'string':\n return visitor.string(schema as SchemaWithType<'string'>, ctx);\n case 'tuple':\n return visitor.tuple(schema as SchemaWithType<'tuple'>, ctx, walk);\n case 'undefined':\n return visitor.undefined(schema as SchemaWithType<'undefined'>, ctx);\n case 'unknown':\n return visitor.unknown(schema as SchemaWithType<'unknown'>, ctx);\n case 'void':\n return visitor.void(schema as SchemaWithType<'void'>, ctx);\n }\n}\n\n/**\n * Helper to create a child context with an extended path.\n */\nexport function childContext<TPlugin>(\n ctx: SchemaVisitorContext<TPlugin>,\n ...segments: ReadonlyArray<string | number>\n): SchemaVisitorContext<TPlugin> {\n return {\n ...ctx,\n path: ref([...fromRef(ctx.path), ...segments]),\n };\n}\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Parser } from '../../../config/parser/types';\nimport { createOperationKey } from '../../../ir/operation';\nimport type { PathItemObject, PathsObject } from '../../../openApi/3.1.x/types/spec';\nimport type { OpenApi } from '../../../openApi/types';\nimport type { ResourceMetadata } from '../graph/meta';\nimport { httpMethods } from './operation';\n\ntype FilterNamespace = 'body' | 'operation' | 'parameter' | 'response' | 'schema' | 'unknown';\n\nconst namespaceNeedle = '/';\n\nexport const addNamespace = (namespace: FilterNamespace, value: string = ''): string =>\n `${namespace}${namespaceNeedle}${value}`;\n\nexport const removeNamespace = (\n key: string,\n): {\n name: string;\n namespace: FilterNamespace;\n} => {\n const index = key.indexOf(namespaceNeedle);\n const name = key.slice(index + 1);\n return {\n name,\n namespace: key.slice(0, index)! as FilterNamespace,\n };\n};\n\n/**\n * Converts reference strings from OpenAPI $ref keywords into namespaces.\n *\n * @example '#/components/schemas/Foo' -> 'schema'\n */\nexport const stringToNamespace = (value: string): FilterNamespace => {\n switch (value) {\n case 'parameters':\n return 'parameter';\n case 'requestBodies':\n return 'body';\n case 'responses':\n return 'response';\n case 'definitions':\n case 'schemas':\n return 'schema';\n default:\n return 'unknown';\n }\n};\n\ntype FiltersConfigToState<T> = {\n [K in keyof T]-?: NonNullable<T[K]> extends ReadonlyArray<infer U>\n ? Set<U>\n : NonNullable<T[K]> extends object\n ? FiltersConfigToState<NonNullable<T[K]>>\n : T[K];\n};\n\nexport type Filters = FiltersConfigToState<NonNullable<Parser['filters']>>;\n\ninterface SetAndRegExps {\n regexps: Array<RegExp>;\n set: Set<string>;\n}\n\nconst createFiltersSetAndRegExps = (\n type: FilterNamespace,\n filters: ReadonlyArray<string> | undefined,\n): SetAndRegExps => {\n const keys: Array<string> = [];\n const regexps: Array<RegExp> = [];\n if (filters) {\n for (const value of filters) {\n if (value.startsWith('/') && value.endsWith('/')) {\n regexps.push(new RegExp(value.slice(1, value.length - 1)));\n } else {\n keys.push(addNamespace(type, value));\n }\n }\n }\n return {\n regexps,\n set: new Set(keys),\n };\n};\n\ninterface CollectFiltersSetFromRegExps {\n excludeOperations: SetAndRegExps;\n excludeParameters: SetAndRegExps;\n excludeRequestBodies: SetAndRegExps;\n excludeResponses: SetAndRegExps;\n excludeSchemas: SetAndRegExps;\n includeOperations: SetAndRegExps;\n includeParameters: SetAndRegExps;\n includeRequestBodies: SetAndRegExps;\n includeResponses: SetAndRegExps;\n includeSchemas: SetAndRegExps;\n}\n\nconst collectFiltersSetFromRegExpsOpenApiV2 = ({\n excludeOperations,\n excludeSchemas,\n includeOperations,\n includeSchemas,\n spec,\n}: CollectFiltersSetFromRegExps & {\n spec: OpenApi.V2_0_X;\n}) => {\n if ((excludeOperations.regexps.length || includeOperations.regexps.length) && spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = createOperationKey({ method, path });\n if (excludeOperations.regexps.some((regexp) => regexp.test(key))) {\n excludeOperations.set.add(addNamespace('operation', key));\n }\n if (includeOperations.regexps.some((regexp) => regexp.test(key))) {\n includeOperations.set.add(addNamespace('operation', key));\n }\n }\n }\n }\n\n if (spec.definitions) {\n // TODO: add parameters\n\n if (excludeSchemas.regexps.length || includeSchemas.regexps.length) {\n for (const key of Object.keys(spec.definitions)) {\n if (excludeSchemas.regexps.some((regexp) => regexp.test(key))) {\n excludeSchemas.set.add(addNamespace('schema', key));\n }\n if (includeSchemas.regexps.some((regexp) => regexp.test(key))) {\n includeSchemas.set.add(addNamespace('schema', key));\n }\n }\n }\n }\n};\n\nconst collectFiltersSetFromRegExpsOpenApiV3 = ({\n excludeOperations,\n excludeParameters,\n excludeRequestBodies,\n excludeResponses,\n excludeSchemas,\n includeOperations,\n includeParameters,\n includeRequestBodies,\n includeResponses,\n includeSchemas,\n spec,\n}: CollectFiltersSetFromRegExps & {\n spec: OpenApi.V3_0_X | OpenApi.V3_1_X;\n}) => {\n if ((excludeOperations.regexps.length || includeOperations.regexps.length) && spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = createOperationKey({ method, path });\n if (excludeOperations.regexps.some((regexp) => regexp.test(key))) {\n excludeOperations.set.add(addNamespace('operation', key));\n }\n if (includeOperations.regexps.some((regexp) => regexp.test(key))) {\n includeOperations.set.add(addNamespace('operation', key));\n }\n }\n }\n }\n\n if (spec.components) {\n if (\n (excludeParameters.regexps.length || includeParameters.regexps.length) &&\n spec.components.parameters\n ) {\n for (const key of Object.keys(spec.components.parameters)) {\n if (excludeParameters.regexps.some((regexp) => regexp.test(key))) {\n excludeParameters.set.add(addNamespace('parameter', key));\n }\n if (includeParameters.regexps.some((regexp) => regexp.test(key))) {\n includeParameters.set.add(addNamespace('parameter', key));\n }\n }\n }\n\n if (\n (excludeRequestBodies.regexps.length || includeRequestBodies.regexps.length) &&\n spec.components.requestBodies\n ) {\n for (const key of Object.keys(spec.components.requestBodies)) {\n if (excludeRequestBodies.regexps.some((regexp) => regexp.test(key))) {\n excludeRequestBodies.set.add(addNamespace('body', key));\n }\n if (includeRequestBodies.regexps.some((regexp) => regexp.test(key))) {\n includeRequestBodies.set.add(addNamespace('body', key));\n }\n }\n }\n\n if (\n (excludeResponses.regexps.length || includeResponses.regexps.length) &&\n spec.components.responses\n ) {\n for (const key of Object.keys(spec.components.responses)) {\n if (excludeResponses.regexps.some((regexp) => regexp.test(key))) {\n excludeResponses.set.add(addNamespace('response', key));\n }\n if (includeResponses.regexps.some((regexp) => regexp.test(key))) {\n includeResponses.set.add(addNamespace('response', key));\n }\n }\n }\n\n if (\n (excludeSchemas.regexps.length || includeSchemas.regexps.length) &&\n spec.components.schemas\n ) {\n for (const key of Object.keys(spec.components.schemas)) {\n if (excludeSchemas.regexps.some((regexp) => regexp.test(key))) {\n excludeSchemas.set.add(addNamespace('schema', key));\n }\n if (includeSchemas.regexps.some((regexp) => regexp.test(key))) {\n includeSchemas.set.add(addNamespace('schema', key));\n }\n }\n }\n }\n};\n\nconst collectFiltersSetFromRegExps = ({\n spec,\n ...filters\n}: CollectFiltersSetFromRegExps & {\n spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X;\n}): void => {\n if ('swagger' in spec) {\n collectFiltersSetFromRegExpsOpenApiV2({ ...filters, spec });\n } else {\n collectFiltersSetFromRegExpsOpenApiV3({ ...filters, spec });\n }\n};\n\nexport const createFilters = (\n config: Parser['filters'],\n spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X,\n logger: Logger,\n): Filters => {\n const eventCreateFilters = logger.timeEvent('create-filters');\n const excludeOperations = createFiltersSetAndRegExps('operation', config?.operations?.exclude);\n const includeOperations = createFiltersSetAndRegExps('operation', config?.operations?.include);\n const excludeParameters = createFiltersSetAndRegExps('parameter', config?.parameters?.exclude);\n const includeParameters = createFiltersSetAndRegExps('parameter', config?.parameters?.include);\n const excludeRequestBodies = createFiltersSetAndRegExps('body', config?.requestBodies?.exclude);\n const includeRequestBodies = createFiltersSetAndRegExps('body', config?.requestBodies?.include);\n const excludeResponses = createFiltersSetAndRegExps('response', config?.responses?.exclude);\n const includeResponses = createFiltersSetAndRegExps('response', config?.responses?.include);\n const excludeSchemas = createFiltersSetAndRegExps('schema', config?.schemas?.exclude);\n const includeSchemas = createFiltersSetAndRegExps('schema', config?.schemas?.include);\n\n collectFiltersSetFromRegExps({\n excludeOperations,\n excludeParameters,\n excludeRequestBodies,\n excludeResponses,\n excludeSchemas,\n includeOperations,\n includeParameters,\n includeRequestBodies,\n includeResponses,\n includeSchemas,\n spec,\n });\n\n const filters: Filters = {\n deprecated: config?.deprecated ?? true,\n operations: {\n exclude: excludeOperations.set,\n include: includeOperations.set,\n },\n orphans: config?.orphans ?? false,\n parameters: {\n exclude: excludeParameters.set,\n include: includeParameters.set,\n },\n preserveOrder: config?.preserveOrder ?? false,\n requestBodies: {\n exclude: excludeRequestBodies.set,\n include: includeRequestBodies.set,\n },\n responses: {\n exclude: excludeResponses.set,\n include: includeResponses.set,\n },\n schemas: {\n exclude: excludeSchemas.set,\n include: includeSchemas.set,\n },\n tags: {\n exclude: new Set(config?.tags?.exclude),\n include: new Set(config?.tags?.include),\n },\n };\n eventCreateFilters.timeEnd();\n return filters;\n};\n\nexport const hasFilters = (config: Parser['filters']): boolean => {\n if (!config) {\n return false;\n }\n\n // we explicitly want to strip orphans or deprecated\n if (config.orphans === false || config.deprecated === false) {\n return true;\n }\n\n return Boolean(\n config.operations?.exclude?.length ||\n config.operations?.include?.length ||\n config.parameters?.exclude?.length ||\n config.parameters?.include?.length ||\n config.requestBodies?.exclude?.length ||\n config.requestBodies?.include?.length ||\n config.responses?.exclude?.length ||\n config.responses?.include?.length ||\n config.schemas?.exclude?.length ||\n config.schemas?.include?.length ||\n config.tags?.exclude?.length ||\n config.tags?.include?.length,\n );\n};\n\n/**\n * Collect operations that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectOperations = ({\n filters,\n parameters,\n requestBodies,\n resourceMetadata,\n responses,\n schemas,\n}: {\n filters: Filters;\n parameters: Set<string>;\n requestBodies: Set<string>;\n resourceMetadata: ResourceMetadata;\n responses: Set<string>;\n schemas: Set<string>;\n}): {\n operations: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.operations.include.size\n ? filters.operations.include\n : new Set(resourceMetadata.operations.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.operations.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.operations.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n if (\n filters.tags.exclude.size &&\n node.tags.size &&\n [...filters.tags.exclude].some((tag) => node.tags.has(tag))\n ) {\n continue;\n }\n\n if (\n filters.tags.include.size &&\n !new Set([...filters.tags.include].filter((tag) => node.tags.has(tag))).size\n ) {\n continue;\n }\n\n // skip operation if it references any component not included\n if (\n [...node.dependencies].some((dependency) => {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body':\n return !requestBodies.has(dependency);\n case 'parameter':\n return !parameters.has(dependency);\n case 'response':\n return !responses.has(dependency);\n case 'schema':\n return !schemas.has(dependency);\n default:\n return false;\n }\n })\n ) {\n continue;\n }\n\n finalSet.add(key);\n }\n return { operations: finalSet };\n};\n\n/**\n * Collect parameters that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectParameters = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): {\n parameters: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.parameters.include.size\n ? filters.parameters.include\n : new Set(resourceMetadata.parameters.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.parameters.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.parameters.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body': {\n if (filters.requestBodies.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n case 'schema': {\n if (filters.schemas.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!schemas.has(dependency)) {\n schemas.add(dependency);\n }\n break;\n }\n }\n }\n }\n return { parameters: finalSet };\n};\n\n/**\n * Collect request bodies that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectRequestBodies = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): {\n requestBodies: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.requestBodies.include.size\n ? filters.requestBodies.include\n : new Set(resourceMetadata.requestBodies.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.requestBodies.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.requestBodies.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body': {\n if (filters.requestBodies.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n case 'schema': {\n if (filters.schemas.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!schemas.has(dependency)) {\n schemas.add(dependency);\n }\n break;\n }\n }\n }\n }\n return { requestBodies: finalSet };\n};\n\n/**\n * Collect responses that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectResponses = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): {\n responses: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.responses.include.size\n ? filters.responses.include\n : new Set(resourceMetadata.responses.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.responses.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.responses.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body': {\n if (filters.requestBodies.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n case 'schema': {\n if (filters.schemas.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!schemas.has(dependency)) {\n schemas.add(dependency);\n }\n break;\n }\n }\n }\n }\n return { responses: finalSet };\n};\n\n/**\n * Collect schemas that satisfy the include/exclude filters.\n */\nconst collectSchemas = ({\n filters,\n resourceMetadata,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n}): {\n schemas: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.schemas.include.size\n ? filters.schemas.include\n : new Set(resourceMetadata.schemas.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.schemas.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.schemas.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'schema': {\n if (!finalSet.has(dependency) && !filters.schemas.exclude.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n }\n }\n }\n return { schemas: finalSet };\n};\n\n/**\n * Drop parameters that depend on already excluded parameters.\n */\nconst dropExcludedParameters = ({\n filters,\n parameters,\n resourceMetadata,\n}: {\n filters: Filters;\n parameters: Set<string>;\n resourceMetadata: ResourceMetadata;\n}): void => {\n if (!filters.parameters.exclude.size) {\n return;\n }\n\n for (const key of parameters) {\n const node = resourceMetadata.parameters.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.parameters.exclude) {\n if (node.dependencies.has(excludedKey)) {\n parameters.delete(key);\n break;\n }\n }\n }\n};\n\n/**\n * Drop request bodies that depend on already excluded request bodies.\n */\nconst dropExcludedRequestBodies = ({\n filters,\n requestBodies,\n resourceMetadata,\n}: {\n filters: Filters;\n requestBodies: Set<string>;\n resourceMetadata: ResourceMetadata;\n}): void => {\n if (!filters.requestBodies.exclude.size) {\n return;\n }\n\n for (const key of requestBodies) {\n const node = resourceMetadata.requestBodies.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.requestBodies.exclude) {\n if (node.dependencies.has(excludedKey)) {\n requestBodies.delete(key);\n break;\n }\n }\n }\n};\n\n/**\n * Drop responses that depend on already excluded responses.\n */\nconst dropExcludedResponses = ({\n filters,\n resourceMetadata,\n responses,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n responses: Set<string>;\n}): void => {\n if (!filters.responses.exclude.size) {\n return;\n }\n\n for (const key of responses) {\n const node = resourceMetadata.responses.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.responses.exclude) {\n if (node.dependencies.has(excludedKey)) {\n responses.delete(key);\n break;\n }\n }\n }\n};\n\n/**\n * Drop schemas that depend on already excluded schemas.\n */\nconst dropExcludedSchemas = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): void => {\n if (!filters.schemas.exclude.size) {\n return;\n }\n\n for (const key of schemas) {\n const node = resourceMetadata.schemas.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.schemas.exclude) {\n if (node.dependencies.has(excludedKey)) {\n schemas.delete(key);\n break;\n }\n }\n }\n};\n\nconst dropOrphans = ({\n operationDependencies,\n parameters,\n requestBodies,\n responses,\n schemas,\n}: {\n operationDependencies: Set<string>;\n parameters: Set<string>;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n}) => {\n for (const key of schemas) {\n if (!operationDependencies.has(key)) {\n schemas.delete(key);\n }\n }\n for (const key of parameters) {\n if (!operationDependencies.has(key)) {\n parameters.delete(key);\n }\n }\n for (const key of requestBodies) {\n if (!operationDependencies.has(key)) {\n requestBodies.delete(key);\n }\n }\n for (const key of responses) {\n if (!operationDependencies.has(key)) {\n responses.delete(key);\n }\n }\n};\n\nconst collectOperationDependencies = ({\n operations,\n resourceMetadata,\n}: {\n operations: Set<string>;\n resourceMetadata: ResourceMetadata;\n}): {\n operationDependencies: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = new Set(\n [...operations].flatMap((key) => [\n ...(resourceMetadata.operations.get(key)?.dependencies ?? []),\n ]),\n );\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (finalSet.has(key)) {\n continue;\n }\n\n finalSet.add(key);\n\n const { namespace } = removeNamespace(key);\n let dependencies: Set<string> | undefined;\n if (namespace === 'body') {\n dependencies = resourceMetadata.requestBodies.get(key)?.dependencies;\n } else if (namespace === 'operation') {\n dependencies = resourceMetadata.operations.get(key)?.dependencies;\n } else if (namespace === 'parameter') {\n dependencies = resourceMetadata.parameters.get(key)?.dependencies;\n } else if (namespace === 'response') {\n dependencies = resourceMetadata.responses.get(key)?.dependencies;\n } else if (namespace === 'schema') {\n dependencies = resourceMetadata.schemas.get(key)?.dependencies;\n }\n\n if (!dependencies?.size) {\n continue;\n }\n\n for (const dependency of dependencies) {\n if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n }\n }\n return { operationDependencies: finalSet };\n};\n\nexport const createFilteredDependencies = ({\n filters,\n logger,\n resourceMetadata,\n}: {\n filters: Filters;\n logger: Logger;\n resourceMetadata: ResourceMetadata;\n}): {\n operations: Set<string>;\n parameters: Set<string>;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n} => {\n const eventCreateFilteredDependencies = logger.timeEvent('create-filtered-dependencies');\n const { schemas } = collectSchemas({ filters, resourceMetadata });\n const { parameters } = collectParameters({\n filters,\n resourceMetadata,\n schemas,\n });\n const { requestBodies } = collectRequestBodies({\n filters,\n resourceMetadata,\n schemas,\n });\n const { responses } = collectResponses({\n filters,\n resourceMetadata,\n schemas,\n });\n\n dropExcludedSchemas({ filters, resourceMetadata, schemas });\n dropExcludedParameters({ filters, parameters, resourceMetadata });\n dropExcludedRequestBodies({ filters, requestBodies, resourceMetadata });\n dropExcludedResponses({ filters, resourceMetadata, responses });\n\n // collect operations after dropping components\n const { operations } = collectOperations({\n filters,\n parameters,\n requestBodies,\n resourceMetadata,\n responses,\n schemas,\n });\n\n if (!filters.orphans && operations.size) {\n const { operationDependencies } = collectOperationDependencies({\n operations,\n resourceMetadata,\n });\n dropOrphans({\n operationDependencies,\n parameters,\n requestBodies,\n responses,\n schemas,\n });\n }\n\n eventCreateFilteredDependencies.timeEnd();\n return {\n operations,\n parameters,\n requestBodies,\n responses,\n schemas,\n };\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Graph } from '../../../graph';\nimport { createOperationKey } from '../../../ir/operation';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport { addNamespace, stringToNamespace } from '../utils/filter';\nimport { httpMethods } from '../utils/operation';\n\nexport type ResourceMetadata = {\n operations: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n tags: Set<string>;\n }\n >;\n parameters: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n requestBodies: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n responses: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n schemas: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n};\n\n/**\n * Builds a resource metadata map from a Graph, matching the old Graph interface\n * for compatibility with filtering code.\n */\nexport const buildResourceMetadata = (\n graph: Graph,\n logger: Logger,\n): {\n resourceMetadata: ResourceMetadata;\n} => {\n const eventBuildResourceMetadata = logger.timeEvent('build-resource-metadata');\n const resourceMetadata: ResourceMetadata = {\n operations: new Map(),\n parameters: new Map(),\n requestBodies: new Map(),\n responses: new Map(),\n schemas: new Map(),\n };\n\n const getDependencies = (pointer: string): Set<string> => {\n const dependencies = new Set<string>();\n const nodeDependencies = graph.transitiveDependencies.get(pointer);\n if (nodeDependencies?.size) {\n for (const dependency of nodeDependencies) {\n const path = jsonPointerToPath(dependency);\n const type = path[path.length - 2];\n const name = path[path.length - 1];\n if (type && name) {\n const namespace = stringToNamespace(type);\n if (namespace === 'unknown') {\n console.warn(`unsupported type: ${type}`);\n }\n dependencies.add(addNamespace(namespace, name));\n }\n }\n }\n return dependencies;\n };\n\n // Process each node to find top-level resources\n for (const [pointer, nodeInfo] of graph.nodes) {\n // const node = nodeInfo.node as Record<string, unknown>;\n const path = jsonPointerToPath(pointer);\n\n // OpenAPI 3.x\n if (path[0] === 'components') {\n if (path.length === 3) {\n if (path[1] === 'schemas') {\n // Schema: #/components/schemas/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.schemas.set(addNamespace('schema', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n } else if (path[1] === 'parameters') {\n // Parameter: #/components/parameters/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.parameters.set(addNamespace('parameter', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n } else if (path[1] === 'requestBodies') {\n // RequestBody: #/components/requestBodies/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.requestBodies.set(addNamespace('body', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n } else if (path[1] === 'responses') {\n // Response: #/components/responses/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.responses.set(addNamespace('response', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n }\n }\n continue;\n }\n\n if (path[0] === 'paths') {\n if (path.length === 3 && httpMethods.includes(path[2] as (typeof httpMethods)[number])) {\n // Operation: #/paths/{path}/{method}\n const method = path[path.length - 1]!;\n const operationPath = path.slice(1, -1).join('/');\n const operationKey = createOperationKey({\n method,\n path: operationPath,\n });\n resourceMetadata.operations.set(addNamespace('operation', operationKey), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n tags: nodeInfo.tags ?? new Set(),\n });\n }\n continue;\n }\n\n // OpenAPI 2.0\n if (path[0] === 'definitions') {\n if (path.length === 2) {\n // Schema: #/definitions/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.schemas.set(addNamespace('schema', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n }\n continue;\n }\n }\n\n eventBuildResourceMetadata.timeEnd();\n return { resourceMetadata };\n};\n","export const deepClone = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));\n","export const childSchemaRelationships = [\n ['additionalProperties', 'single'],\n ['allOf', 'array'],\n ['anyOf', 'array'],\n ['contains', 'single'],\n ['dependentSchemas', 'objectMap'],\n ['else', 'single'],\n ['if', 'single'],\n ['items', 'singleOrArray'],\n ['oneOf', 'array'],\n ['patternProperties', 'objectMap'],\n ['properties', 'objectMap'],\n ['propertyNames', 'single'],\n ['then', 'single'],\n ['unevaluatedProperties', 'single'],\n] as const;\n","export const getSchemasObject = (spec: unknown): Record<string, unknown> | undefined => {\n if (hasComponentsSchemasObject(spec)) {\n return (spec as any).components.schemas;\n }\n if (hasDefinitionsObject(spec)) {\n return (spec as any).definitions;\n }\n return;\n};\n\n/**\n * Checks if the given spec has a valid OpenAPI 3.x components.schemas object.\n * Returns true if present, false otherwise.\n */\nexport const hasComponentsSchemasObject = (spec: unknown): boolean =>\n typeof spec === 'object' &&\n spec !== null &&\n 'components' in spec &&\n typeof (spec as any).components === 'object' &&\n (spec as any).components !== null &&\n 'schemas' in (spec as any).components &&\n typeof (spec as any).components.schemas === 'object' &&\n (spec as any).components.schemas !== null;\n\n/**\n * Checks if the given spec has a valid OpenAPI 2.0 definitions object.\n * Returns true if present, false otherwise.\n */\nexport const hasDefinitionsObject = (spec: unknown): boolean =>\n typeof spec === 'object' &&\n spec !== null &&\n 'definitions' in spec &&\n typeof (spec as any).definitions === 'object' &&\n (spec as any).definitions !== null;\n","type Obj = Record<string, unknown> | Set<string> | ReadonlyArray<string | undefined>;\n\nconst hasName = (obj: Obj, value: string): boolean => {\n if (obj instanceof Set) {\n return obj.has(value);\n }\n if (obj instanceof Array) {\n return obj.includes(value);\n }\n return value in obj;\n};\n\nexport const getUniqueComponentName = ({\n base,\n components,\n extraComponents,\n}: {\n base: string;\n /**\n * Input components.\n */\n components: Obj;\n /**\n * Temporary input components, waiting to be inserted for example.\n */\n extraComponents?: Obj;\n}): string => {\n let index = 2;\n let name = base;\n while (hasName(components, name) || (extraComponents && hasName(extraComponents, name))) {\n name = `${base}${index}`;\n index += 1;\n }\n return name;\n};\n\nexport const isPathRootSchema = (path: ReadonlyArray<string | number>) =>\n (path.length === 3 && path[0] === 'components' && path[1] === 'schemas') ||\n (path.length === 2 && path[0] === 'definitions');\n\nexport const specToSchemasPointerNamespace = (spec: unknown): string => {\n if (spec && typeof spec === 'object') {\n if ('swagger' in spec) {\n // #/definitions/SchemaName\n return '#/definitions/';\n }\n\n if ('openapi' in spec) {\n // #/components/schemas/SchemaName\n return '#/components/schemas/';\n }\n }\n\n return '';\n};\n","import type { Parser } from '../../../config/parser/types';\nimport { applyNaming } from '../../../utils/naming/naming';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport { deepClone } from '../utils/schema';\nimport { childSchemaRelationships } from '../utils/schemaChildRelationships';\nimport { getSchemasObject } from '../utils/transforms';\nimport { getUniqueComponentName, isPathRootSchema, specToSchemasPointerNamespace } from './utils';\n\ntype EnumsConfig = Parser['transforms']['enums'];\n\n/**\n * Generate a unique, structural signature for an enum schema for deduplication.\n * Only considers 'type' and sorted 'enum' values, ignoring other fields.\n *\n * @param schema - The schema object to analyze\n * @returns A string signature if the schema is an enum, otherwise undefined\n */\nconst getEnumSignature = (schema: unknown): string | undefined => {\n if (\n !schema ||\n typeof schema !== 'object' ||\n !('enum' in schema) ||\n !(schema.enum instanceof Array)\n ) {\n return;\n }\n // Use type + sorted enum values for signature\n const type = ('type' in schema ? schema.type : undefined) || '';\n const values = [...schema.enum].sort();\n return JSON.stringify({ type, values });\n};\n\ntype NodeInfo = {\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n};\n\n/**\n * Recursively walk all schemas in the OpenAPI spec, visiting every object/array\n * that could contain an enum. Calls the visitor with node info for each.\n *\n * @param key - The key of the current node\n * @param node - The current node\n * @param parent - The parent node\n * @param path - The path to the current node\n * @param visitor - Function to call for each visited node\n */\nconst walkSchemas = ({\n key,\n node,\n parent,\n path,\n visitor,\n}: NodeInfo & {\n visitor: (nodeInfo: NodeInfo) => void;\n}) => {\n if (!node || typeof node !== 'object' || node instanceof Array) return;\n\n const value = node as Record<string, unknown>;\n\n if (\n 'type' in value ||\n 'enum' in value ||\n childSchemaRelationships.some(([keyword]) => keyword in value)\n ) {\n visitor({ key, node, parent, path });\n }\n\n for (const [k, v] of Object.entries(value)) {\n if (typeof v === 'object' && v !== null) {\n if (v instanceof Array) {\n v.forEach((item, index) =>\n walkSchemas({\n key: index,\n node: item,\n parent: v,\n path: [...path, k, index],\n visitor,\n }),\n );\n } else {\n walkSchemas({\n key: k,\n node: v,\n parent: node,\n path: [...path, k],\n visitor,\n });\n }\n }\n }\n};\n\n/**\n * Inlines all root/top-level enums by replacing $refs to them with the actual enum schema,\n * and then removes the now-unreferenced root enums from the schemas object.\n *\n * @param spec - The OpenAPI spec object to transform\n */\nconst inlineMode = ({ spec }: { spec: unknown }) => {\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) {\n return;\n }\n\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n\n // Collect all root enums\n const rootEnums: Record<string, unknown> = {};\n for (const [name, schema] of Object.entries(schemasObj)) {\n const signature = getEnumSignature(schema);\n if (signature) {\n rootEnums[`${schemasPointerNamespace}${name}`] = schema;\n }\n }\n\n // Walk the spec and replace $refs to root enums with inline enum schemas\n const replaceEnumRefs = (node: unknown) => {\n if (node instanceof Array) {\n node.forEach(replaceEnumRefs);\n } else if (node && typeof node === 'object') {\n for (const [k, v] of Object.entries(node)) {\n if (k === '$ref' && typeof v === 'string' && v in rootEnums) {\n // Replace $ref with a deep clone of the enum schema\n Object.assign(node, deepClone(rootEnums[v]));\n delete (node as Record<string, unknown>)['$ref'];\n } else {\n replaceEnumRefs(v);\n }\n }\n }\n };\n replaceEnumRefs(spec);\n\n // Remove unreferenced root enums\n for (const pointer of Object.keys(rootEnums)) {\n const path = jsonPointerToPath(pointer);\n const name = path[path.length - 1]!;\n if (name) {\n delete schemasObj[name];\n }\n }\n};\n\n/**\n * Promotes all inline enums to reusable root components (if mode is 'root'),\n * deduplicates by signature, and replaces inline enums with $refs.\n *\n * Naming, casing, and deduplication are controlled by the enums transform config.\n * Existing root enums are reused if structurally identical.\n *\n * @param spec - The OpenAPI spec object to transform\n * @param config - The enums transform config\n */\nconst rootMode = ({ config, spec }: { config: EnumsConfig; spec: unknown }) => {\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) {\n return;\n }\n\n // Build a map of existing root enum signatures to their names for deduplication\n const rootEnumSignatures: Record<string, string> = {};\n for (const [name, schema] of Object.entries(schemasObj)) {\n const signature = getEnumSignature(schema);\n if (signature) {\n rootEnumSignatures[signature] = name;\n }\n }\n\n // Collect all inline enums (not at root schemas)\n const inlineEnums: Array<{\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n signature: string;\n }> = [];\n\n walkSchemas({\n key: null,\n node: spec,\n parent: null,\n path: [],\n visitor: (nodeInfo) => {\n if (!isPathRootSchema(nodeInfo.path)) {\n const signature = getEnumSignature(nodeInfo.node);\n if (signature) {\n inlineEnums.push({ ...nodeInfo, signature });\n }\n }\n },\n });\n\n // Deduplicate and assign unique names for promoted enums\n const signatureToName: Record<string, string | undefined> = {};\n const signatureToSchema: Record<string, unknown> = {};\n\n for (const { key, node, signature } of inlineEnums) {\n if (signature in signatureToName) {\n // Already handled\n continue;\n }\n\n // Use existing root enum if available\n if (signature in rootEnumSignatures) {\n signatureToName[signature] = rootEnumSignatures[signature];\n continue;\n }\n\n // Generate a unique name for the new root enum using config\n const base = applyNaming(\n typeof node === 'object' && node && 'title' in node && typeof node.title === 'string'\n ? node.title\n : String(key),\n config,\n );\n const name = getUniqueComponentName({\n base,\n components: schemasObj,\n extraComponents: Object.values(signatureToName),\n });\n signatureToName[signature] = name;\n signatureToSchema[signature] = node;\n }\n\n // Add new root enums to the schemas object\n for (const [signature, name] of Object.entries(signatureToName)) {\n // Only add if not already present\n const schema = signatureToSchema[signature];\n if (name && !(name in schemasObj) && schema && typeof schema === 'object') {\n schemasObj[name] = schema;\n }\n }\n\n // Replace inline enums with $ref to the new root enum\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n for (const { key, parent, signature } of inlineEnums) {\n const name = signatureToName[signature];\n if (name && key != null && parent && typeof parent === 'object') {\n (parent as Record<string, unknown>)[key] = {\n $ref: `${schemasPointerNamespace}${name}`,\n };\n }\n }\n};\n\n/**\n * Applies the enums transform according to the configured mode ('inline' or 'root').\n *\n * - In 'inline' mode, all root enums are inlined and removed.\n * - In 'root' mode, all inline enums are promoted to root components and deduplicated.\n *\n * @param config - The enums transform config\n * @param spec - The OpenAPI spec object to transform\n */\nexport const enumsTransform = ({ config, spec }: { config: EnumsConfig; spec: unknown }) => {\n if (config.mode === 'inline') {\n inlineMode({ spec });\n return;\n }\n\n if (config.mode === 'root') {\n rootMode({ config, spec });\n return;\n }\n};\n","import { childSchemaRelationships } from '../utils/schemaChildRelationships';\n\ntype NodeInfo = {\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n};\n\n/**\n * Recursively walk all schemas in the OpenAPI spec, visiting every object.\n * Calls the visitor with node info for each.\n *\n * @param key - The key of the current node\n * @param node - The current node\n * @param parent - The parent node\n * @param path - The path to the current node\n * @param visitor - Function to call for each visited node\n */\nconst walkSchemas = ({\n key,\n node,\n parent,\n path,\n visitor,\n}: NodeInfo & {\n visitor: (nodeInfo: NodeInfo) => void;\n}) => {\n if (!node || typeof node !== 'object' || node instanceof Array) return;\n\n const value = node as Record<string, unknown>;\n\n if ('type' in value || childSchemaRelationships.some(([keyword]) => keyword in value)) {\n visitor({ key, node, parent, path });\n }\n\n for (const [k, v] of Object.entries(value)) {\n if (typeof v === 'object' && v !== null) {\n if (v instanceof Array) {\n v.forEach((item, index) =>\n walkSchemas({\n key: index,\n node: item,\n parent: v,\n path: [...path, k, index],\n visitor,\n }),\n );\n } else {\n walkSchemas({\n key: k,\n node: v,\n parent: node,\n path: [...path, k],\n visitor,\n });\n }\n }\n }\n};\n\n/**\n * Applies the properties required by default transform\n *\n * @param spec - The OpenAPI spec object to transform\n */\nexport const propertiesRequiredByDefaultTransform = ({ spec }: { spec: unknown }) => {\n walkSchemas({\n key: null,\n node: spec,\n parent: null,\n path: [],\n visitor: (nodeInfo) => {\n if (\n nodeInfo.node &&\n typeof nodeInfo.node === 'object' &&\n 'type' in nodeInfo.node &&\n nodeInfo.node.type === 'object' &&\n 'properties' in nodeInfo.node &&\n nodeInfo.node.properties &&\n typeof nodeInfo.node.properties === 'object' &&\n !('required' in nodeInfo.node)\n ) {\n const propKeys = Object.keys(nodeInfo.node.properties as Record<string, unknown>);\n if (propKeys.length > 0) {\n (nodeInfo.node as Record<string, unknown>).required = propKeys;\n }\n }\n },\n });\n};\n","/**\n * Deep equality for JSON-compatible values (objects, arrays, primitives).\n * Used to determine whether read/write pruned variants actually differ.\n */\nconst deepEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n const typeA = typeof a;\n const typeB = typeof b;\n if (typeA !== typeB) return false;\n if (typeA !== 'object') return false;\n\n // Arrays\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n\n // Plain objects\n const objA = a as Record<string, unknown>;\n const objB = b as Record<string, unknown>;\n const keysA = Object.keys(objA).sort();\n const keysB = Object.keys(objB).sort();\n if (keysA.length !== keysB.length) return false;\n for (let i = 0; i < keysA.length; i++) {\n if (keysA[i] !== keysB[i]) return false;\n }\n for (const key of keysA) {\n if (!deepEqual(objA[key], objB[key])) return false;\n }\n return true;\n};\n\nexport default deepEqual;\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Graph, NodeInfo } from '../../../graph';\nimport { normalizeJsonPointer, pathToJsonPointer } from '../../../utils/ref';\nimport { childSchemaRelationships } from './schemaChildRelationships';\n\n/**\n * Represents the possible access scopes for OpenAPI nodes.\n * - 'normal': Default scope for regular nodes.\n * - 'read': Node is read-only (e.g., readOnly: true).\n * - 'write': Node is write-only (e.g., writeOnly: true).\n */\nexport type Scope = 'normal' | 'read' | 'write';\n\n/**\n * Ensures every relevant child node (e.g., properties, items) in the graph has a `scopes` property.\n * If a node does not have its own scopes, it inherits from its parent if available.\n *\n * @param nodes - Map of JSON Pointer to NodeInfo.\n */\nexport const annotateChildScopes = (nodes: Graph['nodes']): void => {\n for (const [, nodeInfo] of nodes) {\n if (nodeInfo.scopes) continue;\n\n if (nodeInfo.parentPointer) {\n const parentInfo = nodes.get(nodeInfo.parentPointer);\n if (parentInfo?.scopes) {\n nodeInfo.scopes = new Set(parentInfo.scopes);\n }\n }\n }\n};\n\ninterface Cache {\n parentToChildren: Map<string, Array<string>>;\n subtreeDependencies: Map<string, Set<string>>;\n transitiveDependencies: Map<string, Set<string>>;\n}\n\ntype PointerDependenciesResult = {\n subtreeDependencies: Set<string>;\n transitiveDependencies: Set<string>;\n};\n\n/**\n * Recursively collects all $ref dependencies in the subtree rooted at `pointer`.\n */\nconst collectPointerDependencies = ({\n cache,\n graph,\n pointer,\n visited,\n}: {\n cache: Cache;\n graph: Graph;\n pointer: string;\n visited: Set<string>;\n}): PointerDependenciesResult => {\n const cached = cache.transitiveDependencies.get(pointer);\n if (cached) {\n return {\n subtreeDependencies: cache.subtreeDependencies.get(pointer)!,\n transitiveDependencies: cached,\n };\n }\n\n if (visited.has(pointer)) {\n return {\n subtreeDependencies: new Set(),\n transitiveDependencies: new Set(),\n };\n }\n visited.add(pointer);\n\n const nodeInfo = graph.nodes.get(pointer);\n if (!nodeInfo) {\n return {\n subtreeDependencies: new Set(),\n transitiveDependencies: new Set(),\n };\n }\n\n const transitiveDependencies = new Set<string>();\n const subtreeDependencies = new Set<string>();\n\n // Add direct $ref dependencies for this node\n // (from the dependencies map, or by checking nodeInfo.node directly)\n // We'll use the dependencies map for consistency:\n const nodeDependencies = graph.nodeDependencies.get(pointer);\n if (nodeDependencies) {\n for (const depPointer of nodeDependencies) {\n transitiveDependencies.add(depPointer);\n subtreeDependencies.add(depPointer);\n // Recursively collect dependencies of the referenced node\n const depResult = collectPointerDependencies({\n cache,\n graph,\n pointer: depPointer,\n visited,\n });\n for (const dependency of depResult.transitiveDependencies) {\n transitiveDependencies.add(dependency);\n }\n }\n }\n\n const children = cache.parentToChildren.get(pointer) ?? [];\n for (const childPointer of children) {\n let childResult: Partial<PointerDependenciesResult> = {\n subtreeDependencies: cache.subtreeDependencies.get(childPointer),\n transitiveDependencies: cache.transitiveDependencies.get(childPointer),\n };\n if (!childResult.subtreeDependencies || !childResult.transitiveDependencies) {\n childResult = collectPointerDependencies({\n cache,\n graph,\n pointer: childPointer,\n visited,\n });\n cache.transitiveDependencies.set(childPointer, childResult.transitiveDependencies!);\n cache.subtreeDependencies.set(childPointer, childResult.subtreeDependencies!);\n }\n for (const dependency of childResult.transitiveDependencies!) {\n transitiveDependencies.add(dependency);\n }\n for (const dependency of childResult.subtreeDependencies!) {\n subtreeDependencies.add(dependency);\n }\n }\n\n cache.transitiveDependencies.set(pointer, transitiveDependencies);\n cache.subtreeDependencies.set(pointer, subtreeDependencies);\n return {\n subtreeDependencies,\n transitiveDependencies,\n };\n};\n\n/**\n * Propagates scopes through the graph using a worklist algorithm.\n * Each node's scopes will be updated to include any scopes inherited via $ref dependencies, combinator/child relationships, and parent relationships.\n * Handles cycles and deep chains efficiently.\n *\n * Whenever a node's scopes change, all dependents are notified:\n * - Its parent (if any)\n * - All nodes that reference it via $ref (reverse dependencies)\n * - Combinator parents (allOf/anyOf/oneOf) if applicable\n *\n * @param graph - The Graph structure containing nodes, dependencies, and reverseNodeDependencies.\n */\nexport const propagateScopes = (graph: Graph): void => {\n const worklist: Set<string> = new Set(\n Array.from(graph.nodes.entries())\n .filter(([, nodeInfo]) => nodeInfo.scopes && nodeInfo.scopes.size > 0)\n .map(([pointer]) => pointer),\n );\n\n /**\n * Notifies all dependents of a node that its scopes may have changed.\n * Dependents include:\n * - The parent node (if any)\n * - All nodes that reference this node via $ref (reverse dependencies)\n * - Combinator parents (allOf/anyOf/oneOf) if this node is a combinator child\n *\n * @param pointer - The JSON pointer of the node whose dependents to notify\n * @param nodeInfo - The NodeInfo of the node\n * @param childPointer - (Optional) The pointer of the child, used to detect combinator parents\n */\n const notifyAllDependents = (pointer: string, nodeInfo: NodeInfo, childPointer?: string) => {\n if (nodeInfo.parentPointer) {\n worklist.add(nodeInfo.parentPointer);\n }\n const reverseNodeDependencies = graph.reverseNodeDependencies.get(pointer);\n if (reverseNodeDependencies) {\n for (const dependentPointer of reverseNodeDependencies) {\n worklist.add(dependentPointer);\n }\n }\n if (childPointer) {\n // If this is a combinator child, notify the combinator parent\n const combinatorChildMatch = childPointer.match(/(.*)\\/(allOf|anyOf|oneOf)\\/\\d+$/);\n if (combinatorChildMatch) {\n const combinatorParentPointer = combinatorChildMatch[1];\n if (combinatorParentPointer) {\n worklist.add(combinatorParentPointer);\n }\n }\n }\n };\n\n /**\n * Propagates scopes from a child node to its parent node.\n * If the parent's scopes change, notifies all dependents.\n *\n * @param pointer - The parent node's pointer\n * @param nodeInfo - The parent node's NodeInfo\n * @param childPointer - The child node's pointer\n */\n const propagateChildScopes = (\n pointer: string,\n nodeInfo: NodeInfo,\n childPointer: string,\n ): void => {\n if (!nodeInfo?.scopes) return;\n const childInfo = graph.nodes.get(childPointer);\n if (!childInfo?.scopes) return;\n const changed = propagateScopesToNode(childInfo, nodeInfo);\n if (changed) {\n notifyAllDependents(pointer, nodeInfo, childPointer);\n }\n };\n\n while (worklist.size > 0) {\n const pointer = worklist.values().next().value!;\n worklist.delete(pointer);\n\n const nodeInfo = graph.nodes.get(pointer);\n if (!nodeInfo) continue;\n\n if (!nodeInfo.scopes) {\n nodeInfo.scopes = new Set();\n }\n\n const node = nodeInfo.node as Record<string, unknown>;\n\n // Propagate scopes from all child schema relationships (combinators, properties, etc.)\n for (const [keyword, type] of childSchemaRelationships) {\n if (!node || typeof node !== 'object' || !(keyword in node)) continue;\n const value = node[keyword];\n if (type === 'array' && value instanceof Array) {\n for (let index = 0; index < value.length; index++) {\n const childPointer = `${pointer}/${keyword}/${index}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n } else if (\n type === 'objectMap' &&\n typeof value === 'object' &&\n value !== null &&\n !(value instanceof Array)\n ) {\n for (const key of Object.keys(value)) {\n const childPointer = `${pointer}/${keyword}/${key}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n } else if (type === 'single' && typeof value === 'object' && value !== null) {\n const childPointer = `${pointer}/${keyword}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n } else if (type === 'singleOrArray') {\n if (value instanceof Array) {\n for (let index = 0; index < value.length; index++) {\n const childPointer = `${pointer}/${keyword}/${index}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n } else if (typeof value === 'object' && value !== null) {\n const childPointer = `${pointer}/${keyword}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n }\n }\n\n // Propagate scopes from $ref dependencies\n const nodeDependencies = graph.nodeDependencies.get(pointer);\n if (nodeDependencies) {\n for (const depPointer of nodeDependencies) {\n const depNode = graph.nodes.get(depPointer);\n if (depNode?.scopes) {\n const changed = propagateScopesToNode(depNode, nodeInfo);\n if (changed) {\n notifyAllDependents(pointer, nodeInfo);\n }\n }\n }\n }\n\n // Propagate scopes up the parent chain\n if (nodeInfo.parentPointer) {\n const parentInfo = graph.nodes.get(nodeInfo.parentPointer);\n if (parentInfo) {\n const changed = propagateScopesToNode(nodeInfo, parentInfo);\n if (changed) {\n notifyAllDependents(nodeInfo.parentPointer, parentInfo);\n }\n }\n }\n }\n};\n\n/**\n * Propagates scopes from one node to another.\n * Adds any scopes from fromNodeInfo to toNodeInfo that are not already present.\n * Returns true if any scopes were added, false otherwise.\n *\n * @param fromNodeInfo - The node to propagate scopes from\n * @param toNodeInfo - The node to propagate scopes to\n * @returns boolean - Whether any scopes were added\n */\nconst propagateScopesToNode = (fromNodeInfo: NodeInfo, toNodeInfo: NodeInfo): boolean => {\n if (!fromNodeInfo.scopes) {\n return false;\n }\n\n if (!toNodeInfo.scopes) {\n toNodeInfo.scopes = new Set();\n }\n\n let changed = false;\n\n for (const scope of fromNodeInfo.scopes) {\n if (!toNodeInfo.scopes.has(scope)) {\n toNodeInfo.scopes.add(scope);\n changed = true;\n }\n }\n\n return changed;\n};\n\n/**\n * Seeds each node in the graph with its local access scope(s) based on its own properties.\n * - 'read' if readOnly: true\n * - 'write' if writeOnly: true\n * - 'normal' if node is an object property\n *\n * Only non-array objects are considered for scope seeding.\n *\n * @param nodes - Map of JSON Pointer to NodeInfo.\n */\nexport const seedLocalScopes = (nodes: Graph['nodes']): void => {\n for (const [pointer, nodeInfo] of nodes) {\n const { node } = nodeInfo;\n\n if (typeof node !== 'object' || node === null || node instanceof Array) {\n continue;\n }\n\n if ('readOnly' in node && node.readOnly === true) {\n nodeInfo.scopes = new Set(['read']);\n } else if ('writeOnly' in node && node.writeOnly === true) {\n nodeInfo.scopes = new Set(['write']);\n } else if (pointer.match(/\\/properties\\/[^/]+$/)) {\n nodeInfo.scopes = new Set(['normal']);\n }\n }\n};\n\n/**\n * Builds a graph of all nodes in an OpenAPI spec, indexed by normalized JSON Pointer,\n * and tracks all $ref dependencies and reverse dependencies between nodes.\n *\n * - All keys in the returned maps are normalized JSON Pointers (RFC 6901, always starting with '#').\n * - The `nodes` map allows fast lookup of any node and its parent/key context.\n * - The `dependencies` map records, for each node, the set of normalized pointers it references via $ref.\n * - The `reverseNodeDependencies` map records, for each node, the set of nodes that reference it via $ref.\n * - After construction, all nodes will have their local and propagated scopes annotated.\n *\n * @param root The root object (e.g., the OpenAPI spec)\n * @returns An object with:\n * - nodes: Map from normalized JSON Pointer string to NodeInfo\n * - dependencies: Map from normalized JSON Pointer string to Set of referenced normalized JSON Pointers\n * - reverseNodeDependencies: Map from normalized JSON Pointer string to Set of referencing normalized JSON Pointers\n */\nexport function buildGraph(\n root: unknown,\n logger: Logger,\n): {\n graph: Graph;\n} {\n const eventBuildGraph = logger.timeEvent('build-graph');\n const graph: Graph = {\n nodeDependencies: new Map(),\n nodes: new Map(),\n reverseNodeDependencies: new Map(),\n subtreeDependencies: new Map(),\n transitiveDependencies: new Map(),\n };\n\n const walk = ({\n key,\n node,\n parentPointer,\n path,\n }: NodeInfo & {\n path: ReadonlyArray<string | number>;\n }) => {\n if (typeof node !== 'object' || node === null) {\n return;\n }\n\n const pointer = pathToJsonPointer(path);\n\n let deprecated: boolean | undefined;\n let tags: Set<string> | undefined;\n\n if (typeof node === 'object' && node !== null) {\n // Check for deprecated property\n if ('deprecated' in node && typeof node.deprecated === 'boolean') {\n deprecated = Boolean(node.deprecated);\n }\n // If this node has a $ref, record the dependency\n if ('$ref' in node && typeof node.$ref === 'string') {\n const refPointer = normalizeJsonPointer(node.$ref);\n if (!graph.nodeDependencies.has(pointer)) {\n graph.nodeDependencies.set(pointer, new Set());\n }\n graph.nodeDependencies.get(pointer)!.add(refPointer);\n }\n // Check for tags property (should be an array of strings)\n if ('tags' in node && node.tags instanceof Array) {\n tags = new Set(node.tags.filter((tag) => typeof tag === 'string'));\n }\n }\n\n graph.nodes.set(pointer, { deprecated, key, node, parentPointer, tags });\n\n if (node instanceof Array) {\n node.forEach((item, index) =>\n walk({\n key: index,\n node: item,\n parentPointer: pointer,\n path: [...path, index],\n }),\n );\n } else {\n for (const [childKey, value] of Object.entries(node)) {\n walk({\n key: childKey,\n node: value,\n parentPointer: pointer,\n path: [...path, childKey],\n });\n }\n }\n };\n\n walk({\n key: null,\n node: root,\n parentPointer: null,\n path: [],\n });\n\n const cache: Cache = {\n parentToChildren: new Map(),\n subtreeDependencies: new Map(),\n transitiveDependencies: new Map(),\n };\n\n for (const [pointer, nodeInfo] of graph.nodes) {\n const parent = nodeInfo.parentPointer;\n if (!parent) continue;\n if (!cache.parentToChildren.has(parent)) {\n cache.parentToChildren.set(parent, []);\n }\n cache.parentToChildren.get(parent)!.push(pointer);\n }\n\n for (const [pointerFrom, pointers] of graph.nodeDependencies) {\n for (const pointerTo of pointers) {\n if (!graph.reverseNodeDependencies.has(pointerTo)) {\n graph.reverseNodeDependencies.set(pointerTo, new Set());\n }\n graph.reverseNodeDependencies.get(pointerTo)!.add(pointerFrom);\n }\n }\n\n seedLocalScopes(graph.nodes);\n propagateScopes(graph);\n annotateChildScopes(graph.nodes);\n\n for (const pointer of graph.nodes.keys()) {\n const result = collectPointerDependencies({\n cache,\n graph,\n pointer,\n visited: new Set(),\n });\n graph.transitiveDependencies.set(pointer, result.transitiveDependencies);\n graph.subtreeDependencies.set(pointer, result.subtreeDependencies);\n }\n\n eventBuildGraph.timeEnd();\n\n // functions creating data for debug scripts located in `dev/`\n // const { maxChildren, maxDepth, totalNodes } = debugTools.graph.analyzeStructure(graph);\n // const nodesForViz = debugTools.graph.exportForVisualization(graph);\n // fs.writeFileSync('dev/graph.json', JSON.stringify(nodesForViz, null, 2));\n\n return { graph };\n}\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Parser } from '../../../config/parser/types';\nimport type { Graph } from '../../../graph';\nimport { applyNaming } from '../../../utils/naming/naming';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport deepEqual from '../utils/deepEqual';\nimport { buildGraph, type Scope } from '../utils/graph';\nimport { deepClone } from '../utils/schema';\nimport { childSchemaRelationships } from '../utils/schemaChildRelationships';\nimport {\n getSchemasObject,\n hasComponentsSchemasObject,\n hasDefinitionsObject,\n} from '../utils/transforms';\nimport { getUniqueComponentName, isPathRootSchema, specToSchemasPointerNamespace } from './utils';\n\ntype OriginalSchemas = Record<string, unknown>;\n\ntype SplitMapping = Record<\n string,\n {\n read?: string;\n write?: string;\n }\n>;\n\ntype SplitSchemas = {\n /** Key is the original schema pointer. */\n mapping: SplitMapping;\n /** splitPointer -> originalPointer */\n reverseMapping: Record<string, string>;\n /** name -> schema object */\n schemas: Record<string, unknown>;\n};\n\ntype ReadWriteConfig = Parser['transforms']['readWrite'];\n\nconst schemaKeys = new Set([\n 'additionalProperties',\n 'allOf',\n 'anyOf',\n 'items',\n 'not',\n 'oneOf',\n 'patternProperties',\n 'properties',\n 'schema',\n 'unevaluatedProperties',\n]);\n\nconst getComponentContext = (path: ReadonlyArray<string | number>): Scope | undefined => {\n // OpenAPI 3.x: #/components/{type}/{name}\n if (path.length === 3 && path[0] === 'components') {\n const type = path[1];\n if (type === 'parameters') return 'write';\n if (type === 'requestBodies') return 'write';\n if (type === 'responses') return 'read';\n if (type === 'headers') return 'read';\n }\n // OpenAPI 2.x: #/parameters/{name}, #/responses/{name}\n if (path.length === 2) {\n const type = path[0];\n if (type === 'parameters') return 'write';\n if (type === 'responses') return 'read';\n }\n return;\n};\n\n/**\n * Capture the original schema objects by pointer before splitting.\n * This is used to safely remove only the true originals after splitting,\n * even if names are swapped or overwritten by split variants.\n */\nconst captureOriginalSchemas = (spec: unknown, logger: Logger): OriginalSchemas => {\n const event = logger.timeEvent('capture-original-schemas');\n const originals: OriginalSchemas = {};\n if (hasComponentsSchemasObject(spec)) {\n for (const [name, obj] of Object.entries((spec as any).components.schemas)) {\n originals[`#/components/schemas/${name}`] = obj;\n }\n } else if (hasDefinitionsObject(spec)) {\n for (const [name, obj] of Object.entries((spec as any).definitions)) {\n originals[`#/definitions/${name}`] = obj;\n }\n }\n event.timeEnd();\n return originals;\n};\n\n/**\n * Inserts split schemas into the spec at the correct location (OpenAPI 3.x or 2.0).\n * This function is robust to spec version and will assign all split schemas\n * to either components.schemas (OAS3) or definitions (OAS2).\n *\n * @param spec - The OpenAPI spec object\n * @param split - The split schemas (from splitSchemas)\n */\nconst insertSplitSchemasIntoSpec = ({\n logger,\n spec,\n split,\n}: {\n logger: Logger;\n spec: unknown;\n split: Pick<SplitSchemas, 'schemas'>;\n}) => {\n const event = logger.timeEvent('insert-split-schemas-into-spec');\n if (hasComponentsSchemasObject(spec)) {\n Object.assign((spec as any).components.schemas, split.schemas);\n } else if (hasDefinitionsObject(spec)) {\n Object.assign((spec as any).definitions, split.schemas);\n }\n event.timeEnd();\n};\n\n/**\n * Prunes a schema by removing all child schemas (in any structural keyword)\n * that are marked with the given scope (readOnly/writeOnly), or that are $ref to a schema\n * that is exclusively the excluded scope (according to the graph).\n *\n * Uses childSchemaRelationships for parity with graph traversal.\n * Returns true if the schema itself should be removed from its parent.\n *\n * @param graph - The Graph containing all nodes and their scopes\n * @param schema - The schema object to prune\n * @param scope - The scope to exclude ('readOnly' or 'writeOnly')\n * @returns boolean - Whether the schema should be removed from its parent\n */\nconst pruneSchemaByScope = (\n graph: Graph,\n schema: unknown,\n scope: 'readOnly' | 'writeOnly',\n): boolean => {\n if (schema && typeof schema === 'object') {\n // Handle $ref schemas\n if ('$ref' in schema && typeof schema.$ref === 'string') {\n const nodeInfo = graph.nodes.get(schema.$ref);\n if (nodeInfo?.scopes) {\n // Only remove $ref if the referenced schema is *exclusively* the excluded scope.\n // This ensures 'normal' or multi-scope schemas are always kept.\n if (\n (scope === 'writeOnly' && nodeInfo.scopes.size === 1 && nodeInfo.scopes.has('write')) ||\n (scope === 'readOnly' && nodeInfo.scopes.size === 1 && nodeInfo.scopes.has('read'))\n ) {\n delete (schema as Record<string, unknown>)['$ref'];\n // If the schema is now empty, remove it\n if (!childSchemaRelationships.some(([keyword]) => keyword in schema)) {\n return true;\n }\n }\n }\n }\n // Recursively prune all child schemas according to childSchemaRelationships\n for (const [keyword, type] of childSchemaRelationships) {\n if (!(keyword in schema)) {\n continue;\n }\n const value = (schema as Record<string, unknown>)[keyword];\n if (type === 'array' && value instanceof Array) {\n for (let index = value.length - 1; index >= 0; index--) {\n const item = value[index];\n if (\n item &&\n typeof item === 'object' &&\n (item as Record<string, unknown>)[scope] === true\n ) {\n value.splice(index, 1);\n } else {\n const shouldRemove = pruneSchemaByScope(graph, item, scope);\n if (shouldRemove) value.splice(index, 1);\n }\n }\n if (!value.length) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n } else if (\n type === 'objectMap' &&\n typeof value === 'object' &&\n value !== null &&\n !(value instanceof Array)\n ) {\n const objMap = value as Record<string, unknown>;\n // Track removed properties for object schemas to update required array\n const removedProperties = new Set<string>();\n\n for (const key of Object.keys(objMap)) {\n const prop = objMap[key];\n if (\n prop &&\n typeof prop === 'object' &&\n (prop as Record<string, unknown>)[scope] === true\n ) {\n delete objMap[key];\n // Track removed properties for object schemas\n if (keyword === 'properties') {\n removedProperties.add(key);\n }\n } else {\n const shouldRemove = pruneSchemaByScope(graph, prop, scope);\n if (shouldRemove) {\n delete objMap[key];\n // Track removed properties for object schemas\n if (keyword === 'properties') {\n removedProperties.add(key);\n }\n }\n }\n }\n\n // Update required array if properties were removed\n if (\n removedProperties.size > 0 &&\n keyword === 'properties' &&\n 'required' in schema &&\n Array.isArray((schema as Record<string, unknown>).required)\n ) {\n const required = (schema as Record<string, unknown>).required as string[];\n const filteredRequired = required.filter((prop) => !removedProperties.has(prop));\n\n if (!filteredRequired.length) {\n delete (schema as Record<string, unknown>).required;\n } else {\n (schema as Record<string, unknown>).required = filteredRequired;\n }\n }\n\n if (!Object.keys(objMap).length) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n } else if (type === 'single' && typeof value === 'object' && value !== null) {\n if ((value as Record<string, unknown>)[scope] === true) {\n delete (schema as Record<string, unknown>)[keyword];\n } else {\n const shouldRemove = pruneSchemaByScope(graph, value, scope);\n if (shouldRemove) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n }\n } else if (type === 'singleOrArray') {\n if (value instanceof Array) {\n for (let index = value.length - 1; index >= 0; index--) {\n const item = value[index];\n if (\n item &&\n typeof item === 'object' &&\n (item as Record<string, unknown>)[scope] === true\n ) {\n value.splice(index, 1);\n } else {\n const shouldRemove = pruneSchemaByScope(graph, item, scope);\n if (shouldRemove) value.splice(index, 1);\n }\n }\n if (!value.length) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n } else if (typeof value === 'object' && value !== null) {\n if ((value as Record<string, unknown>)[scope] === true) {\n delete (schema as Record<string, unknown>)[keyword];\n } else {\n const shouldRemove = pruneSchemaByScope(graph, value, scope);\n if (shouldRemove) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n }\n }\n }\n }\n // After all removals, if this is type: object and has no structural fields, remove it\n if (\n (schema as Record<string, unknown>).type === 'object' &&\n !childSchemaRelationships.some(([keyword]) => keyword in schema)\n ) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Remove only the true original schemas that were split, by object identity.\n * This is robust to swaps, overwrites, and name collisions.\n *\n * @param originalSchemas - Map of original pointers to their schema objects (captured before splitting)\n * @param spec - The OpenAPI spec object\n * @param split - The split mapping (from splitSchemas)\n */\nconst removeOriginalSplitSchemas = ({\n logger,\n originalSchemas,\n spec,\n split,\n}: {\n logger: Logger;\n originalSchemas: OriginalSchemas;\n spec: unknown;\n split: Pick<SplitSchemas, 'mapping'>;\n}) => {\n const event = logger.timeEvent('remove-original-split-schemas');\n const schemasObj = getSchemasObject(spec);\n\n for (const originalPointer of Object.keys(split.mapping)) {\n const path = jsonPointerToPath(originalPointer);\n const name = path[path.length - 1]!;\n if (\n typeof name === 'string' &&\n schemasObj &&\n Object.prototype.hasOwnProperty.call(schemasObj, name) &&\n schemasObj[name] === originalSchemas[originalPointer]\n ) {\n delete schemasObj[name];\n }\n }\n event.timeEnd();\n};\n\n/**\n * Create writable variants of parent schemas that have discriminators\n * and are referenced by split schemas.\n */\nfunction splitDiscriminatorSchemas({\n config,\n existingNames,\n schemasPointerNamespace,\n spec,\n split,\n}: {\n config: ReadWriteConfig;\n existingNames: Set<string>;\n schemasPointerNamespace: string;\n spec: unknown;\n split: SplitSchemas;\n}) {\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) return;\n\n const parentSchemasToSplit = new Map<string, Set<Scope>>();\n\n // First pass: identify parent schemas that need writable variants\n for (const [name, schema] of Object.entries(split.schemas)) {\n const pointer = `${schemasPointerNamespace}${name}`;\n const originalPointer = split.reverseMapping[pointer];\n\n if (originalPointer) {\n const mapping = split.mapping[originalPointer];\n if (mapping) {\n const contextVariant: Scope | null =\n mapping.read === pointer ? 'read' : mapping.write === pointer ? 'write' : null;\n\n // Check allOf for $refs to schemas with discriminators\n if (\n contextVariant &&\n schema &&\n typeof schema === 'object' &&\n 'allOf' in schema &&\n schema.allOf instanceof Array\n ) {\n for (const comp of schema.allOf) {\n if (\n comp &&\n typeof comp === 'object' &&\n '$ref' in comp &&\n typeof comp.$ref === 'string'\n ) {\n const refPath = jsonPointerToPath(comp.$ref);\n const schemaName = refPath[refPath.length - 1];\n\n if (typeof schemaName === 'string' && schemaName in schemasObj) {\n const resolvedSchema = schemasObj[schemaName];\n\n // Check if this schema has a discriminator with mapping\n if (\n resolvedSchema &&\n typeof resolvedSchema === 'object' &&\n 'discriminator' in resolvedSchema &&\n resolvedSchema.discriminator &&\n typeof resolvedSchema.discriminator === 'object' &&\n 'mapping' in resolvedSchema.discriminator &&\n resolvedSchema.discriminator.mapping &&\n typeof resolvedSchema.discriminator.mapping === 'object'\n ) {\n // This parent schema needs a variant for this context\n if (!parentSchemasToSplit.has(comp.$ref)) {\n parentSchemasToSplit.set(comp.$ref, new Set());\n }\n parentSchemasToSplit.get(comp.$ref)!.add(contextVariant);\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Second pass: create writable variants of parent schemas and update their discriminator mappings\n const parentSchemaVariants = new Map<string, SplitMapping[keyof SplitMapping]>();\n\n for (const [parentRef, contexts] of parentSchemasToSplit) {\n const refPath = jsonPointerToPath(parentRef);\n const parentName = refPath[refPath.length - 1];\n\n if (typeof parentName !== 'string' || !(parentName in schemasObj)) continue;\n\n const parentSchema = schemasObj[parentName];\n if (!parentSchema || typeof parentSchema !== 'object') continue;\n\n const variants: SplitMapping[keyof SplitMapping] = {};\n\n // Create variants for each context\n for (const context of contexts) {\n const variantSchema = deepClone(parentSchema);\n\n // Update discriminator mapping in the variant\n if (\n 'discriminator' in variantSchema &&\n variantSchema.discriminator &&\n typeof variantSchema.discriminator === 'object' &&\n 'mapping' in variantSchema.discriminator &&\n variantSchema.discriminator.mapping &&\n typeof variantSchema.discriminator.mapping === 'object'\n ) {\n const mapping = variantSchema.discriminator.mapping;\n const updatedMapping: Record<string, string> = {};\n\n for (const [discriminatorValue, originalRef] of Object.entries(mapping)) {\n const map = split.mapping[originalRef];\n if (map) {\n if (context === 'read' && map.read) {\n updatedMapping[discriminatorValue] = map.read;\n } else if (context === 'write' && map.write) {\n updatedMapping[discriminatorValue] = map.write;\n } else {\n updatedMapping[discriminatorValue] = originalRef;\n }\n } else {\n updatedMapping[discriminatorValue] = originalRef;\n }\n }\n\n variantSchema.discriminator.mapping = updatedMapping;\n }\n\n // Add the variant to split.schemas with an appropriate name\n if (context === 'write') {\n const writeBase = applyNaming(parentName, config.requests);\n const writeName = getUniqueComponentName({\n base: writeBase,\n components: existingNames,\n });\n existingNames.add(writeName);\n split.schemas[writeName] = variantSchema;\n variants.write = `${schemasPointerNamespace}${writeName}`;\n }\n // We could create read variants too, but typically they're not needed\n // since the original schema serves as the read variant\n }\n\n parentSchemaVariants.set(parentRef, variants);\n }\n\n // Third pass: update $refs in split schemas to point to the parent variants\n for (const [name, schema] of Object.entries(split.schemas)) {\n const pointer = `${schemasPointerNamespace}${name}`;\n const originalPointer = split.reverseMapping[pointer];\n if (!originalPointer) continue;\n\n const mapping = split.mapping[originalPointer];\n if (!mapping) continue;\n\n const contextVariant: Scope | null =\n mapping.read === pointer ? 'read' : mapping.write === pointer ? 'write' : null;\n\n if (contextVariant && schema && typeof schema === 'object') {\n // Update $refs in allOf\n if ('allOf' in schema && schema.allOf instanceof Array) {\n for (let i = 0; i < schema.allOf.length; i++) {\n const comp = schema.allOf[i];\n\n if (comp && typeof comp === 'object' && '$ref' in comp && typeof comp.$ref === 'string') {\n const variants = parentSchemaVariants.get(comp.$ref);\n\n if (variants) {\n if (contextVariant === 'write' && variants.write) {\n comp.$ref = variants.write;\n } else if (contextVariant === 'read' && variants.read) {\n comp.$ref = variants.read;\n }\n }\n }\n }\n }\n }\n }\n}\n\n/**\n * Splits schemas with both 'read' and 'write' scopes into read/write variants.\n * Returns the new schemas and a mapping from original pointer to new variant pointers.\n *\n * @param config - The readWrite transform config\n * @param graph - The Graph containing all nodes and their scopes\n * @param spec - The OpenAPI spec object\n * @returns SplitSchemas - The split schemas and pointer mappings\n */\nexport const splitSchemas = ({\n config,\n graph,\n logger,\n spec,\n}: {\n config: ReadWriteConfig;\n graph: Graph;\n logger: Logger;\n spec: unknown;\n}): SplitSchemas => {\n const event = logger.timeEvent('split-schemas');\n const existingNames = new Set<string>();\n const split: SplitSchemas = {\n mapping: {},\n reverseMapping: {},\n schemas: {},\n };\n\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n const schemasNamespaceSegments = schemasPointerNamespace.split('/').length - 1;\n\n /**\n * Extracts the schema name from pointer, but only if it's a top-level schema\n * pointer. Returns an empty string if it's a nested pointer.\n * @param pointer\n * @returns Schema's base name.\n */\n const pointerToSchema = (pointer: string): string => {\n if (pointer.startsWith(schemasPointerNamespace)) {\n const path = jsonPointerToPath(pointer);\n if (path.length === schemasNamespaceSegments) {\n return path[schemasNamespaceSegments - 1] || '';\n }\n }\n return '';\n };\n\n // Collect all existing schema names\n for (const pointer of graph.nodes.keys()) {\n const name = pointerToSchema(pointer);\n if (name) existingNames.add(name);\n }\n\n for (const [pointer, nodeInfo] of graph.nodes) {\n const name = pointerToSchema(pointer);\n // Only split top-level schemas, with either read-only or write-only scopes (or both).\n if (\n !name ||\n !(nodeInfo.scopes?.has('read') || nodeInfo.scopes?.has('write')) ||\n !nodeInfo.scopes?.has('normal')\n ) {\n continue;\n }\n\n // read variant\n const readSchema = deepClone<unknown>(nodeInfo.node);\n pruneSchemaByScope(graph, readSchema, 'writeOnly');\n const readBase = applyNaming(name, config.responses);\n const readName =\n readBase === name\n ? readBase\n : getUniqueComponentName({\n base: readBase,\n components: existingNames,\n });\n existingNames.add(readName);\n split.schemas[readName] = readSchema;\n const readPointer = `${schemasPointerNamespace}${readName}`;\n\n // write variant\n const writeSchema = deepClone<unknown>(nodeInfo.node);\n pruneSchemaByScope(graph, writeSchema, 'readOnly');\n\n // Check if this schema (or any of its descendants) references any schema that\n // will need read/write variants. This is determined by checking transitive\n // dependencies for schemas with both 'normal' and ('read' or 'write') scopes.\n const transitiveDeps = graph.transitiveDependencies.get(pointer) || new Set();\n const referencesReadWriteSchemas = Array.from(transitiveDeps).some((depPointer) => {\n const depNodeInfo = graph.nodes.get(depPointer);\n return (\n depNodeInfo?.scopes?.has('normal') &&\n (depNodeInfo.scopes.has('read') || depNodeInfo.scopes.has('write'))\n );\n });\n\n // If pruning did not change anything (both variants equal and equal to original),\n // and the schema doesn't reference any schemas that will have read/write variants,\n // skip splitting and keep the original single schema.\n if (\n !referencesReadWriteSchemas &&\n deepEqual(readSchema, writeSchema) &&\n deepEqual(readSchema, nodeInfo.node)\n ) {\n continue;\n }\n const writeBase = applyNaming(name, config.requests);\n const writeName =\n writeBase === name && writeBase !== readName\n ? writeBase\n : getUniqueComponentName({\n base: writeBase,\n components: existingNames,\n });\n existingNames.add(writeName);\n split.schemas[writeName] = writeSchema;\n const writePointer = `${schemasPointerNamespace}${writeName}`;\n\n split.mapping[pointer] = {\n read: readPointer,\n write: writePointer,\n };\n split.reverseMapping[readPointer] = pointer;\n split.reverseMapping[writePointer] = pointer;\n }\n\n splitDiscriminatorSchemas({\n config,\n existingNames,\n schemasPointerNamespace,\n spec,\n split,\n });\n\n event.timeEnd();\n return split;\n};\n\ntype WalkArgs = {\n context: Scope | null;\n currentPointer: string | null;\n inSchema: boolean;\n node: unknown;\n path: ReadonlyArray<string | number>;\n visited?: Set<string>;\n};\n\n/**\n * Recursively updates $ref fields in the spec to point to the correct read/write variant\n * according to the current context (read/write), using the split mapping.\n *\n * @param spec - The OpenAPI spec object\n * @param split - The split mapping (from splitSchemas)\n */\nexport const updateRefsInSpec = ({\n logger,\n spec,\n split,\n}: {\n logger: Logger;\n spec: unknown;\n split: Omit<SplitSchemas, 'schemas'>;\n}): void => {\n const event = logger.timeEvent('update-refs-in-spec');\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n\n const walk = ({\n context,\n currentPointer,\n inSchema,\n node,\n path,\n visited = new Set(),\n }: WalkArgs): void => {\n if (node instanceof Array) {\n node.forEach((item, index) =>\n walk({\n context,\n currentPointer,\n inSchema,\n node: item,\n path: [...path, index],\n visited,\n }),\n );\n } else if (node && typeof node === 'object') {\n // Detect if we're entering a split schema variant\n let nextPointer = currentPointer;\n let nextContext = context;\n if (isPathRootSchema(path)) {\n // Use the last path segment instead of a fixed index (path[2]) because\n // path depth varies across OAS2/OAS3 and contexts; fixed indexing is brittle.\n const nameSegment = path[path.length - 1] as string;\n nextPointer = `${schemasPointerNamespace}${nameSegment}`;\n const originalPointer = split.reverseMapping[nextPointer];\n if (originalPointer) {\n const mapping = split.mapping[originalPointer];\n if (mapping?.read === nextPointer) {\n nextContext = 'read';\n } else if (mapping?.write === nextPointer) {\n nextContext = 'write';\n }\n }\n // For schemas that are not split variants, keep the inherited context.\n // This ensures that $refs inside these schemas are resolved based on\n // where the schema is actually used (requestBody vs responses), not\n // based on the schema's own scopes which track readOnly/writeOnly fields.\n }\n\n const compContext = getComponentContext(path);\n if (compContext !== undefined) {\n // For each component, walk with the correct context\n for (const key in node) {\n if (!Object.prototype.hasOwnProperty.call(node, key)) {\n continue;\n }\n walk({\n context: compContext,\n currentPointer: nextPointer,\n inSchema: false,\n node: (node as Record<string, unknown>)[key],\n path: [...path, key],\n visited,\n });\n }\n return;\n }\n\n for (const key in node) {\n if (!Object.prototype.hasOwnProperty.call(node, key)) {\n continue;\n }\n const value = (node as Record<string, unknown>)[key];\n\n // Only treat context switches at the OpenAPI structure level (not inside schemas)\n if (!inSchema) {\n if (key === 'requestBody') {\n walk({\n context: 'write',\n currentPointer: nextPointer,\n inSchema: false,\n node: value,\n path: [...path, key],\n visited,\n });\n continue;\n }\n if (key === 'responses') {\n walk({\n context: 'read',\n currentPointer: nextPointer,\n inSchema: false,\n node: value,\n path: [...path, key],\n visited,\n });\n continue;\n }\n if (key === 'parameters' && Array.isArray(value)) {\n value.forEach((param, index) => {\n if (param && typeof param === 'object' && 'schema' in param) {\n walk({\n context: 'write',\n currentPointer: nextPointer,\n inSchema: true,\n node: param.schema,\n path: [...path, key, index, 'schema'],\n visited,\n });\n }\n // Also handle content (OpenAPI 3.x)\n if (param && typeof param === 'object' && 'content' in param) {\n walk({\n context: 'write',\n currentPointer: nextPointer,\n inSchema: false,\n node: param.content,\n path: [...path, key, index, 'content'],\n visited,\n });\n }\n });\n continue;\n }\n // OpenAPI 3.x: headers in responses\n if (key === 'headers' && typeof value === 'object' && value !== null) {\n for (const headerKey in value) {\n if (!Object.prototype.hasOwnProperty.call(value, headerKey)) {\n continue;\n }\n walk({\n context: 'read',\n currentPointer: nextPointer,\n inSchema: false,\n node: (value as Record<string, unknown>)[headerKey],\n path: [...path, key, headerKey],\n visited,\n });\n }\n continue;\n }\n }\n\n // Entering a schema context\n if (schemaKeys.has(key)) {\n walk({\n context: nextContext,\n currentPointer: nextPointer,\n inSchema: true,\n node: value,\n path: [...path, key],\n visited,\n });\n } else if (key === '$ref' && typeof value === 'string') {\n // Prefer exact match first\n const map = split.mapping[value];\n if (map) {\n if (nextContext === 'read' && map.read) {\n (node as Record<string, unknown>)[key] = map.read;\n } else if (nextContext === 'write' && map.write) {\n (node as Record<string, unknown>)[key] = map.write;\n } else if (!nextContext && map.read) {\n // For schemas with no context (unused in operations), default to read variant\n // This ensures $refs in unused schemas don't point to removed originals\n (node as Record<string, unknown>)[key] = map.read;\n }\n }\n } else if (key === 'discriminator' && typeof value === 'object' && value !== null) {\n // Update discriminator mappings to point to the correct read/write variants\n if ('mapping' in value && value.mapping && typeof value.mapping === 'object') {\n const updatedMapping: Record<string, string> = {};\n for (const [discriminatorValue, originalRef] of Object.entries(value.mapping)) {\n const map = split.mapping[originalRef];\n if (map) {\n if (nextContext === 'read' && map.read) {\n updatedMapping[discriminatorValue] = map.read;\n } else if (nextContext === 'write' && map.write) {\n updatedMapping[discriminatorValue] = map.write;\n } else {\n // For schemas with no context, don't update the mapping.\n // This preserves the original mapping for base schemas.\n updatedMapping[discriminatorValue] = originalRef;\n }\n } else {\n updatedMapping[discriminatorValue] = originalRef;\n }\n }\n value.mapping = updatedMapping;\n }\n // Continue walking the discriminator object for other properties\n walk({\n context: nextContext,\n currentPointer: nextPointer,\n inSchema,\n node: value,\n path: [...path, key],\n visited,\n });\n } else {\n walk({\n context: nextContext,\n currentPointer: nextPointer,\n inSchema,\n node: value,\n path: [...path, key],\n visited,\n });\n }\n }\n }\n };\n walk({\n context: null,\n currentPointer: null,\n inSchema: false,\n node: spec,\n path: [],\n });\n event.timeEnd();\n};\n\n/**\n * Orchestrates the full read/write transform:\n * - Captures original schemas\n * - Splits schemas into read/write variants\n * - Inserts split schemas into the spec\n * - Updates $refs throughout the spec\n * - Removes original schemas that were split\n *\n * @param config - The readWrite transform config\n * @param spec - The OpenAPI spec object\n */\nexport const readWriteTransform = ({\n config,\n logger,\n spec,\n}: {\n config: ReadWriteConfig;\n logger: Logger;\n spec: unknown;\n}) => {\n const { graph } = buildGraph(spec, logger);\n const originalSchemas = captureOriginalSchemas(spec, logger);\n const split = splitSchemas({ config, graph, logger, spec });\n insertSplitSchemasIntoSpec({ logger, spec, split });\n updateRefsInSpec({ logger, spec, split });\n removeOriginalSplitSchemas({ logger, originalSchemas, spec, split });\n};\n","import type { Parser } from '../../../config/parser/types';\nimport { applyNaming } from '../../../utils/naming/naming';\nimport { getSchemasObject } from '../utils/transforms';\nimport { specToSchemasPointerNamespace } from './utils';\n\ntype SchemaNameConfig = Parser['transforms']['schemaName'];\n\n/**\n * Recursively walks the entire spec object and replaces all $ref strings\n * according to the provided rename mapping.\n */\nconst rewriteRefs = (node: unknown, renameMap: Record<string, string>) => {\n if (node instanceof Array) {\n node.forEach((item) => rewriteRefs(item, renameMap));\n } else if (node && typeof node === 'object') {\n for (const [key, value] of Object.entries(node)) {\n if (key === '$ref' && typeof value === 'string' && value in renameMap) {\n (node as Record<string, unknown>)[key] = renameMap[value];\n } else {\n rewriteRefs(value, renameMap);\n }\n }\n }\n};\n\n/**\n * Renames schema component keys and updates all $ref pointers throughout\n * the spec. Handles collisions by skipping renames when the target name\n * already exists or conflicts with another rename.\n */\nexport const schemaNameTransform = ({\n config,\n spec,\n}: {\n config: SchemaNameConfig;\n spec: unknown;\n}) => {\n if (!config) {\n return;\n }\n\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) {\n return;\n }\n\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n if (!schemasPointerNamespace) {\n return;\n }\n\n const renameMap: Record<string, string> = {};\n const newNames = new Set<string>();\n const namingConfig = { name: config };\n\n for (const oldName of Object.keys(schemasObj)) {\n const newName = applyNaming(oldName, namingConfig);\n\n if (newName === oldName || newName in schemasObj || newNames.has(newName)) {\n continue;\n }\n\n renameMap[`${schemasPointerNamespace}${oldName}`] = `${schemasPointerNamespace}${newName}`;\n newNames.add(newName);\n }\n\n for (const [oldPointer, newPointer] of Object.entries(renameMap)) {\n const oldName = oldPointer.slice(schemasPointerNamespace.length);\n const newName = newPointer.slice(schemasPointerNamespace.length);\n const schema = schemasObj[oldName];\n\n delete schemasObj[oldName];\n schemasObj[newName] = schema;\n }\n\n if (Object.keys(renameMap).length > 0) {\n rewriteRefs(spec, renameMap);\n }\n};\n","import type { Context } from '../../../ir/context';\nimport { enumsTransform } from './enums';\nimport { propertiesRequiredByDefaultTransform } from './propertiesRequiredByDefault';\nimport { readWriteTransform } from './readWrite';\nimport { schemaNameTransform } from './schemas';\n\nexport const transformOpenApiSpec = ({ context }: { context: Context }) => {\n const { logger } = context;\n const eventTransformOpenApiSpec = logger.timeEvent('transform-openapi-spec');\n\n if (context.config.parser.transforms.schemaName) {\n schemaNameTransform({\n config: context.config.parser.transforms.schemaName,\n spec: context.spec,\n });\n }\n\n if (context.config.parser.transforms.enums.enabled) {\n enumsTransform({\n config: context.config.parser.transforms.enums,\n spec: context.spec,\n });\n }\n\n if (context.config.parser.transforms.propertiesRequiredByDefault) {\n propertiesRequiredByDefaultTransform({ spec: context.spec });\n }\n\n if (context.config.parser.transforms.readWrite.enabled) {\n readWriteTransform({\n config: context.config.parser.transforms.readWrite,\n logger,\n spec: context.spec,\n });\n }\n eventTransformOpenApiSpec.timeEnd();\n};\n","import type { IR } from '../../../ir/types';\n\nexport const mergeParametersObjects = ({\n source,\n target,\n}: {\n source: IR.ParametersObject | undefined;\n target: IR.ParametersObject | undefined;\n}): IR.ParametersObject | undefined => {\n const result = { ...target };\n\n if (source) {\n if (source.cookie) {\n if (result.cookie) {\n result.cookie = {\n ...result.cookie,\n ...source.cookie,\n };\n } else {\n result.cookie = source.cookie;\n }\n }\n\n if (source.header) {\n if (result.header) {\n result.header = {\n ...result.header,\n ...source.header,\n };\n } else {\n result.header = source.header;\n }\n }\n\n if (source.path) {\n if (result.path) {\n result.path = {\n ...result.path,\n ...source.path,\n };\n } else {\n result.path = source.path;\n }\n }\n\n if (source.query) {\n if (result.query) {\n result.query = {\n ...result.query,\n ...source.query,\n };\n } else {\n result.query = source.query;\n }\n }\n }\n\n if (!Object.keys(result).length) {\n return;\n }\n\n return result;\n};\n","import colors from 'ansi-colors';\n\nimport type { Context } from '../../../ir/context';\n\nexport interface ValidatorIssue {\n /**\n * Machine-readable issue code\n *\n * @example\n * 'invalid_type'\n */\n code: 'duplicate_key' | 'invalid_type' | 'missing_required_field';\n /**\n * Optional additional data.\n *\n * @example\n * 'expectedType'\n */\n context?: Record<string, any>;\n /**\n * Human-readable issue summary.\n */\n message: string;\n /**\n * JSONPath-like array to issue location.\n */\n path: ReadonlyArray<string | number>;\n /**\n * Error severity.\n */\n severity: 'error' | 'warning';\n}\n\nexport interface ValidatorResult {\n issues: ReadonlyArray<ValidatorIssue>;\n valid: boolean;\n}\n\nconst isSimpleKey = (key: string) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n\nconst formatPath = (path: ReadonlyArray<string | number>): string =>\n path\n .map((segment, i) => {\n if (typeof segment === 'number') {\n return `[${segment}]`;\n }\n\n if (i === 0) {\n // first segment no dot or brackets\n return segment;\n }\n\n return isSimpleKey(segment) ? `.${segment}` : `['${segment.replace(/\"/g, \"\\\\'\")}']`;\n })\n .join('');\n\nconst formatValidatorIssue = (issue: ValidatorIssue): string => {\n const pathStr = formatPath(issue.path);\n const level = issue.severity === 'error' ? colors.bold.red : colors.bold.yellow;\n\n const highlightedMessage = issue.message.replace(/`([^`]+)`/g, (_, code) =>\n colors.yellow(`\\`${code}\\``),\n );\n\n return `${level(`[${issue.severity.toUpperCase()}]`)} ${colors.cyan(pathStr)}: ${highlightedMessage}`;\n};\n\nconst shouldPrint = ({ context, issue }: { context: Context; issue: ValidatorIssue }) => {\n if (context.config.logs.level === 'silent') {\n return false;\n }\n\n if (issue.severity === 'error') {\n return context.config.logs.level !== 'warn';\n }\n\n return true;\n};\n\nexport const handleValidatorResult = ({\n context,\n result,\n}: {\n context: Context;\n result: ValidatorResult;\n}) => {\n for (const issue of result.issues) {\n if (shouldPrint({ context, issue })) {\n console.log(formatValidatorIssue(issue));\n }\n }\n\n if (!result.valid) {\n process.exit(1);\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { OpenApiV2_0_X, OperationObject, PathItemObject, PathsObject } from '../types/spec';\n\n/**\n * Replace source spec with filtered version.\n */\nexport const filterSpec = ({\n logger,\n operations,\n preserveOrder,\n schemas,\n spec,\n}: {\n logger: Logger;\n operations: Set<string>;\n parameters: Set<string>;\n preserveOrder: boolean;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n spec: OpenApiV2_0_X;\n}) => {\n const eventFilterSpec = logger.timeEvent('filter-spec');\n if (spec.definitions) {\n const filtered: typeof spec.definitions = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.definitions)) {\n if (schemas.has(addNamespace('schema', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of schemas) {\n const { name } = removeNamespace(key);\n const source = spec.definitions[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.definitions = filtered;\n }\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n\n for (const method of httpMethods) {\n // @ts-expect-error\n const operation = pathItem[method] as OperationObject;\n if (!operation) {\n continue;\n }\n\n const key = addNamespace('operation', createOperationKey({ method, path }));\n if (!operations.has(key)) {\n // @ts-expect-error\n delete pathItem[method];\n }\n }\n\n // remove paths that have no operations left\n if (!Object.keys(pathItem).length) {\n delete spec.paths[path];\n }\n }\n }\n eventFilterSpec.timeEnd();\n};\n","const fileLikeRegExp =\n /^(application\\/(pdf|rtf|msword|vnd\\.(ms-|openxmlformats-officedocument\\.)|zip|x-(7z|tar|rar|zip|iso)|octet-stream|gzip|x-msdownload|json\\+download|xml|x-yaml|x-7z-compressed|x-tar)|text\\/(yaml|css|javascript)|audio\\/(mpeg|wav)|video\\/(mp4|x-matroska)|image\\/(vnd\\.adobe\\.photoshop|svg\\+xml))(; ?charset=[^;]+)?$/i;\nconst jsonMimeRegExp = /^application\\/(.*\\+)?json(;.*)?$/i;\nconst multipartFormDataMimeRegExp = /^multipart\\/form-data(;.*)?$/i;\nconst textMimeRegExp = /^text\\/[a-z0-9.+-]+(;.*)?$/i;\nconst xWwwFormUrlEncodedMimeRegExp = /^application\\/x-www-form-urlencoded(;.*)?$/i;\nconst octetStreamMimeRegExp = /^application\\/octet-stream(;.*)?$/i;\n\nexport type IRMediaType = 'form-data' | 'json' | 'text' | 'url-search-params' | 'octet-stream';\n\nexport const isMediaTypeFileLike = ({ mediaType }: { mediaType: string }): boolean => {\n fileLikeRegExp.lastIndex = 0;\n return fileLikeRegExp.test(mediaType);\n};\n\nexport const mediaTypeToIrMediaType = ({\n mediaType,\n}: {\n mediaType: string;\n}): IRMediaType | undefined => {\n jsonMimeRegExp.lastIndex = 0;\n if (jsonMimeRegExp.test(mediaType)) {\n return 'json';\n }\n\n multipartFormDataMimeRegExp.lastIndex = 0;\n if (multipartFormDataMimeRegExp.test(mediaType)) {\n return 'form-data';\n }\n\n textMimeRegExp.lastIndex = 0;\n if (textMimeRegExp.test(mediaType)) {\n return 'text';\n }\n\n xWwwFormUrlEncodedMimeRegExp.lastIndex = 0;\n if (xWwwFormUrlEncodedMimeRegExp.test(mediaType)) {\n return 'url-search-params';\n }\n\n octetStreamMimeRegExp.lastIndex = 0;\n if (octetStreamMimeRegExp.test(mediaType)) {\n return 'octet-stream';\n }\n\n return;\n};\n","import type { IRMediaType } from '../../../ir/mediaType';\nimport { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType';\nimport type { ReferenceObject, ResponseObject, SchemaObject } from '../types/spec';\n\ninterface Content {\n mediaType: string;\n schema: SchemaObject | ReferenceObject | undefined;\n type: IRMediaType | undefined;\n}\n\nexport const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => {\n const { mediaType, schema } = content;\n\n if (schema && '$ref' in schema) {\n return {\n allOf: [{ ...schema }],\n };\n }\n\n if (!schema) {\n if (isMediaTypeFileLike({ mediaType })) {\n return {\n format: 'binary',\n type: 'string',\n };\n }\n return;\n }\n\n if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) {\n return {\n ...schema,\n format: 'binary',\n };\n }\n\n return schema;\n};\n\nexport const mediaTypeObjects = ({\n mimeTypes,\n response,\n}: {\n mimeTypes: ReadonlyArray<string> | undefined;\n response: Pick<ResponseObject, 'schema'>;\n}): ReadonlyArray<Content> => {\n const objects: Array<Content> = [];\n\n for (const mediaType of mimeTypes ?? []) {\n objects.push({\n mediaType,\n schema: response.schema,\n type: mediaTypeToIrMediaType({ mediaType }),\n });\n }\n\n return objects;\n};\n","import type { Parser } from '../config/parser/types';\nimport type { IR } from './types';\n\nexport function getPaginationKeywordsRegExp(pagination: Parser['pagination']): RegExp {\n const pattern = `^(${pagination.keywords.join('|')})$`;\n return new RegExp(pattern);\n}\n\nexport interface Pagination {\n in: 'body' | 'cookie' | 'header' | 'path' | 'query';\n name: string;\n schema: IR.SchemaObject;\n}\n","import type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\n\n/**\n * Supported types for discriminator properties.\n */\nexport type DiscriminatorPropertyType = 'boolean' | 'integer' | 'number' | 'string';\n\n/**\n * Converts a string discriminator mapping value to the appropriate type based on\n * the actual property type in the schema.\n *\n * OpenAPI discriminator mappings always use string keys, but the actual discriminator\n * property may be a boolean, number, or integer. This function converts the string\n * key to the correct runtime value and IR type.\n */\nexport const convertDiscriminatorValue = (\n value: string,\n propertyType: DiscriminatorPropertyType,\n): { const: IR.SchemaObject['const']; type: IR.SchemaObject['type'] } => {\n switch (propertyType) {\n case 'boolean': {\n const lowerValue = value.toLowerCase();\n if (lowerValue !== 'true' && lowerValue !== 'false') {\n console.warn(\n '๐Ÿšจ',\n `non-boolean discriminator mapping value \"${value}\" for boolean property, falling back to string`,\n );\n return {\n const: value,\n type: 'string',\n };\n }\n return {\n const: lowerValue === 'true',\n type: 'boolean',\n };\n }\n case 'integer': {\n const parsed = parseInt(value, 10);\n if (Number.isNaN(parsed)) {\n console.warn(\n '๐Ÿšจ',\n `non-numeric discriminator mapping value \"${value}\" for integer property, falling back to string`,\n );\n return {\n const: value,\n type: 'string',\n };\n }\n return {\n const: parsed,\n type: 'integer',\n };\n }\n case 'number': {\n const parsed = parseFloat(value);\n if (Number.isNaN(parsed)) {\n console.warn(\n '๐Ÿšจ',\n `non-numeric discriminator mapping value \"${value}\" for number property, falling back to string`,\n );\n return {\n const: value,\n type: 'string',\n };\n }\n return {\n const: parsed,\n type: 'number',\n };\n }\n default:\n return {\n const: value,\n type: 'string',\n };\n }\n};\n\nexport const discriminatorValues = (\n $ref: string,\n mapping?: Record<string, string>,\n shouldUseRefAsValue?: () => boolean,\n): ReadonlyArray<string> => {\n const values: Array<string> = [];\n\n for (const name in mapping) {\n if (mapping[name] === $ref) {\n values.push(name);\n }\n }\n\n if (!values.length && (!shouldUseRefAsValue || shouldUseRefAsValue())) {\n return [refToName($ref)];\n }\n\n return values;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { addItemsToSchema } from '../../../ir/utils';\nimport type {\n SchemaState,\n SchemaType,\n SchemaWithRequired,\n} from '../../../openApi/shared/types/schema';\nimport { discriminatorValues } from '../../../openApi/shared/utils/discriminator';\nimport { isTopLevelComponent, refToName } from '../../../utils/ref';\nimport type { SchemaObject } from '../types/spec';\n\nexport const getSchemaType = ({\n schema,\n}: {\n schema: SchemaObject;\n}): SchemaType<SchemaObject> | undefined => {\n if (schema.type) {\n return schema.type;\n }\n\n // infer object based on the presence of properties\n if (schema.properties) {\n return 'object';\n }\n\n return;\n};\n\nconst parseSchemaJsDoc = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.example) {\n irSchema.example = schema.example;\n }\n\n if (schema.description) {\n irSchema.description = schema.description;\n }\n\n if (schema.title) {\n irSchema.title = schema.title;\n }\n};\n\nconst parseSchemaMeta = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.default !== undefined) {\n irSchema.default = schema.default;\n }\n\n if (schema.exclusiveMaximum) {\n if (schema.maximum !== undefined) {\n irSchema.exclusiveMaximum = schema.maximum;\n }\n } else if (schema.maximum !== undefined) {\n irSchema.maximum = schema.maximum;\n }\n\n if (schema.exclusiveMinimum) {\n if (schema.minimum !== undefined) {\n irSchema.exclusiveMinimum = schema.minimum;\n }\n } else if (schema.minimum !== undefined) {\n irSchema.minimum = schema.minimum;\n }\n\n if (schema.format) {\n irSchema.format = schema.format;\n }\n\n if (schema.maxItems !== undefined) {\n irSchema.maxItems = schema.maxItems;\n }\n\n if (schema.maxLength !== undefined) {\n irSchema.maxLength = schema.maxLength;\n }\n\n if (schema.minItems !== undefined) {\n irSchema.minItems = schema.minItems;\n }\n\n if (schema.minLength !== undefined) {\n irSchema.minLength = schema.minLength;\n }\n\n if (schema.pattern) {\n irSchema.pattern = schema.pattern;\n }\n\n if (schema.readOnly) {\n irSchema.accessScope = 'read';\n }\n};\n\nconst parseArray = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (schema.maxItems && schema.maxItems === schema.minItems) {\n irSchema.type = 'tuple';\n } else {\n irSchema.type = 'array';\n }\n\n let schemaItems: Array<IR.SchemaObject> = [];\n\n if (schema.items) {\n const irItemsSchema = schemaToIrSchema({\n context,\n schema: schema.items,\n state,\n });\n\n if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {\n schemaItems = Array(schema.maxItems).fill(irItemsSchema);\n } else {\n if ('$ref' in schema.items) {\n schemaItems.push(irItemsSchema);\n } else {\n const ofArray = schema.items.allOf;\n if (ofArray && ofArray.length > 1 && !schema.items['x-nullable']) {\n // bring composition up to avoid incorrectly nested arrays\n irSchema = {\n ...irSchema,\n ...irItemsSchema,\n };\n } else {\n schemaItems.push(irItemsSchema);\n }\n }\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseBoolean = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'boolean';\n\n return irSchema;\n};\n\nconst parseNumber = ({\n irSchema = {},\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = schema.type;\n\n return irSchema;\n};\n\nconst parseObject = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'object';\n\n const schemaProperties: Record<string, IR.SchemaObject> = {};\n\n for (const name in schema.properties) {\n const property = schema.properties[name]!;\n if (typeof property === 'boolean') {\n // TODO: parser - handle boolean properties\n } else {\n const irPropertySchema = schemaToIrSchema({\n context,\n schema: property,\n state,\n });\n schemaProperties[name] = irPropertySchema;\n }\n }\n\n if (Object.keys(schemaProperties).length) {\n irSchema.properties = schemaProperties;\n }\n\n if (schema.additionalProperties === undefined) {\n if (!irSchema.properties) {\n irSchema.additionalProperties = {\n type: 'unknown',\n };\n }\n } else if (typeof schema.additionalProperties === 'boolean') {\n // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf\n // This would override inherited properties from other schemas in the composition\n const isEmptyObjectInAllOf =\n state.inAllOf &&\n schema.additionalProperties === false &&\n (!schema.properties || !Object.keys(schema.properties).length);\n\n if (!isEmptyObjectInAllOf) {\n irSchema.additionalProperties = {\n type: schema.additionalProperties ? 'unknown' : 'never',\n };\n }\n } else {\n const irAdditionalPropertiesSchema = schemaToIrSchema({\n context,\n schema: schema.additionalProperties,\n state,\n });\n irSchema.additionalProperties = irAdditionalPropertiesSchema;\n }\n\n if (schema.required) {\n irSchema.required = schema.required;\n }\n\n return irSchema;\n};\n\nconst parseString = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'string';\n\n return irSchema;\n};\n\nexport const parseExtensions = ({ source, target }: { source: object; target: object }) => {\n for (const key in source) {\n if (key.startsWith('x-')) {\n (target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];\n }\n }\n};\n\nconst initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n\n parseSchemaJsDoc({\n irSchema,\n schema,\n });\n\n parseExtensions({\n source: schema,\n target: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseAllOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'allOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.allOf;\n\n for (const compositionSchema of compositionSchemas) {\n const originalInAllOf = state.inAllOf;\n // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components\n if (!('$ref' in compositionSchema)) {\n state.inAllOf = true;\n }\n const irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n state.inAllOf = originalInAllOf;\n if (state.inAllOf === undefined) {\n delete state.inAllOf;\n }\n\n if (schema.required) {\n if (irCompositionSchema.required) {\n irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];\n } else {\n irCompositionSchema.required = schema.required;\n }\n }\n\n schemaItems.push(irCompositionSchema);\n\n if (compositionSchema.$ref) {\n const ref = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n // `$ref` should be passed from the root `parseSchema()` call\n if (ref.discriminator && state.$ref) {\n const values = discriminatorValues(state.$ref);\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) => ({\n const: value,\n type: 'string',\n }));\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [ref.discriminator]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n type: 'object',\n };\n if (ref.required?.includes(ref.discriminator)) {\n irDiscriminatorSchema.required = [ref.discriminator];\n }\n schemaItems.push(irDiscriminatorSchema);\n }\n }\n }\n\n if (schemaType === 'object') {\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n for (const requiredProperty of irObjectSchema.required ?? []) {\n if (!irObjectSchema.properties[requiredProperty]) {\n for (const compositionSchema of compositionSchemas) {\n // TODO: parser - this could be probably resolved more accurately\n const finalCompositionSchema = compositionSchema.$ref\n ? context.resolveRef<SchemaObject>(compositionSchema.$ref)\n : compositionSchema;\n\n if (getSchemaType({ schema: finalCompositionSchema }) === 'object') {\n const irCompositionSchema = parseOneType({\n context,\n schema: {\n ...finalCompositionSchema,\n type: 'object',\n },\n state,\n });\n\n if (irCompositionSchema.properties?.[requiredProperty]) {\n irObjectSchema.properties[requiredProperty] =\n irCompositionSchema.properties[requiredProperty];\n break;\n }\n }\n }\n }\n }\n schemaItems.push(irObjectSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n logicalOperator: 'and',\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schema['x-nullable']) {\n // nest composition to avoid producing an intersection with null\n const nestedItems: Array<IR.SchemaObject> = [\n {\n type: 'null',\n },\n ];\n\n if (schemaItems.length) {\n nestedItems.unshift(irSchema);\n }\n\n irSchema = {\n items: nestedItems,\n logicalOperator: 'or',\n };\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original deprecated\n if (nestedItems[0]!.deprecated) {\n irSchema.deprecated = nestedItems[0]!.deprecated;\n }\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original description\n if (nestedItems[0]!.description) {\n irSchema.description = nestedItems[0]!.description;\n }\n }\n\n return irSchema;\n};\n\nconst parseEnum = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'enum'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n irSchema.type = 'enum';\n\n const schemaItems: Array<IR.SchemaObject> = [];\n\n for (const [index, enumValue] of schema.enum.entries()) {\n const typeOfEnumValue = typeof enumValue;\n let enumType: SchemaType<SchemaObject> | 'null' | undefined;\n\n if (\n typeOfEnumValue === 'string' ||\n typeOfEnumValue === 'number' ||\n typeOfEnumValue === 'boolean'\n ) {\n enumType = typeOfEnumValue;\n } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {\n enumType = 'array';\n } else if (enumValue === null) {\n // nullable must be true\n if (schema['x-nullable']) {\n enumType = 'null';\n }\n } else {\n console.warn(\n '๐Ÿšจ',\n `unhandled \"${typeOfEnumValue}\" typeof value \"${enumValue}\" for enum`,\n schema.enum,\n );\n }\n\n if (!enumType) {\n continue;\n }\n\n const irTypeSchema = parseOneType({\n context,\n schema: {\n description: schema['x-enum-descriptions']?.[index],\n title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],\n // cast enum to string temporarily\n type: enumType === 'null' ? 'string' : enumType,\n },\n state,\n });\n\n irTypeSchema.const = enumValue;\n\n // cast enum back\n if (enumType === 'null') {\n irTypeSchema.type = enumType;\n }\n\n if (irTypeSchema.type === 'array') {\n irTypeSchema.type = 'tuple';\n }\n\n schemaItems.push(irTypeSchema);\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseRef = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, '$ref'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/definitions/Foo/properties/bar)\n // to avoid generating orphaned named types or referencing unregistered symbols\n const isComponentsRef = isTopLevelComponent(schema.$ref);\n if (!isComponentsRef) {\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n const irSchema = schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n return irSchema;\n }\n // Fallback to preserving the ref if circular\n }\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n irSchema.$ref = decodeURI(schema.$ref);\n\n // rewrite definitions refs as the internal schema follows OpenAPI 3.x syntax\n // and stores all definitions as reusable schemas\n irSchema.$ref = irSchema.$ref.replace(/#\\/definitions\\/([^/]+)/g, '#/components/schemas/$1');\n\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n }\n\n return irSchema;\n};\n\nconst parseNullableType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n const typeIrSchema: IR.SchemaObject = {};\n\n parseSchemaMeta({ irSchema: typeIrSchema, schema });\n\n if (typeIrSchema.default === null) {\n // clear to avoid duplicate default inside the non-null schema.\n // this would produce incorrect validator output\n delete typeIrSchema.default;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [\n parseOneType({\n context,\n irSchema: typeIrSchema,\n schema,\n state,\n }),\n {\n type: 'null',\n },\n ];\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseType = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n\n const type = getSchemaType({ schema });\n\n if (!type) {\n return irSchema;\n }\n\n if (schema['x-nullable']) {\n return parseNullableType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n }\n\n return parseOneType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n};\n\nconst parseOneType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n }\n\n switch (schema.type) {\n case 'array':\n return parseArray({\n context,\n irSchema,\n schema,\n state,\n });\n case 'boolean':\n return parseBoolean({\n context,\n irSchema,\n schema,\n state,\n });\n case 'integer':\n case 'number':\n return parseNumber({\n context,\n irSchema,\n schema,\n state,\n });\n case 'object':\n return parseObject({\n context,\n irSchema,\n schema,\n state,\n });\n case 'string':\n return parseString({\n context,\n irSchema,\n schema,\n state,\n });\n default:\n // gracefully handle invalid type\n return parseUnknown({\n context,\n irSchema,\n schema,\n });\n }\n};\n\nconst parseUnknown = ({\n irSchema,\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n irSchema.type = 'unknown';\n\n parseSchemaMeta({ irSchema, schema });\n\n return irSchema;\n};\n\nexport const schemaToIrSchema = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaObject;\n state: SchemaState | undefined;\n}): IR.SchemaObject => {\n if (!state) {\n state = {\n circularReferenceTracker: new Set(),\n };\n }\n\n if (state.$ref) {\n state.circularReferenceTracker.add(state.$ref);\n }\n\n if (schema.$ref) {\n return parseRef({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, '$ref'>,\n state,\n });\n }\n\n if (schema.enum) {\n return parseEnum({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'enum'>,\n state,\n });\n }\n\n if (schema.allOf) {\n return parseAllOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'allOf'>,\n state,\n });\n }\n\n // infer object based on the presence of properties\n if (schema.type || schema.properties) {\n return parseType({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n return parseUnknown({ context, schema });\n};\n\nexport const parseSchema = ({\n $ref,\n context,\n schema,\n}: {\n $ref: string;\n context: Context;\n schema: SchemaObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.schemas) {\n context.ir.components.schemas = {};\n }\n\n context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({\n context,\n schema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { getPaginationKeywordsRegExp } from '../../../ir/pagination';\nimport type { SchemaType } from '../../../openApi/shared/types/schema';\nimport type { ParameterObject, ReferenceObject } from '../types/spec';\nimport type { SchemaObject } from '../types/spec';\nimport { getSchemaType } from './schema';\n\nconst isPaginationType = (schemaType: SchemaType<SchemaObject> | undefined): boolean =>\n schemaType === 'boolean' ||\n schemaType === 'integer' ||\n schemaType === 'number' ||\n schemaType === 'string';\n\n// We handle only simple values for now, up to 1 nested field\nexport const paginationField = ({\n context,\n name,\n schema,\n}: {\n context: Context;\n name: string;\n schema:\n | ParameterObject\n | SchemaObject\n | ReferenceObject\n | {\n in: undefined;\n };\n}): boolean | string => {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n if (paginationRegExp.test(name)) {\n return true;\n }\n\n if ('$ref' in schema) {\n const ref = context.resolveRef<ParameterObject | SchemaObject>(schema.$ref ?? '');\n\n if ('in' in ref && ref.in) {\n const refSchema =\n 'schema' in ref\n ? ref.schema\n : {\n ...ref,\n in: undefined,\n };\n\n return paginationField({\n context,\n name,\n schema: refSchema,\n });\n }\n\n return paginationField({\n context,\n name,\n schema: ref,\n });\n }\n\n if ('in' in schema) {\n if (!schema.in) {\n return false;\n }\n\n const finalSchema =\n 'schema' in schema\n ? schema.schema\n : {\n ...schema,\n in: undefined,\n };\n\n return paginationField({\n context,\n name,\n schema: finalSchema,\n });\n }\n\n for (const name in schema.properties) {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n\n if (paginationRegExp.test(name)) {\n const property = schema.properties[name]!;\n\n if (typeof property !== 'boolean' && !('$ref' in property)) {\n const schemaType = getSchemaType({ schema: property });\n // TODO: resolve deeper references\n\n if (isPaginationType(schemaType)) {\n return name;\n }\n }\n }\n }\n\n for (const allOf of schema.allOf ?? []) {\n const pagination = paginationField({\n context,\n name,\n schema: allOf,\n });\n if (pagination) {\n return pagination;\n }\n }\n\n return false;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type { State } from '../../../openApi/shared/types/state';\nimport { operationToId } from '../../../openApi/shared/utils/operation';\nimport type {\n OperationObject,\n ParameterObject,\n PathItemObject,\n ResponseObject,\n SchemaObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { contentToSchema, mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ninterface Operation\n extends Omit<OperationObject, 'parameters'>, Pick<IR.OperationObject, 'parameters'> {\n requestBody?: OperationObject['parameters'];\n}\n\nconst parseOperationJsDoc = ({\n irOperation,\n operation,\n}: {\n irOperation: IR.OperationObject;\n operation: Operation;\n}) => {\n if (operation.deprecated !== undefined) {\n irOperation.deprecated = operation.deprecated;\n }\n\n if (operation.description) {\n irOperation.description = operation.description;\n }\n\n if (operation.summary) {\n irOperation.summary = operation.summary;\n }\n\n if (operation.tags?.length) {\n irOperation.tags = operation.tags;\n }\n};\n\nconst initIrOperation = ({\n context,\n method,\n operation,\n path,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n state: State;\n}): IR.OperationObject => {\n const irOperation: IR.OperationObject = {\n id: operationToId({\n context,\n id: operation.operationId,\n method,\n path,\n state,\n }),\n method,\n path,\n };\n\n if (operation.operationId) {\n irOperation.operationId = operation.operationId;\n }\n\n parseOperationJsDoc({\n irOperation,\n operation,\n });\n\n parseExtensions({\n source: operation,\n target: irOperation,\n });\n\n return irOperation;\n};\n\nconst operationToIrOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}): IR.OperationObject => {\n const irOperation = initIrOperation({\n context,\n method,\n operation,\n path,\n state,\n });\n\n if (operation.parameters) {\n irOperation.parameters = operation.parameters;\n }\n\n let isRequestBodyRequired = false;\n const requestBodyObject: IR.BodyObject = {\n mediaType: '',\n schema: {\n properties: {},\n required: [],\n type: 'object',\n },\n };\n const requestBodyObjectRequired: Array<string> = [];\n\n // Check if there are any body parameters (not formData) to determine default media type\n const hasBodyParameter = operation.requestBody?.some((param) => {\n const resolvedParam = '$ref' in param ? context.resolveRef<ParameterObject>(param.$ref) : param;\n return resolvedParam.in === 'body';\n });\n\n for (const requestBodyParameter of operation.requestBody ?? []) {\n const requestBody =\n '$ref' in requestBodyParameter\n ? context.resolveRef<ParameterObject>(requestBodyParameter.$ref)\n : requestBodyParameter;\n const schema: SchemaObject =\n requestBody.in === 'body'\n ? requestBody.schema\n : {\n ...requestBody,\n format: requestBody.type === 'file' ? 'binary' : requestBody.format,\n required: undefined,\n type: requestBody.type === 'file' ? 'string' : requestBody.type,\n };\n\n // Only default to JSON if we have body parameters and no consumes specified\n // FormData parameters without consumes should not get a default media type\n let mimeTypes = operation.consumes;\n if (!mimeTypes && hasBodyParameter && requestBody.in === 'body') {\n mimeTypes = ['application/json'];\n }\n\n const contents = mediaTypeObjects({\n mimeTypes,\n response: { schema },\n });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n const pagination = paginationField({\n context,\n name: '',\n schema:\n content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n });\n\n const irSchema = schemaToIrSchema({\n context,\n schema:\n '$ref' in requestBody\n ? {\n allOf: [\n {\n ...requestBody,\n $ref: requestBody.$ref as string,\n required: [],\n type: 'string',\n },\n ],\n description: requestBody.description,\n }\n : content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n state: undefined,\n });\n\n requestBodyObject.mediaType = content.mediaType;\n\n if (requestBody.in === 'body') {\n requestBodyObject.schema = irSchema;\n } else {\n requestBodyObject.schema.properties![requestBody.name] = irSchema;\n\n if (requestBody.required) {\n requestBodyObjectRequired.push(requestBody.name);\n }\n }\n\n if (pagination) {\n requestBodyObject.pagination = pagination;\n }\n\n if (content.type) {\n requestBodyObject.type = content.type;\n }\n }\n\n if (requestBody.required) {\n isRequestBodyRequired = true;\n }\n }\n\n if (requestBodyObject.mediaType) {\n if (requestBodyObjectRequired.length) {\n requestBodyObject.schema.required = requestBodyObjectRequired;\n }\n\n irOperation.body = requestBodyObject;\n\n if (isRequestBodyRequired) {\n irOperation.body.required = isRequestBodyRequired;\n }\n }\n\n for (const name in operation.responses) {\n if (!irOperation.responses) {\n irOperation.responses = {};\n }\n\n const response = operation.responses[name]!;\n const responseObject =\n '$ref' in response ? context.resolveRef<ResponseObject>(response.$ref) : response;\n const contents = mediaTypeObjects({\n // assume JSON by default\n mimeTypes: operation.produces ? operation.produces : ['application/json'],\n response: responseObject,\n });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n irOperation.responses[name] = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: responseObject.description,\n ...contentToSchema({ content }),\n },\n state: undefined,\n }),\n };\n } else {\n irOperation.responses[name] = {\n schema: {\n description: responseObject.description,\n // TODO: parser - cover all statues with empty response bodies\n // 1xx, 204, 205, 304\n type: name === '204' ? 'void' : 'unknown',\n },\n };\n }\n }\n\n if (operation.security) {\n const securitySchemeObjects: Map<string, IR.SecurityObject> = new Map();\n\n for (const securityRequirementObject of operation.security) {\n for (const name in securityRequirementObject) {\n const securitySchemeObject = securitySchemesMap.get(name);\n\n if (!securitySchemeObject) {\n continue;\n }\n\n let irSecuritySchemeObject: IR.SecurityObject | undefined;\n\n if (securitySchemeObject.type === 'apiKey') {\n irSecuritySchemeObject = securitySchemeObject;\n }\n\n if (securitySchemeObject.type === 'basic') {\n irSecuritySchemeObject = {\n description: securitySchemeObject.description,\n scheme: 'basic',\n type: 'http',\n };\n }\n\n if (securitySchemeObject.type === 'oauth2') {\n irSecuritySchemeObject = {\n description: securitySchemeObject.description,\n flows: {},\n type: 'oauth2',\n };\n\n switch (securitySchemeObject.flow) {\n case 'accessCode':\n irSecuritySchemeObject.flows.authorizationCode = {\n authorizationUrl: securitySchemeObject.authorizationUrl!,\n scopes: securitySchemeObject.scopes,\n tokenUrl: securitySchemeObject.tokenUrl!,\n };\n break;\n case 'application':\n irSecuritySchemeObject.flows.clientCredentials = {\n scopes: securitySchemeObject.scopes,\n tokenUrl: securitySchemeObject.tokenUrl!,\n };\n break;\n case 'implicit':\n irSecuritySchemeObject.flows.implicit = {\n authorizationUrl: securitySchemeObject.authorizationUrl!,\n scopes: securitySchemeObject.scopes,\n };\n break;\n case 'password':\n irSecuritySchemeObject.flows.password = {\n scopes: securitySchemeObject.scopes,\n tokenUrl: securitySchemeObject.tokenUrl!,\n };\n break;\n }\n }\n\n if (!irSecuritySchemeObject) {\n continue;\n }\n\n securitySchemeObjects.set(name, irSecuritySchemeObject);\n }\n }\n\n if (securitySchemeObjects.size) {\n irOperation.security = Array.from(securitySchemeObjects.values());\n }\n }\n\n // TODO: parser - handle servers\n // qux: operation.servers\n\n return irOperation;\n};\n\nexport const parsePathOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: {\n context: Context;\n method: Extract<\n keyof PathItemObject,\n 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'\n >;\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.paths) {\n context.ir.paths = {};\n }\n\n if (!context.ir.paths[path]) {\n context.ir.paths[path] = {};\n }\n\n context.ir.paths[path][method] = operationToIrOperation({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type {\n OperationObject,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from '../types/spec';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ntype Parameter = Exclude<ParameterObject, { in: 'body' }>;\n\n/**\n * Returns default parameter `explode` based on value of `collectionFormat`.\n */\nconst defaultExplode = (collectionFormat: Parameter['collectionFormat']): boolean => {\n switch (collectionFormat) {\n case 'multi':\n return true;\n case 'csv':\n case 'pipes':\n case 'ssv':\n case 'tsv':\n default:\n return false;\n }\n};\n\n/**\n * Returns default parameter `style` based on value of `in`.\n */\nconst defaultStyle = (_in: Parameter['in']): Required<IR.ParameterObject>['style'] => {\n switch (_in) {\n case 'header':\n case 'path':\n return 'simple';\n case 'query':\n default:\n return 'form';\n }\n};\n\nexport const parametersArrayToObject = ({\n context,\n operation,\n parameters,\n}: {\n context: Context;\n operation: OperationObject;\n parameters?: ReadonlyArray<ParameterObject | ReferenceObject>;\n}): IR.ParametersObject | undefined => {\n if (!parameters || !Object.keys(parameters).length) {\n return;\n }\n\n const parametersObject: IR.ParametersObject = {};\n\n for (const parameterOrReference of parameters) {\n const parameter =\n '$ref' in parameterOrReference\n ? context.dereference<ParameterObject>(parameterOrReference)\n : parameterOrReference;\n\n // push request body parameters into a separate field\n if (parameter.in === 'body' || parameter.in === 'formData') {\n // @ts-expect-error\n if (!operation.requestBody) {\n // @ts-expect-error\n operation.requestBody = [];\n }\n\n // @ts-expect-error\n operation.requestBody.push(parameter);\n continue;\n }\n\n if (!parametersObject[parameter.in]) {\n parametersObject[parameter.in] = {};\n }\n\n // lowercase keys for case insensitive access\n parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({\n $ref: `#/todo/real/path/to/parameter/${parameter.name}`,\n context,\n parameter,\n });\n }\n\n return parametersObject;\n};\n\nconst parameterToIrParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: Parameter;\n}): IR.ParameterObject => {\n const schema = parameter;\n\n const finalSchema: SchemaObject =\n schema && '$ref' in schema\n ? {\n allOf: [\n {\n ...schema,\n $ref: schema.$ref as string,\n required: Array.isArray(schema.required) ? schema.required : [],\n type: schema.type as SchemaObject['type'],\n },\n ],\n description: parameter.description,\n }\n : {\n description: parameter.description,\n ...schema,\n required: Array.isArray(schema.required) ? schema.required : [],\n type: schema.type as SchemaObject['type'],\n };\n\n const pagination = paginationField({\n context,\n name: parameter.name,\n schema: finalSchema,\n });\n\n const style = defaultStyle(parameter.in);\n const explode = defaultExplode(parameter.collectionFormat);\n const allowReserved = false;\n\n const irParameter: IR.ParameterObject = {\n allowReserved,\n explode,\n location: parameter.in as IR.ParameterObject['location'],\n name: parameter.name,\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n style,\n };\n\n if (parameter.description) {\n irParameter.description = parameter.description;\n }\n\n if (pagination) {\n irParameter.pagination = pagination;\n }\n\n if (parameter.required) {\n irParameter.required = parameter.required;\n }\n\n parseExtensions({\n source: parameter,\n target: irParameter,\n });\n\n return irParameter;\n};\n","const parseUrlRegExp =\n /^(([^:/?#]+):)?((\\/\\/)?([^:/?#]*)(:?([^/?#]*)))?([^?#]*)(\\?([^#]*))?(#(.*))?/;\n\ninterface Url {\n host: string;\n path: string;\n port: string;\n protocol: string;\n}\n\nexport function parseUrl(value: string): Url {\n const errorResponse: Url = {\n host: '',\n path: '',\n port: '',\n protocol: '',\n };\n\n parseUrlRegExp.lastIndex = 0;\n const match = value.match(parseUrlRegExp);\n\n if (!match) {\n return errorResponse;\n }\n\n const host = match[5] || '';\n\n // value is a relative file system path\n if (host === '.' || host === '..') {\n return errorResponse;\n }\n\n const path = match[8] || '';\n const protocol = match[2] || '';\n\n // value is probably a Windows file system path\n if (protocol.length === 1) {\n return errorResponse;\n }\n\n return {\n host,\n path: path === '/' ? '' : path,\n port: match[7] || '',\n protocol,\n };\n}\n","import type { Context } from '../../../ir/context';\nimport { parseUrl } from '../../../utils/url';\n\nexport const parseServers = ({ context }: { context: Context }) => {\n let schemes: ReadonlyArray<string> = context.spec.schemes ?? [];\n let host = context.spec.host ?? '';\n const path = context.spec.basePath ?? '';\n\n for (const input of context.config.input) {\n if (typeof input.path === 'string') {\n const url = parseUrl(input.path);\n\n if (!schemes.length) {\n if (url.protocol) {\n schemes = [url.protocol] as typeof schemes;\n }\n }\n\n if (!host) {\n host = `${url.host}${url.port ? `:${url.port}` : ''}`;\n }\n }\n }\n\n if (!schemes.length) {\n schemes = [''];\n }\n\n const servers = schemes\n .map((scheme) => `${scheme ? `${scheme}://` : ''}${host}${path}`)\n .filter(Boolean);\n\n if (servers.length) {\n context.ir.servers = servers.map((url) => ({\n url,\n }));\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type { OpenApiV2_0_X, PathItemObject, PathsObject } from '../types/spec';\n\nexport const validateOpenApiSpec = (spec: OpenApiV2_0_X, logger: Logger): ValidatorResult => {\n const eventValidate = logger.timeEvent('validate');\n const issues: Array<ValidatorIssue> = [];\n const operationIds = new Map();\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n if (method === 'trace') {\n continue;\n }\n\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const operationKey = createOperationKey({ method, path });\n\n if (operation.operationId) {\n if (!operationIds.has(operation.operationId)) {\n operationIds.set(operation.operationId, operationKey);\n } else {\n issues.push({\n code: 'duplicate_key',\n context: {\n key: 'operationId',\n value: operation.operationId,\n },\n message: 'Duplicate `operationId` found. Each `operationId` must be unique.',\n path: ['paths', path, method, 'operationId'],\n severity: 'error',\n });\n }\n }\n }\n }\n }\n\n eventValidate.timeEnd();\n return {\n issues,\n valid: !issues.some((issue) => issue.severity === 'error'),\n };\n};\n","import type { Context } from '../../../ir/context';\nimport { buildResourceMetadata } from '../../../openApi/shared/graph/meta';\nimport { transformOpenApiSpec } from '../../../openApi/shared/transforms';\nimport type { State } from '../../../openApi/shared/types/state';\nimport {\n createFilteredDependencies,\n createFilters,\n hasFilters,\n} from '../../../openApi/shared/utils/filter';\nimport { buildGraph } from '../../../openApi/shared/utils/graph';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport { handleValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type {\n OpenApiV2_0_X,\n OperationObject,\n PathItemObject,\n PathsObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { filterSpec } from './filter';\nimport { parsePathOperation } from './operation';\nimport { parametersArrayToObject } from './parameter';\nimport { parseSchema } from './schema';\nimport { parseServers } from './server';\nimport { validateOpenApiSpec } from './validate';\n\ntype PathKeys<T extends keyof PathsObject = keyof PathsObject> = keyof T extends infer K\n ? K extends `/${string}`\n ? K\n : never\n : never;\n\nexport const parseV2_0_X = (context: Context<OpenApiV2_0_X>) => {\n if (context.config.parser.validate_EXPERIMENTAL) {\n const result = validateOpenApiSpec(context.spec, context.logger);\n handleValidatorResult({ context, result });\n }\n\n const shouldFilterSpec = hasFilters(context.config.parser.filters);\n if (shouldFilterSpec) {\n const filters = createFilters(context.config.parser.filters, context.spec, context.logger);\n const { graph } = buildGraph(context.spec, context.logger);\n const { resourceMetadata } = buildResourceMetadata(graph, context.logger);\n const sets = createFilteredDependencies({\n filters,\n logger: context.logger,\n resourceMetadata,\n });\n filterSpec({\n ...sets,\n logger: context.logger,\n preserveOrder: filters.preserveOrder,\n spec: context.spec,\n });\n }\n\n transformOpenApiSpec({ context });\n\n const state: State = {\n ids: new Map(),\n };\n const securitySchemesMap = new Map<string, SecuritySchemeObject>();\n\n for (const name in context.spec.securityDefinitions) {\n const securitySchemeObject = context.spec.securityDefinitions[name]!;\n securitySchemesMap.set(name, securitySchemeObject);\n }\n\n if (context.spec.definitions) {\n for (const name in context.spec.definitions) {\n const $ref = `#/definitions/${name}`;\n const schema = context.spec.definitions[name]!;\n\n parseSchema({\n $ref,\n context,\n schema,\n });\n }\n }\n\n parseServers({ context });\n\n for (const path in context.spec.paths) {\n if (path.startsWith('x-')) continue;\n const pathItem = context.spec.paths[path as PathKeys]!;\n\n const finalPathItem = pathItem.$ref\n ? {\n ...context.resolveRef<PathItemObject>(pathItem.$ref),\n ...pathItem,\n }\n : pathItem;\n\n const commonOperation: OperationObject = {\n consumes: context.spec.consumes,\n produces: context.spec.produces,\n responses: {},\n security: context.spec.security,\n };\n const operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'> = {\n context,\n operation: {\n ...commonOperation,\n parameters: parametersArrayToObject({\n context,\n operation: commonOperation,\n parameters: finalPathItem.parameters,\n }),\n },\n path: path as PathKeys,\n securitySchemesMap,\n state,\n };\n\n if (finalPathItem.delete) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.delete,\n parameters: finalPathItem.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.delete,\n parameters,\n },\n });\n }\n\n if (finalPathItem.get) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.get,\n parameters: finalPathItem.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.get,\n parameters,\n },\n });\n }\n\n if (finalPathItem.head) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.head,\n parameters: finalPathItem.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.head,\n parameters,\n },\n });\n }\n\n if (finalPathItem.options) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.options,\n parameters: finalPathItem.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.options,\n parameters,\n },\n });\n }\n\n if (finalPathItem.patch) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.patch,\n parameters: finalPathItem.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.patch,\n parameters,\n },\n });\n }\n\n if (finalPathItem.post) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.post,\n parameters: finalPathItem.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.post,\n parameters,\n },\n });\n }\n\n if (finalPathItem.put) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.put,\n parameters: finalPathItem.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.put,\n parameters,\n },\n });\n }\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { OpenApiV3_0_X, PathItemObject, PathsObject } from '../types/spec';\n\n/**\n * Replace source spec with filtered version.\n */\nexport const filterSpec = ({\n logger,\n operations,\n parameters,\n preserveOrder,\n requestBodies,\n responses,\n schemas,\n spec,\n}: {\n logger: Logger;\n operations: Set<string>;\n parameters: Set<string>;\n preserveOrder: boolean;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n spec: OpenApiV3_0_X;\n}) => {\n const eventFilterSpec = logger.timeEvent('filter-spec');\n if (spec.components) {\n if (spec.components.parameters) {\n const filtered: typeof spec.components.parameters = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.parameters)) {\n if (parameters.has(addNamespace('parameter', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of parameters) {\n const { name } = removeNamespace(key);\n const source = spec.components.parameters[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.parameters = filtered;\n }\n\n if (spec.components.requestBodies) {\n const filtered: typeof spec.components.requestBodies = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.requestBodies)) {\n if (requestBodies.has(addNamespace('body', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of requestBodies) {\n const { name } = removeNamespace(key);\n const source = spec.components.requestBodies[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.requestBodies = filtered;\n }\n\n if (spec.components.responses) {\n const filtered: typeof spec.components.responses = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.responses)) {\n if (responses.has(addNamespace('response', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of responses) {\n const { name } = removeNamespace(key);\n const source = spec.components.responses[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.responses = filtered;\n }\n\n if (spec.components.schemas) {\n const filtered: typeof spec.components.schemas = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.schemas)) {\n if (schemas.has(addNamespace('schema', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of schemas) {\n const { name } = removeNamespace(key);\n const source = spec.components.schemas[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.schemas = filtered;\n }\n }\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = addNamespace('operation', createOperationKey({ method, path }));\n if (!operations.has(key)) {\n delete pathItem[method];\n }\n }\n\n // remove paths that have no operations left\n if (!Object.keys(pathItem).length) {\n delete spec.paths[path];\n }\n }\n }\n eventFilterSpec.timeEnd();\n};\n","import type { IRMediaType } from '../../../ir/mediaType';\nimport { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType';\nimport type { MediaTypeObject, ReferenceObject, SchemaObject } from '../types/spec';\n\ninterface Content {\n mediaType: string;\n schema: SchemaObject | ReferenceObject | undefined;\n type: IRMediaType | undefined;\n}\n\nexport const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => {\n const { mediaType, schema } = content;\n\n if (schema && '$ref' in schema) {\n return {\n allOf: [{ ...schema }],\n };\n }\n\n if (!schema) {\n if (isMediaTypeFileLike({ mediaType })) {\n return {\n format: 'binary',\n type: 'string',\n };\n }\n return;\n }\n\n if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) {\n return {\n ...schema,\n format: 'binary',\n };\n }\n\n return schema;\n};\n\nexport const mediaTypeObjects = ({\n content,\n}: {\n content: Record<string, MediaTypeObject> | undefined;\n}): ReadonlyArray<Content> => {\n const objects: Array<Content> = [];\n\n for (const mediaType in content) {\n objects.push({\n mediaType,\n schema: content[mediaType]!.schema,\n type: mediaTypeToIrMediaType({ mediaType }),\n });\n }\n\n return objects;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { addItemsToSchema } from '../../../ir/utils';\nimport type {\n SchemaState,\n SchemaType,\n SchemaWithRequired,\n} from '../../../openApi/shared/types/schema';\nimport {\n convertDiscriminatorValue,\n type DiscriminatorPropertyType,\n discriminatorValues,\n} from '../../../openApi/shared/utils/discriminator';\nimport { isTopLevelComponent, refToName } from '../../../utils/ref';\nimport type { ReferenceObject, SchemaObject } from '../types/spec';\n\nexport const getSchemaType = ({\n schema,\n}: {\n schema: SchemaObject;\n}): SchemaType<SchemaObject> | undefined => {\n if (schema.type) {\n return schema.type;\n }\n\n // infer object based on the presence of properties\n if (schema.properties) {\n return 'object';\n }\n\n return;\n};\n\n/**\n * Finds the type of a discriminator property by looking it up in the provided schemas.\n * Searches through properties and allOf chains to find the property definition.\n */\nconst findDiscriminatorPropertyType = ({\n context,\n propertyName,\n schemas,\n}: {\n context: Context;\n propertyName: string;\n schemas: ReadonlyArray<SchemaObject | ReferenceObject>;\n}): DiscriminatorPropertyType => {\n for (const schema of schemas) {\n const resolved = '$ref' in schema ? context.resolveRef<SchemaObject>(schema.$ref) : schema;\n\n // Check direct properties\n const property = resolved.properties?.[propertyName];\n if (property) {\n const resolvedProperty =\n '$ref' in property ? context.resolveRef<SchemaObject>(property.$ref) : property;\n if (\n resolvedProperty.type === 'boolean' ||\n resolvedProperty.type === 'integer' ||\n resolvedProperty.type === 'number'\n ) {\n return resolvedProperty.type;\n }\n }\n\n // Check allOf chains\n if (resolved.allOf) {\n const foundType = findDiscriminatorPropertyType({\n context,\n propertyName,\n schemas: resolved.allOf,\n });\n if (foundType !== 'string') {\n return foundType;\n }\n }\n }\n\n return 'string';\n};\n\n/**\n * Recursively finds discriminators in a schema, including nested allOf compositions.\n * This is needed when a schema extends another schema via allOf, and that parent\n * schema is itself an allOf composition with discriminators in inline schemas.\n */\nconst findDiscriminatorsInSchema = ({\n context,\n discriminators = [],\n schema,\n}: {\n context: Context;\n discriminators?: Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n }>;\n schema: SchemaObject;\n}): Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n}> => {\n // Check if this schema has a discriminator\n if (schema.discriminator) {\n discriminators.push({\n discriminator: schema.discriminator,\n oneOf: schema.oneOf,\n });\n }\n\n // If this schema is an allOf composition, recursively search in its components\n if (schema.allOf) {\n for (const compositionSchema of schema.allOf) {\n let resolvedSchema: SchemaObject;\n if ('$ref' in compositionSchema) {\n resolvedSchema = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n } else {\n resolvedSchema = compositionSchema;\n }\n\n findDiscriminatorsInSchema({\n context,\n discriminators,\n schema: resolvedSchema,\n });\n }\n }\n\n return discriminators;\n};\n\n/**\n * Gets the discriminator value for a schema.\n * Returns only the schema's own discriminator value, not child values.\n */\nconst getAllDiscriminatorValues = ({\n discriminator,\n schemaRef,\n}: {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n schemaRef: string;\n}): Array<string> => {\n const values: Array<string> = [];\n\n // Check each entry in the discriminator mapping\n for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) {\n if (mappedSchemaRef === schemaRef) {\n // This is the current schema's own value\n values.push(value);\n }\n }\n\n return values;\n};\n\nconst parseSchemaJsDoc = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.deprecated !== undefined) {\n irSchema.deprecated = schema.deprecated;\n }\n\n if (schema.example) {\n irSchema.example = schema.example;\n }\n\n if (schema.description) {\n irSchema.description = schema.description;\n }\n\n if (schema.title) {\n irSchema.title = schema.title;\n }\n};\n\nconst parseSchemaMeta = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.default !== undefined) {\n irSchema.default = schema.default;\n }\n\n if (schema.exclusiveMaximum) {\n if (schema.maximum !== undefined) {\n irSchema.exclusiveMaximum = schema.maximum;\n }\n } else if (schema.maximum !== undefined) {\n irSchema.maximum = schema.maximum;\n }\n\n if (schema.exclusiveMinimum) {\n if (schema.minimum !== undefined) {\n irSchema.exclusiveMinimum = schema.minimum;\n }\n } else if (schema.minimum !== undefined) {\n irSchema.minimum = schema.minimum;\n }\n\n if (schema.format) {\n irSchema.format = schema.format;\n }\n\n if (schema.maxItems !== undefined) {\n irSchema.maxItems = schema.maxItems;\n }\n\n if (schema.maxLength !== undefined) {\n irSchema.maxLength = schema.maxLength;\n }\n\n if (schema.minItems !== undefined) {\n irSchema.minItems = schema.minItems;\n }\n\n if (schema.minLength !== undefined) {\n irSchema.minLength = schema.minLength;\n }\n\n if (schema.pattern) {\n irSchema.pattern = schema.pattern;\n }\n\n if (schema.readOnly) {\n irSchema.accessScope = 'read';\n } else if (schema.writeOnly) {\n irSchema.accessScope = 'write';\n }\n};\n\nconst parseArray = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (schema.maxItems && schema.maxItems === schema.minItems) {\n irSchema.type = 'tuple';\n } else {\n irSchema.type = 'array';\n }\n\n let schemaItems: Array<IR.SchemaObject> = [];\n\n if (schema.items) {\n const irItemsSchema = schemaToIrSchema({\n context,\n schema: schema.items,\n state,\n });\n\n if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {\n schemaItems = Array(schema.maxItems).fill(irItemsSchema);\n } else {\n if ('$ref' in schema.items) {\n schemaItems.push(irItemsSchema);\n } else {\n const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf;\n if (ofArray && ofArray.length > 1 && !schema.items.nullable) {\n // bring composition up to avoid incorrectly nested arrays\n irSchema = {\n ...irSchema,\n ...irItemsSchema,\n };\n } else {\n schemaItems.push(irItemsSchema);\n }\n }\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseBoolean = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'boolean';\n\n return irSchema;\n};\n\nconst parseNumber = ({\n irSchema = {},\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = schema.type;\n\n return irSchema;\n};\n\nconst parseObject = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'object';\n\n const schemaProperties: Record<string, IR.SchemaObject> = {};\n\n for (const name in schema.properties) {\n const property = schema.properties[name]!;\n if (typeof property === 'boolean') {\n // TODO: parser - handle boolean properties\n } else {\n schemaProperties[name] = schemaToIrSchema({\n context,\n schema: property,\n state,\n });\n }\n }\n\n if (Object.keys(schemaProperties).length) {\n irSchema.properties = schemaProperties;\n }\n\n if (schema.additionalProperties === undefined) {\n if (!irSchema.properties) {\n irSchema.additionalProperties = {\n type: 'unknown',\n };\n }\n } else if (typeof schema.additionalProperties === 'boolean') {\n // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf\n // This would override inherited properties from other schemas in the composition\n const isEmptyObjectInAllOf =\n state.inAllOf &&\n schema.additionalProperties === false &&\n (!schema.properties || !Object.keys(schema.properties).length);\n\n if (!isEmptyObjectInAllOf) {\n irSchema.additionalProperties = {\n type: schema.additionalProperties ? 'unknown' : 'never',\n };\n }\n } else {\n const irAdditionalPropertiesSchema = schemaToIrSchema({\n context,\n schema: schema.additionalProperties,\n state,\n });\n irSchema.additionalProperties = irAdditionalPropertiesSchema;\n }\n\n if (schema.required) {\n irSchema.required = schema.required;\n }\n\n return irSchema;\n};\n\nconst parseString = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'string';\n\n return irSchema;\n};\n\nexport const parseExtensions = ({ source, target }: { source: object; target: object }) => {\n for (const key in source) {\n if (key.startsWith('x-')) {\n (target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];\n }\n }\n};\n\nconst initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n\n parseSchemaJsDoc({\n irSchema,\n schema,\n });\n\n parseExtensions({\n source: schema,\n target: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseAllOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'allOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.allOf;\n\n // Collect discriminator information to add after all compositions are processed\n type DiscriminatorInfo = {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n isRequired: boolean;\n values: ReadonlyArray<string>;\n };\n const discriminatorsToAdd: Array<DiscriminatorInfo> = [];\n const addedDiscriminators = new Set<string>();\n\n for (const compositionSchema of compositionSchemas) {\n const originalInAllOf = state.inAllOf;\n // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components\n if (!('$ref' in compositionSchema)) {\n state.inAllOf = true;\n }\n const irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n state.inAllOf = originalInAllOf;\n if (state.inAllOf === undefined) {\n delete state.inAllOf;\n }\n\n if (schema.required) {\n if (irCompositionSchema.required) {\n irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];\n } else {\n irCompositionSchema.required = schema.required;\n }\n }\n\n schemaItems.push(irCompositionSchema);\n\n if ('$ref' in compositionSchema) {\n const ref = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n // `$ref` should be passed from the root `parseSchema()` call\n if (state.$ref) {\n // Find all discriminators in the referenced schema, including nested allOf compositions\n const discriminators = findDiscriminatorsInSchema({\n context,\n schema: ref,\n });\n\n // Process each discriminator found\n for (const { discriminator, oneOf } of discriminators) {\n // Skip if we've already collected this discriminator property\n if (addedDiscriminators.has(discriminator.propertyName)) {\n continue;\n }\n\n const values = discriminatorValues(\n state.$ref,\n discriminator.mapping,\n // If the ref has oneOf, we only use the schema name as the value\n // only if current schema is part of the oneOf. Else it is extending\n // the ref schema\n oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined,\n );\n\n if (values.length > 0) {\n // Check if the discriminator property is required in any of the discriminator schemas\n const isRequired = discriminators.some(\n (d) =>\n d.discriminator.propertyName === discriminator.propertyName &&\n // Check in the ref's required array or in the allOf components\n (ref.required?.includes(d.discriminator.propertyName) ||\n (ref.allOf &&\n ref.allOf.some((item) => {\n const resolvedItem =\n '$ref' in item ? context.resolveRef<SchemaObject>(item.$ref) : item;\n return resolvedItem.required?.includes(d.discriminator.propertyName);\n }))),\n );\n\n discriminatorsToAdd.push({\n discriminator,\n isRequired,\n values,\n });\n addedDiscriminators.add(discriminator.propertyName);\n }\n }\n }\n }\n }\n\n // Now add discriminators after all compositions have been processed\n for (const { discriminator, isRequired, values } of discriminatorsToAdd) {\n // Get all discriminator values including children for union types\n const allValues = getAllDiscriminatorValues({\n discriminator,\n schemaRef: state.$ref!,\n });\n\n // Use allValues if we found children, otherwise use the original values\n const finalValues = allValues.length > 0 ? allValues : values;\n\n // Detect the actual type of the discriminator property\n const propertyType = findDiscriminatorPropertyType({\n context,\n propertyName: discriminator.propertyName,\n schemas: compositionSchemas,\n });\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = finalValues.map((value) =>\n convertDiscriminatorValue(value, propertyType),\n );\n\n const discriminatorProperty: IR.SchemaObject =\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!;\n\n // Check if any $ref schemas in schemaItems have this discriminator property\n // If yes, mark them to omit it to avoid conflicts\n for (const item of schemaItems) {\n if (item.$ref || item.symbolRef) {\n // Check if the referenced schema has this property\n const hasProperty = (() => {\n if (!item.$ref) return false;\n try {\n const refSchema = context.resolveRef<SchemaObject>(item.$ref);\n // Check if the discriminator property exists in the ref schema\n return (\n refSchema.properties?.[discriminator.propertyName] !== undefined ||\n (refSchema.allOf &&\n refSchema.allOf.some((allOfItem) => {\n const resolved =\n '$ref' in allOfItem\n ? context.resolveRef<SchemaObject>(allOfItem.$ref)\n : allOfItem;\n return resolved.properties?.[discriminator.propertyName] !== undefined;\n }))\n );\n } catch {\n return false;\n }\n })();\n\n if (hasProperty) {\n // Mark this ref to omit the discriminator property\n if (!item.omit) {\n item.omit = [discriminator.propertyName];\n } else if (!item.omit.includes(discriminator.propertyName)) {\n item.omit = [...item.omit, discriminator.propertyName];\n }\n }\n }\n }\n\n // Find the inline schema (non-$ref) to merge the discriminator property into\n // The inline schema should be the last non-$ref item in schemaItems\n let inlineSchema: IR.SchemaObject | undefined;\n for (let i = schemaItems.length - 1; i >= 0; i--) {\n const item = schemaItems[i]!;\n // Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema\n if (item.type === 'object' || item.properties) {\n inlineSchema = item;\n break;\n }\n }\n\n // If we found an inline schema, add the discriminator property to it\n if (inlineSchema) {\n if (!inlineSchema.properties) {\n inlineSchema.properties = {};\n }\n inlineSchema.properties[discriminator.propertyName] = discriminatorProperty;\n\n if (isRequired) {\n if (!inlineSchema.required) {\n inlineSchema.required = [];\n }\n if (!inlineSchema.required.includes(discriminator.propertyName)) {\n inlineSchema.required = [...inlineSchema.required, discriminator.propertyName];\n }\n }\n } else {\n // Fallback: create a separate discriminator schema if no inline schema found\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [discriminator.propertyName]: discriminatorProperty,\n },\n type: 'object',\n };\n\n if (isRequired) {\n irDiscriminatorSchema.required = [discriminator.propertyName];\n }\n schemaItems.push(irDiscriminatorSchema);\n }\n }\n\n if (schemaType === 'object') {\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n for (const requiredProperty of irObjectSchema.required ?? []) {\n if (!irObjectSchema.properties[requiredProperty]) {\n for (const compositionSchema of compositionSchemas) {\n // TODO: parser - this could be probably resolved more accurately\n const finalCompositionSchema =\n '$ref' in compositionSchema\n ? context.resolveRef<SchemaObject>(compositionSchema.$ref)\n : compositionSchema;\n\n if (getSchemaType({ schema: finalCompositionSchema }) === 'object') {\n const irCompositionSchema = parseOneType({\n context,\n schema: {\n ...finalCompositionSchema,\n type: 'object',\n },\n state,\n });\n\n if (irCompositionSchema.properties?.[requiredProperty]) {\n irObjectSchema.properties[requiredProperty] =\n irCompositionSchema.properties[requiredProperty];\n break;\n }\n }\n }\n }\n }\n schemaItems.push(irObjectSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n logicalOperator: 'and',\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schema.nullable) {\n // nest composition to avoid producing an intersection with null\n const nestedItems: Array<IR.SchemaObject> = [\n {\n type: 'null',\n },\n ];\n\n if (schemaItems.length) {\n nestedItems.unshift(irSchema);\n }\n\n irSchema = {\n items: nestedItems,\n logicalOperator: 'or',\n };\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original deprecated\n if (nestedItems[0]!.deprecated) {\n irSchema.deprecated = nestedItems[0]!.deprecated;\n }\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original description\n if (nestedItems[0]!.description) {\n irSchema.description = nestedItems[0]!.description;\n }\n }\n\n return irSchema;\n};\n\nconst parseAnyOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'anyOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.anyOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n schemaItems.push(irCompositionSchema);\n }\n\n if (schema.nullable) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaType === 'object') {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseEnum = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'enum'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n irSchema.type = 'enum';\n\n const schemaItems: Array<IR.SchemaObject> = [];\n\n for (const [index, enumValue] of schema.enum.entries()) {\n const typeOfEnumValue = typeof enumValue;\n let enumType: SchemaType<SchemaObject> | 'null' | undefined;\n\n if (\n typeOfEnumValue === 'string' ||\n typeOfEnumValue === 'number' ||\n typeOfEnumValue === 'boolean'\n ) {\n enumType = typeOfEnumValue;\n } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {\n enumType = 'array';\n } else if (enumValue === null) {\n // nullable must be true\n if (schema.nullable) {\n enumType = 'null';\n }\n } else {\n console.warn(\n '๐Ÿšจ',\n `unhandled \"${typeOfEnumValue}\" typeof value \"${enumValue}\" for enum`,\n schema.enum,\n );\n }\n\n if (!enumType) {\n continue;\n }\n\n const irTypeSchema = parseOneType({\n context,\n schema: {\n description: schema['x-enum-descriptions']?.[index],\n title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],\n // cast enum to string temporarily\n type: enumType === 'null' ? 'string' : enumType,\n },\n state,\n });\n\n irTypeSchema.const = enumValue;\n\n // cast enum back\n if (enumType === 'null') {\n irTypeSchema.type = enumType;\n }\n\n if (irTypeSchema.type === 'array') {\n irTypeSchema.type = 'tuple';\n }\n\n schemaItems.push(irTypeSchema);\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseOneOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'oneOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n let schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.oneOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n required: [schema.discriminator.propertyName],\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n // since we know oneOf will be using \"or\" logical operator, if the parsed\n // composition schema also has an \"or\" operator, we can bring it up\n // to avoid unnecessary brackets\n if (\n irCompositionSchema.logicalOperator === 'or' &&\n irCompositionSchema.type !== 'array' &&\n irCompositionSchema.items\n ) {\n schemaItems = schemaItems.concat(irCompositionSchema.items);\n } else {\n schemaItems.push(irCompositionSchema);\n }\n }\n\n if (schema.nullable) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaType === 'object') {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseRef = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: ReferenceObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/components/schemas/Foo/properties/bar)\n // to avoid generating orphaned named types or referencing unregistered symbols\n const isComponentsRef = isTopLevelComponent(schema.$ref);\n if (!isComponentsRef) {\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n const irSchema = schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n return irSchema;\n }\n // Fallback to preserving the ref if circular\n }\n\n const irSchema: IR.SchemaObject = {};\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n irSchema.$ref = decodeURI(schema.$ref);\n\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n }\n\n return irSchema;\n};\n\nconst parseNullableType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n const typeIrSchema: IR.SchemaObject = {};\n\n parseSchemaMeta({ irSchema: typeIrSchema, schema });\n\n if (typeIrSchema.default === null) {\n // clear to avoid duplicate default inside the non-null schema.\n // this would produce incorrect validator output\n delete typeIrSchema.default;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [\n parseOneType({\n context,\n irSchema: typeIrSchema,\n schema,\n state,\n }),\n {\n type: 'null',\n },\n ];\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseType = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n\n const type = getSchemaType({ schema });\n\n if (!type) {\n return irSchema;\n }\n\n if (!schema.nullable) {\n return parseOneType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n }\n\n return parseNullableType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n};\n\nconst parseOneType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n }\n\n switch (schema.type) {\n case 'array':\n return parseArray({\n context,\n irSchema,\n schema,\n state,\n });\n case 'boolean':\n return parseBoolean({\n context,\n irSchema,\n schema,\n state,\n });\n case 'integer':\n case 'number':\n return parseNumber({\n context,\n irSchema,\n schema,\n state,\n });\n case 'object':\n return parseObject({\n context,\n irSchema,\n schema,\n state,\n });\n case 'string':\n return parseString({\n context,\n irSchema,\n schema,\n state,\n });\n default:\n // gracefully handle invalid type\n return parseUnknown({\n context,\n irSchema,\n schema,\n });\n }\n};\n\nconst parseUnknown = ({\n irSchema,\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n irSchema.type = 'unknown';\n\n parseSchemaMeta({ irSchema, schema });\n\n return irSchema;\n};\n\nexport const schemaToIrSchema = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaObject | ReferenceObject;\n state: SchemaState | undefined;\n}): IR.SchemaObject => {\n if (!state) {\n state = {\n circularReferenceTracker: new Set(),\n };\n }\n\n if (state.$ref) {\n state.circularReferenceTracker.add(state.$ref);\n }\n\n if ('$ref' in schema) {\n return parseRef({\n context,\n schema,\n state,\n });\n }\n\n if (schema.enum) {\n return parseEnum({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'enum'>,\n state,\n });\n }\n\n if (schema.allOf) {\n return parseAllOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'allOf'>,\n state,\n });\n }\n\n if (schema.anyOf) {\n return parseAnyOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'anyOf'>,\n state,\n });\n }\n\n if (schema.oneOf) {\n return parseOneOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'oneOf'>,\n state,\n });\n }\n\n // infer object based on the presence of properties\n if (schema.type || schema.properties) {\n return parseType({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n return parseUnknown({ context, schema });\n};\n\nexport const parseSchema = ({\n $ref,\n context,\n schema,\n}: {\n $ref: string;\n context: Context;\n schema: SchemaObject | ReferenceObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.schemas) {\n context.ir.components.schemas = {};\n }\n\n context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({\n context,\n schema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { getPaginationKeywordsRegExp } from '../../../ir/pagination';\nimport type { SchemaType } from '../../../openApi/shared/types/schema';\nimport type { ParameterObject, ReferenceObject, RequestBodyObject } from '../types/spec';\nimport type { SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { getSchemaType } from './schema';\n\nconst isPaginationType = (schemaType: SchemaType<SchemaObject> | undefined): boolean =>\n schemaType === 'boolean' ||\n schemaType === 'integer' ||\n schemaType === 'number' ||\n schemaType === 'string';\n\n// We handle only simple values for now, up to 1 nested field\nexport const paginationField = ({\n context,\n name,\n schema,\n}: {\n context: Context;\n name: string;\n schema: SchemaObject | ReferenceObject;\n}): boolean | string => {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n if (paginationRegExp.test(name)) {\n return true;\n }\n\n if ('$ref' in schema) {\n const ref = context.resolveRef<ParameterObject | RequestBodyObject | SchemaObject>(schema.$ref);\n\n if ('content' in ref || 'in' in ref) {\n let refSchema: SchemaObject | ReferenceObject | undefined;\n\n if ('in' in ref) {\n refSchema = ref.schema;\n }\n\n if (!refSchema) {\n // parameter or body\n const contents = mediaTypeObjects({ content: ref.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content?.schema) {\n refSchema = content.schema;\n }\n }\n\n if (!refSchema) {\n return false;\n }\n\n return paginationField({\n context,\n name,\n schema: refSchema,\n });\n }\n\n return paginationField({\n context,\n name,\n schema: ref,\n });\n }\n\n for (const name in schema.properties) {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n\n if (paginationRegExp.test(name)) {\n const property = schema.properties[name]!;\n\n if (typeof property !== 'boolean' && !('$ref' in property)) {\n const schemaType = getSchemaType({ schema: property });\n // TODO: resolve deeper references\n\n if (isPaginationType(schemaType)) {\n return name;\n }\n }\n }\n }\n\n for (const allOf of schema.allOf ?? []) {\n const pagination = paginationField({\n context,\n name,\n schema: allOf,\n });\n if (pagination) {\n return pagination;\n }\n }\n\n return false;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type { State } from '../../../openApi/shared/types/state';\nimport { operationToId } from '../../../openApi/shared/utils/operation';\nimport type {\n OperationObject,\n PathItemObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { contentToSchema, mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ninterface Operation\n extends Omit<OperationObject, 'parameters'>, Pick<IR.OperationObject, 'parameters'> {}\n\nconst parseOperationJsDoc = ({\n irOperation,\n operation,\n}: {\n irOperation: IR.OperationObject;\n operation: Operation;\n}) => {\n if (operation.deprecated !== undefined) {\n irOperation.deprecated = operation.deprecated;\n }\n\n if (operation.description) {\n irOperation.description = operation.description;\n }\n\n if (operation.summary) {\n irOperation.summary = operation.summary;\n }\n\n if (operation.tags?.length) {\n irOperation.tags = operation.tags;\n }\n};\n\nconst initIrOperation = ({\n context,\n method,\n operation,\n path,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n state: State;\n}): IR.OperationObject => {\n const irOperation: IR.OperationObject = {\n id: operationToId({\n context,\n id: operation.operationId,\n method,\n path,\n state,\n }),\n method,\n path,\n };\n\n if (operation.operationId) {\n irOperation.operationId = operation.operationId;\n }\n\n parseOperationJsDoc({\n irOperation,\n operation,\n });\n\n parseExtensions({\n source: operation,\n target: irOperation,\n });\n\n return irOperation;\n};\n\nconst operationToIrOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}): IR.OperationObject => {\n const irOperation = initIrOperation({\n context,\n method,\n operation,\n path,\n state,\n });\n\n if (operation.parameters) {\n irOperation.parameters = operation.parameters;\n }\n\n if (operation.requestBody) {\n const requestBody =\n '$ref' in operation.requestBody\n ? context.resolveRef<RequestBodyObject>(operation.requestBody.$ref)\n : operation.requestBody;\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n const pagination = paginationField({\n context,\n name: '',\n schema:\n content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n });\n\n irOperation.body = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema:\n '$ref' in operation.requestBody\n ? {\n allOf: [{ ...operation.requestBody }],\n description: requestBody.description,\n }\n : content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n state: undefined,\n }),\n };\n\n if (pagination) {\n irOperation.body.pagination = pagination;\n }\n\n if (requestBody.required) {\n irOperation.body.required = requestBody.required;\n }\n\n if (content.type) {\n irOperation.body.type = content.type;\n }\n }\n }\n\n for (const name in operation.responses) {\n if (name.startsWith('x-')) continue;\n\n if (!irOperation.responses) {\n irOperation.responses = {};\n }\n\n const response = operation.responses[name]! as ResponseObject | ReferenceObject;\n const responseObject =\n '$ref' in response ? context.resolveRef<ResponseObject>(response.$ref) : response;\n const contents = mediaTypeObjects({ content: responseObject.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n irOperation.responses[name] = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: responseObject.description,\n ...contentToSchema({ content }),\n },\n state: undefined,\n }),\n };\n } else {\n irOperation.responses[name] = {\n schema: {\n description: responseObject.description,\n // TODO: parser - cover all statues with empty response bodies\n // 1xx, 204, 205, 304\n type: name === '204' ? 'void' : 'unknown',\n },\n };\n }\n }\n\n if (operation.security) {\n const securitySchemeObjects: Map<string, IR.SecurityObject> = new Map();\n\n for (const securityRequirementObject of operation.security) {\n for (const name in securityRequirementObject) {\n const securitySchemeObject = securitySchemesMap.get(name);\n\n if (!securitySchemeObject) {\n continue;\n }\n\n securitySchemeObjects.set(name, securitySchemeObject);\n }\n }\n\n if (securitySchemeObjects.size) {\n irOperation.security = Array.from(securitySchemeObjects.values());\n }\n }\n\n // TODO: parser - handle servers\n // qux: operation.servers\n\n return irOperation;\n};\n\nexport const parsePathOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: {\n context: Context;\n method: Extract<\n keyof PathItemObject,\n 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'\n >;\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.paths) {\n context.ir.paths = {};\n }\n\n if (!context.ir.paths[path]) {\n context.ir.paths[path] = {};\n }\n\n if (operation.servers) {\n context.ir.servers = [...(context.ir.servers ?? []), ...operation.servers];\n }\n\n context.ir.paths[path][method] = operationToIrOperation({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { ParameterObject, ReferenceObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\n/**\n * Returns default parameter `allowReserved` based on value of `in`.\n */\nconst defaultAllowReserved = (_in: ParameterObject['in']): boolean | undefined => {\n switch (_in) {\n // this keyword only applies to parameters with an `in` value of `query`\n case 'query':\n return false;\n default:\n return;\n }\n};\n\n/**\n * Returns default parameter `explode` based on value of `style`.\n */\nconst defaultExplode = (style: Required<ParameterObject>['style']): boolean => {\n switch (style) {\n // default value for `deepObject` is `false`, but that behavior is undefined\n // so we use `true` to make this work with the `client-fetch` package\n case 'deepObject':\n case 'form':\n return true;\n default:\n return false;\n }\n};\n\n/**\n * Returns default parameter `style` based on value of `in`.\n */\nconst defaultStyle = (_in: ParameterObject['in']): Required<IR.ParameterObject>['style'] => {\n switch (_in) {\n case 'header':\n case 'path':\n return 'simple';\n case 'cookie':\n case 'query':\n return 'form';\n }\n};\n\nexport const parametersArrayToObject = ({\n context,\n parameters,\n}: {\n context: Context;\n parameters?: ReadonlyArray<ParameterObject | ReferenceObject>;\n}): IR.ParametersObject | undefined => {\n if (!parameters || !Object.keys(parameters).length) {\n return;\n }\n\n const parametersObject: IR.ParametersObject = {};\n\n for (const parameterOrReference of parameters) {\n const parameter =\n '$ref' in parameterOrReference\n ? context.dereference<ParameterObject>(parameterOrReference)\n : parameterOrReference;\n\n if (!parametersObject[parameter.in]) {\n parametersObject[parameter.in] = {};\n }\n\n // lowercase keys for case insensitive access\n parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({\n $ref: `#/todo/real/path/to/parameter/${parameter.name}`,\n context,\n parameter,\n });\n }\n\n return parametersObject;\n};\n\nconst parameterToIrParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}): IR.ParameterObject => {\n // TODO: parser - fix\n let schema = parameter.schema;\n\n if (!schema) {\n const contents = mediaTypeObjects({ content: parameter.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content) {\n schema = content.schema;\n }\n }\n\n const finalSchema: SchemaObject =\n schema && '$ref' in schema\n ? {\n allOf: [{ ...schema }],\n deprecated: parameter.deprecated,\n description: parameter.description,\n }\n : {\n deprecated: parameter.deprecated,\n description: parameter.description,\n ...schema,\n };\n\n const pagination = paginationField({\n context,\n name: parameter.name,\n schema: finalSchema,\n });\n\n const style = parameter.style || defaultStyle(parameter.in);\n const explode = parameter.explode !== undefined ? parameter.explode : defaultExplode(style);\n const allowReserved =\n parameter.allowReserved !== undefined\n ? parameter.allowReserved\n : defaultAllowReserved(parameter.in);\n\n const irParameter: IR.ParameterObject = {\n allowReserved,\n explode,\n location: parameter.in,\n name: parameter.name,\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n style,\n };\n\n if (parameter.deprecated) {\n irParameter.deprecated = parameter.deprecated;\n }\n\n if (parameter.description) {\n irParameter.description = parameter.description;\n }\n\n if (pagination) {\n irParameter.pagination = pagination;\n }\n\n if (parameter.required) {\n irParameter.required = parameter.required;\n }\n\n parseExtensions({\n source: parameter,\n target: irParameter,\n });\n\n return irParameter;\n};\n\nexport const parseParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.parameters) {\n context.ir.components.parameters = {};\n }\n\n context.ir.components.parameters[refToName($ref)] = parameterToIrParameter({\n $ref,\n context,\n parameter,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { RequestBodyObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { schemaToIrSchema } from './schema';\n\nconst requestBodyToIrRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}): IR.RequestBodyObject => {\n // TODO: parser - fix\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n const schema = content ? content.schema : undefined;\n\n const finalSchema: SchemaObject = {\n description: requestBody.description,\n ...schema,\n };\n\n const irRequestBody: IR.RequestBodyObject = {\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n };\n\n if (requestBody.description) {\n irRequestBody.description = requestBody.description;\n }\n\n if (requestBody.required) {\n irRequestBody.required = requestBody.required;\n }\n\n return irRequestBody;\n};\n\nexport const parseRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.requestBodies) {\n context.ir.components.requestBodies = {};\n }\n\n context.ir.components.requestBodies[refToName($ref)] = requestBodyToIrRequestBody({\n $ref,\n context,\n requestBody,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { parseUrl } from '../../../utils/url';\n\nexport function parseServers({ context }: { context: Context }): void {\n if (context.spec.servers) {\n context.ir.servers = context.spec.servers;\n return;\n }\n\n for (const input of context.config.input) {\n if (typeof input.path === 'string') {\n const url = parseUrl(input.path);\n context.ir.servers = [\n {\n url: `${url.protocol ? `${url.protocol}://` : ''}${url.host}${url.port ? `:${url.port}` : ''}`,\n },\n ];\n }\n }\n\n if (!context.ir.servers) {\n context.ir.servers = [\n {\n url: '/',\n },\n ];\n }\n}\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type { OpenApiV3_0_X, PathItemObject, PathsObject } from '../types/spec';\n\nexport const validateOpenApiSpec = (spec: OpenApiV3_0_X, logger: Logger): ValidatorResult => {\n const eventValidate = logger.timeEvent('validate');\n const issues: Array<ValidatorIssue> = [];\n const operationIds = new Map();\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const operationKey = createOperationKey({ method, path });\n\n if (operation.operationId) {\n if (!operationIds.has(operation.operationId)) {\n operationIds.set(operation.operationId, operationKey);\n } else {\n issues.push({\n code: 'duplicate_key',\n context: {\n key: 'operationId',\n value: operation.operationId,\n },\n message: 'Duplicate `operationId` found. Each `operationId` must be unique.',\n path: ['paths', path, method, 'operationId'],\n severity: 'error',\n });\n }\n }\n }\n }\n }\n\n if (spec.servers) {\n if (typeof spec.servers !== 'object' || !Array.isArray(spec.servers)) {\n issues.push({\n code: 'invalid_type',\n message: '`servers` must be an array.',\n path: [],\n severity: 'error',\n });\n }\n\n for (let index = 0; index < spec.servers.length; index++) {\n const server = spec.servers[index];\n if (!server || typeof server !== 'object') {\n issues.push({\n code: 'invalid_type',\n context: {\n actual: typeof server,\n expected: 'object',\n },\n message: 'Each entry in `servers` must be an object.',\n path: ['servers', index],\n severity: 'error',\n });\n } else {\n if (!server.url) {\n issues.push({\n code: 'missing_required_field',\n context: {\n field: 'url',\n },\n message: 'Missing required field `url` in server object.',\n path: ['servers', index],\n severity: 'error',\n });\n }\n }\n }\n }\n\n eventValidate.timeEnd();\n return {\n issues,\n valid: !issues.some((issue) => issue.severity === 'error'),\n };\n};\n","import type { Context } from '../../../ir/context';\nimport { buildResourceMetadata } from '../../../openApi/shared/graph/meta';\nimport { transformOpenApiSpec } from '../../../openApi/shared/transforms';\nimport type { State } from '../../../openApi/shared/types/state';\nimport {\n createFilteredDependencies,\n createFilters,\n hasFilters,\n} from '../../../openApi/shared/utils/filter';\nimport { buildGraph } from '../../../openApi/shared/utils/graph';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport { handleValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type {\n OpenApiV3_0_X,\n ParameterObject,\n PathItemObject,\n PathsObject,\n RequestBodyObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { filterSpec } from './filter';\nimport { parsePathOperation } from './operation';\nimport { parametersArrayToObject, parseParameter } from './parameter';\nimport { parseRequestBody } from './requestBody';\nimport { parseSchema } from './schema';\nimport { parseServers } from './server';\nimport { validateOpenApiSpec } from './validate';\n\nexport const parseV3_0_X = (context: Context<OpenApiV3_0_X>) => {\n if (context.config.parser.validate_EXPERIMENTAL) {\n const result = validateOpenApiSpec(context.spec, context.logger);\n handleValidatorResult({ context, result });\n }\n\n const shouldFilterSpec = hasFilters(context.config.parser.filters);\n if (shouldFilterSpec) {\n const filters = createFilters(context.config.parser.filters, context.spec, context.logger);\n const { graph } = buildGraph(context.spec, context.logger);\n const { resourceMetadata } = buildResourceMetadata(graph, context.logger);\n const sets = createFilteredDependencies({\n filters,\n logger: context.logger,\n resourceMetadata,\n });\n filterSpec({\n ...sets,\n logger: context.logger,\n preserveOrder: filters.preserveOrder,\n spec: context.spec,\n });\n }\n\n transformOpenApiSpec({ context });\n\n const state: State = {\n ids: new Map(),\n };\n const securitySchemesMap = new Map<string, SecuritySchemeObject>();\n\n // TODO: parser - handle more component types, old parser handles only parameters and schemas\n if (context.spec.components) {\n for (const name in context.spec.components.securitySchemes) {\n const securityOrReference = context.spec.components.securitySchemes[name]!;\n const securitySchemeObject =\n '$ref' in securityOrReference\n ? context.resolveRef<SecuritySchemeObject>(securityOrReference.$ref)\n : securityOrReference;\n securitySchemesMap.set(name, securitySchemeObject);\n }\n\n for (const name in context.spec.components.parameters) {\n const $ref = `#/components/parameters/${name}`;\n const parameterOrReference = context.spec.components.parameters[name]!;\n const parameter =\n '$ref' in parameterOrReference\n ? context.resolveRef<ParameterObject>(parameterOrReference.$ref)\n : parameterOrReference;\n\n parseParameter({\n $ref,\n context,\n parameter,\n });\n }\n\n for (const name in context.spec.components.requestBodies) {\n const $ref = `#/components/requestBodies/${name}`;\n const requestBodyOrReference = context.spec.components.requestBodies[name]!;\n const requestBody =\n '$ref' in requestBodyOrReference\n ? context.resolveRef<RequestBodyObject>(requestBodyOrReference.$ref)\n : requestBodyOrReference;\n\n parseRequestBody({\n $ref,\n context,\n requestBody,\n });\n }\n\n for (const name in context.spec.components.schemas) {\n const $ref = `#/components/schemas/${name}`;\n const schema = context.spec.components.schemas[name]!;\n\n parseSchema({\n $ref,\n context,\n schema,\n });\n }\n }\n\n parseServers({ context });\n\n for (const path in context.spec.paths) {\n if (path.startsWith('x-')) continue;\n const pathItem = context.spec.paths[path as keyof PathsObject]! as PathItemObject;\n\n const finalPathItem = pathItem.$ref\n ? {\n ...context.resolveRef<PathItemObject>(pathItem.$ref),\n ...pathItem,\n }\n : pathItem;\n\n const operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method' | 'operation'> & {\n operation: Omit<Parameters<typeof parsePathOperation>[0]['operation'], 'responses'>;\n } = {\n context,\n operation: {\n description: finalPathItem.description,\n parameters: parametersArrayToObject({\n context,\n parameters: finalPathItem.parameters,\n }),\n security: context.spec.security,\n servers: finalPathItem.servers,\n summary: finalPathItem.summary,\n },\n path: path as `/${string}`,\n securitySchemesMap,\n state,\n };\n\n if (finalPathItem.delete) {\n parsePathOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.delete,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.get) {\n parsePathOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.get,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.head) {\n parsePathOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.head,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.options) {\n parsePathOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.options,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.patch) {\n parsePathOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.patch,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.post) {\n parsePathOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.post,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.put) {\n parsePathOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.put,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.trace) {\n parsePathOperation({\n ...operationArgs,\n method: 'trace',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.trace,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.trace.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { OpenApiV3_1_X, PathItemObject, PathsObject } from '../types/spec';\n\n/**\n * Replace source spec with filtered version.\n */\nexport const filterSpec = ({\n logger,\n operations,\n parameters,\n preserveOrder,\n requestBodies,\n responses,\n schemas,\n spec,\n}: {\n logger: Logger;\n operations: Set<string>;\n parameters: Set<string>;\n preserveOrder: boolean;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n spec: OpenApiV3_1_X;\n}) => {\n const eventFilterSpec = logger.timeEvent('filter-spec');\n if (spec.components) {\n if (spec.components.parameters) {\n const filtered: typeof spec.components.parameters = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.parameters)) {\n if (parameters.has(addNamespace('parameter', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of parameters) {\n const { name } = removeNamespace(key);\n const source = spec.components.parameters[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.parameters = filtered;\n }\n\n if (spec.components.requestBodies) {\n const filtered: typeof spec.components.requestBodies = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.requestBodies)) {\n if (requestBodies.has(addNamespace('body', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of requestBodies) {\n const { name } = removeNamespace(key);\n const source = spec.components.requestBodies[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.requestBodies = filtered;\n }\n\n if (spec.components.responses) {\n const filtered: typeof spec.components.responses = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.responses)) {\n if (responses.has(addNamespace('response', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of responses) {\n const { name } = removeNamespace(key);\n const source = spec.components.responses[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.responses = filtered;\n }\n\n if (spec.components.schemas) {\n const filtered: typeof spec.components.schemas = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.schemas)) {\n if (schemas.has(addNamespace('schema', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of schemas) {\n const { name } = removeNamespace(key);\n const source = spec.components.schemas[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.schemas = filtered;\n }\n }\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = addNamespace('operation', createOperationKey({ method, path }));\n if (!operations.has(key)) {\n delete pathItem[method];\n }\n }\n\n // remove paths that have no operations left\n if (!Object.keys(pathItem).length) {\n delete spec.paths[path];\n }\n }\n }\n eventFilterSpec.timeEnd();\n};\n","import type { IRMediaType } from '../../../ir/mediaType';\nimport { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType';\nimport type { MediaTypeObject, SchemaObject } from '../types/spec';\n\ninterface Content {\n mediaType: string;\n schema: SchemaObject | undefined;\n type: IRMediaType | undefined;\n}\n\nexport const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => {\n const { mediaType, schema } = content;\n\n if (!schema) {\n if (isMediaTypeFileLike({ mediaType })) {\n return {\n format: 'binary',\n type: 'string',\n };\n }\n return;\n }\n\n if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) {\n return {\n ...schema,\n format: 'binary',\n };\n }\n\n return schema;\n};\n\nexport const mediaTypeObjects = ({\n content,\n}: {\n content: Record<string, MediaTypeObject> | undefined;\n}): ReadonlyArray<Content> => {\n const objects: Array<Content> = [];\n\n for (const mediaType in content) {\n objects.push({\n mediaType,\n schema: content[mediaType]!.schema,\n type: mediaTypeToIrMediaType({ mediaType }),\n });\n }\n\n return objects;\n};\n","import type { Context } from '../../../ir/context';\nimport { isMediaTypeFileLike } from '../../../ir/mediaType';\nimport type { IR } from '../../../ir/types';\nimport { addItemsToSchema } from '../../../ir/utils';\nimport type {\n SchemaState,\n SchemaType,\n SchemaWithRequired,\n} from '../../../openApi/shared/types/schema';\nimport {\n convertDiscriminatorValue,\n type DiscriminatorPropertyType,\n discriminatorValues,\n} from '../../../openApi/shared/utils/discriminator';\nimport { isTopLevelComponent, refToName } from '../../../utils/ref';\nimport type { SchemaObject } from '../types/spec';\n\nexport const getSchemaTypes = ({\n schema,\n}: {\n schema: SchemaObject;\n}): ReadonlyArray<SchemaType<SchemaObject>> => {\n if (typeof schema.type === 'string') {\n return [schema.type];\n }\n\n if (schema.type) {\n return schema.type;\n }\n\n // infer object based on the presence of properties\n if (schema.properties) {\n return ['object'];\n }\n\n return [];\n};\n\n/**\n * Finds the type of a discriminator property by looking it up in the provided schemas.\n * Searches through properties and allOf chains to find the property definition.\n */\nconst findDiscriminatorPropertyType = ({\n context,\n propertyName,\n schemas,\n}: {\n context: Context;\n propertyName: string;\n schemas: ReadonlyArray<SchemaObject>;\n}): DiscriminatorPropertyType => {\n for (const schema of schemas) {\n const resolved = schema.$ref ? context.resolveRef<SchemaObject>(schema.$ref) : schema;\n\n // Check direct properties\n const property = resolved.properties?.[propertyName];\n if (property === true) {\n continue;\n }\n if (property) {\n const resolvedProperty = property.$ref\n ? context.resolveRef<SchemaObject>(property.$ref)\n : property;\n // Handle both single type and array of types (3.1.x supports type arrays)\n const propertyTypes = Array.isArray(resolvedProperty.type)\n ? resolvedProperty.type\n : resolvedProperty.type\n ? [resolvedProperty.type]\n : [];\n for (const propType of propertyTypes) {\n if (propType === 'boolean' || propType === 'integer' || propType === 'number') {\n return propType;\n }\n }\n }\n\n // Check allOf chains\n if (resolved.allOf) {\n const foundType = findDiscriminatorPropertyType({\n context,\n propertyName,\n schemas: resolved.allOf,\n });\n if (foundType !== 'string') {\n return foundType;\n }\n }\n }\n\n return 'string';\n};\n\n/**\n * Recursively finds discriminators in a schema, including nested allOf compositions.\n * This is needed when a schema extends another schema via allOf, and that parent\n * schema is itself an allOf composition with discriminators in inline schemas.\n */\nconst findDiscriminatorsInSchema = ({\n context,\n discriminators = [],\n schema,\n}: {\n context: Context;\n discriminators?: Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n }>;\n schema: SchemaObject;\n}): Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n}> => {\n // Check if this schema has a discriminator\n if (schema.discriminator) {\n discriminators.push({\n discriminator: schema.discriminator,\n oneOf: schema.oneOf,\n });\n }\n\n // If this schema is an allOf composition, recursively search in its components\n if (schema.allOf) {\n for (const compositionSchema of schema.allOf) {\n let resolvedSchema: SchemaObject;\n if (compositionSchema.$ref) {\n resolvedSchema = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n } else {\n resolvedSchema = compositionSchema;\n }\n\n findDiscriminatorsInSchema({\n context,\n discriminators,\n schema: resolvedSchema,\n });\n }\n }\n\n return discriminators;\n};\n\n/**\n * Gets the discriminator value for a schema.\n * Returns only the schema's own discriminator value, not child values.\n */\nconst getAllDiscriminatorValues = ({\n discriminator,\n schemaRef,\n}: {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n schemaRef: string;\n}): Array<string> => {\n const values: Array<string> = [];\n\n // Check each entry in the discriminator mapping\n for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) {\n if (mappedSchemaRef === schemaRef) {\n // This is the current schema's own value\n values.push(value);\n }\n }\n\n return values;\n};\n\nconst parseSchemaJsDoc = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.deprecated !== undefined) {\n irSchema.deprecated = schema.deprecated;\n }\n\n if (schema.example) {\n irSchema.example = schema.example;\n }\n\n if (schema.description) {\n irSchema.description = schema.description;\n }\n\n if (schema.title) {\n irSchema.title = schema.title;\n }\n};\n\nconst parseSchemaMeta = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.const !== undefined) {\n irSchema.const = schema.const;\n\n // try to infer schema type\n if (!schema.type) {\n if (schema.const === null) {\n irSchema.type = 'null';\n } else {\n switch (typeof schema.const) {\n case 'bigint':\n case 'number':\n irSchema.type = 'number';\n break;\n case 'boolean':\n irSchema.type = 'boolean';\n break;\n case 'string':\n irSchema.type = 'string';\n break;\n }\n }\n }\n }\n\n if (schema.default !== undefined) {\n irSchema.default = schema.default;\n }\n\n if (schema.exclusiveMaximum !== undefined) {\n irSchema.exclusiveMaximum = schema.exclusiveMaximum;\n }\n\n if (schema.exclusiveMinimum !== undefined) {\n irSchema.exclusiveMinimum = schema.exclusiveMinimum;\n }\n\n if (schema.format) {\n irSchema.format = schema.format;\n } else if (\n schema.contentMediaType &&\n isMediaTypeFileLike({ mediaType: schema.contentMediaType })\n ) {\n irSchema.format = 'binary';\n }\n\n if (schema.maximum !== undefined) {\n irSchema.maximum = schema.maximum;\n }\n\n if (schema.maxItems !== undefined) {\n irSchema.maxItems = schema.maxItems;\n }\n\n if (schema.maxLength !== undefined) {\n irSchema.maxLength = schema.maxLength;\n }\n\n if (schema.minimum !== undefined) {\n irSchema.minimum = schema.minimum;\n }\n\n if (schema.minItems !== undefined) {\n irSchema.minItems = schema.minItems;\n }\n\n if (schema.minLength !== undefined) {\n irSchema.minLength = schema.minLength;\n }\n\n if (schema.pattern) {\n irSchema.pattern = schema.pattern;\n }\n\n if (schema.readOnly) {\n irSchema.accessScope = 'read';\n } else if (schema.writeOnly) {\n irSchema.accessScope = 'write';\n }\n};\n\nconst parseArray = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (\n (schema.prefixItems && schema.prefixItems.length) ||\n (schema.maxItems && schema.maxItems === schema.minItems) ||\n schema.const !== undefined\n ) {\n irSchema.type = 'tuple';\n } else {\n irSchema.type = 'array';\n }\n\n let schemaItems: Array<IR.SchemaObject> = [];\n\n for (const item of schema.prefixItems ?? []) {\n const irItemSchema = schemaToIrSchema({\n context,\n schema: item,\n state,\n });\n schemaItems.push(irItemSchema);\n }\n\n if (schema.items) {\n const irItemsSchema = schemaToIrSchema({\n context,\n schema: schema.items,\n state,\n });\n\n if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {\n schemaItems = Array(schema.maxItems).fill(irItemsSchema);\n } else {\n const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf;\n if (\n ofArray &&\n ofArray.length > 1 &&\n !getSchemaTypes({ schema: schema.items }).includes('null')\n ) {\n // bring composition up to avoid incorrectly nested arrays\n irSchema = {\n ...irSchema,\n ...irItemsSchema,\n };\n } else {\n schemaItems.push(irItemsSchema);\n }\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseBoolean = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n irSchema.type = 'boolean';\n\n return irSchema;\n};\n\nconst parseNull = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n irSchema.type = 'null';\n\n return irSchema;\n};\n\nconst parseNumber = ({\n irSchema = {},\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: Omit<SchemaObject, 'type'> & {\n type: SchemaType<SchemaObject>;\n };\n}): IR.SchemaObject => {\n irSchema.type = schema.type;\n\n return irSchema;\n};\n\nconst parseObject = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'object';\n\n const schemaProperties: Record<string, IR.SchemaObject> = {};\n\n for (const name in schema.properties) {\n const property = schema.properties[name]!;\n if (typeof property === 'boolean') {\n // TODO: parser - handle boolean properties\n } else {\n const irPropertySchema = schemaToIrSchema({\n context,\n schema: property,\n state,\n });\n schemaProperties[name] = irPropertySchema;\n }\n }\n\n if (Object.keys(schemaProperties).length) {\n irSchema.properties = schemaProperties;\n }\n\n if (schema.additionalProperties === undefined) {\n if (!irSchema.properties) {\n irSchema.additionalProperties = {\n type: 'unknown',\n };\n }\n } else if (typeof schema.additionalProperties === 'boolean') {\n // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf\n // This would override inherited properties from other schemas in the composition\n const isEmptyObjectInAllOf =\n state.inAllOf &&\n schema.additionalProperties === false &&\n (!schema.properties || !Object.keys(schema.properties).length) &&\n (!schema.patternProperties || !Object.keys(schema.patternProperties).length);\n\n if (!isEmptyObjectInAllOf) {\n irSchema.additionalProperties = {\n type: schema.additionalProperties ? 'unknown' : 'never',\n };\n }\n } else {\n const irAdditionalPropertiesSchema = schemaToIrSchema({\n context,\n schema: schema.additionalProperties,\n state,\n });\n irSchema.additionalProperties = irAdditionalPropertiesSchema;\n }\n\n if (schema.patternProperties) {\n const patternProperties: Record<string, IR.SchemaObject> = {};\n\n for (const pattern in schema.patternProperties) {\n const patternSchema = schema.patternProperties[pattern]!;\n const irPatternSchema = schemaToIrSchema({\n context,\n schema: patternSchema,\n state,\n });\n patternProperties[pattern] = irPatternSchema;\n }\n\n if (Object.keys(patternProperties).length) {\n irSchema.patternProperties = patternProperties;\n }\n }\n\n if (schema.propertyNames) {\n irSchema.propertyNames = schemaToIrSchema({\n context,\n schema: schema.propertyNames,\n state,\n });\n }\n\n if (schema.required) {\n irSchema.required = schema.required;\n }\n\n return irSchema;\n};\n\nconst parseString = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n irSchema.type = 'string';\n\n return irSchema;\n};\n\nexport const parseExtensions = ({ source, target }: { source: object; target: object }) => {\n for (const key in source) {\n if (key.startsWith('x-')) {\n (target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];\n }\n }\n};\n\nconst initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n\n parseSchemaJsDoc({\n irSchema,\n schema,\n });\n\n parseExtensions({\n source: schema,\n target: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseAllOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'allOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n const compositionSchemas = schema.allOf;\n\n // Collect discriminator information to add after all compositions are processed\n type DiscriminatorInfo = {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n isRequired: boolean;\n values: ReadonlyArray<string>;\n };\n const discriminatorsToAdd: Array<DiscriminatorInfo> = [];\n const addedDiscriminators = new Set<string>();\n\n for (const compositionSchema of compositionSchemas) {\n const originalInAllOf = state.inAllOf;\n // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components\n if (!('$ref' in compositionSchema)) {\n state.inAllOf = true;\n }\n const irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n state.inAllOf = originalInAllOf;\n if (state.inAllOf === undefined) {\n delete state.inAllOf;\n }\n\n if (schema.required) {\n if (irCompositionSchema.required) {\n irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];\n } else {\n irCompositionSchema.required = schema.required;\n }\n }\n\n schemaItems.push(irCompositionSchema);\n\n if (compositionSchema.$ref) {\n const ref = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n // `$ref` should be passed from the root `parseSchema()` call\n if (state.$ref) {\n // Find all discriminators in the referenced schema, including nested allOf compositions\n const discriminators = findDiscriminatorsInSchema({\n context,\n schema: ref,\n });\n\n // Process each discriminator found\n for (const { discriminator, oneOf } of discriminators) {\n // Skip if we've already collected this discriminator property\n if (addedDiscriminators.has(discriminator.propertyName)) {\n continue;\n }\n\n const values = discriminatorValues(\n state.$ref,\n discriminator.mapping,\n // If the ref has oneOf, we only use the schema name as the value\n // only if current schema is part of the oneOf. Else it is extending\n // the ref schema\n oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined,\n );\n\n if (values.length > 0) {\n // Check if the discriminator property is required in any of the discriminator schemas\n const isRequired = discriminators.some(\n (d) =>\n d.discriminator.propertyName === discriminator.propertyName &&\n // Check in the ref's required array or in the allOf components\n (ref.required?.includes(d.discriminator.propertyName) ||\n (ref.allOf &&\n ref.allOf.some((item) => {\n const resolvedItem = item.$ref\n ? context.resolveRef<SchemaObject>(item.$ref)\n : item;\n return resolvedItem.required?.includes(d.discriminator.propertyName);\n }))),\n );\n\n discriminatorsToAdd.push({\n discriminator,\n isRequired,\n values,\n });\n addedDiscriminators.add(discriminator.propertyName);\n }\n }\n }\n }\n }\n\n // Now add discriminators after all compositions have been processed\n for (const { discriminator, isRequired, values } of discriminatorsToAdd) {\n // Get all discriminator values including children for union types\n const allValues = getAllDiscriminatorValues({\n discriminator,\n schemaRef: state.$ref!,\n });\n\n // Use allValues if we found children, otherwise use the original values\n const finalValues = allValues.length > 0 ? allValues : values;\n\n // Detect the actual type of the discriminator property\n const propertyType = findDiscriminatorPropertyType({\n context,\n propertyName: discriminator.propertyName,\n schemas: compositionSchemas,\n });\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = finalValues.map((value) =>\n convertDiscriminatorValue(value, propertyType),\n );\n\n const discriminatorProperty: IR.SchemaObject =\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!;\n\n // Check if any $ref schemas in schemaItems have this discriminator property\n // If yes, mark them to omit it to avoid conflicts\n for (const item of schemaItems) {\n if (item.$ref || item.symbolRef) {\n // Check if the referenced schema has this property\n const hasProperty = (() => {\n if (!item.$ref) return false;\n try {\n const refSchema = context.resolveRef<SchemaObject>(item.$ref);\n // Check if the discriminator property exists in the ref schema\n return (\n refSchema.properties?.[discriminator.propertyName] !== undefined ||\n (refSchema.allOf &&\n refSchema.allOf.some((allOfItem) => {\n const resolved = allOfItem.$ref\n ? context.resolveRef<SchemaObject>(allOfItem.$ref)\n : allOfItem;\n return resolved.properties?.[discriminator.propertyName] !== undefined;\n }))\n );\n } catch {\n return false;\n }\n })();\n\n if (hasProperty) {\n // Mark this ref to omit the discriminator property\n if (!item.omit) {\n item.omit = [discriminator.propertyName];\n } else if (!item.omit.includes(discriminator.propertyName)) {\n item.omit = [...item.omit, discriminator.propertyName];\n }\n }\n }\n }\n\n // Find the inline schema (non-$ref) to merge the discriminator property into\n // The inline schema should be the last non-$ref item in schemaItems\n let inlineSchema: IR.SchemaObject | undefined;\n for (let i = schemaItems.length - 1; i >= 0; i--) {\n const item = schemaItems[i]!;\n // Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema\n if (item.type === 'object' || item.properties) {\n inlineSchema = item;\n break;\n }\n }\n\n // If we found an inline schema, add the discriminator property to it\n if (inlineSchema) {\n if (!inlineSchema.properties) {\n inlineSchema.properties = {};\n }\n inlineSchema.properties[discriminator.propertyName] = discriminatorProperty;\n\n if (isRequired) {\n if (!inlineSchema.required) {\n inlineSchema.required = [];\n }\n if (!inlineSchema.required.includes(discriminator.propertyName)) {\n inlineSchema.required = [...inlineSchema.required, discriminator.propertyName];\n }\n }\n } else {\n // Fallback: create a separate discriminator schema if no inline schema found\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [discriminator.propertyName]: discriminatorProperty,\n },\n type: 'object',\n };\n\n if (isRequired) {\n irDiscriminatorSchema.required = [discriminator.propertyName];\n }\n schemaItems.push(irDiscriminatorSchema);\n }\n }\n\n if (schemaTypes.includes('object')) {\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n for (const requiredProperty of irObjectSchema.required ?? []) {\n if (!irObjectSchema.properties[requiredProperty]) {\n for (const compositionSchema of compositionSchemas) {\n // TODO: parser - this could be probably resolved more accurately\n const finalCompositionSchema = compositionSchema.$ref\n ? context.resolveRef<SchemaObject>(compositionSchema.$ref)\n : compositionSchema;\n\n if (getSchemaTypes({ schema: finalCompositionSchema }).includes('object')) {\n const irCompositionSchema = parseOneType({\n context,\n schema: {\n ...finalCompositionSchema,\n type: 'object',\n },\n state,\n });\n\n if (irCompositionSchema.properties?.[requiredProperty]) {\n irObjectSchema.properties[requiredProperty] =\n irCompositionSchema.properties[requiredProperty];\n break;\n }\n }\n }\n }\n }\n schemaItems.push(irObjectSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n logicalOperator: 'and',\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaTypes.includes('null')) {\n // nest composition to avoid producing an intersection with null\n const nestedItems: Array<IR.SchemaObject> = [\n {\n type: 'null',\n },\n ];\n\n if (schemaItems.length) {\n nestedItems.unshift(irSchema);\n }\n\n irSchema = {\n items: nestedItems,\n logicalOperator: 'or',\n };\n }\n\n return irSchema;\n};\n\nconst parseAnyOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'anyOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n const compositionSchemas = schema.anyOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n schemaItems.push(irCompositionSchema);\n }\n\n if (schemaTypes.includes('null')) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaTypes.includes('object')) {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseEnum = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'enum'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n irSchema.type = 'enum';\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n for (const [index, enumValue] of schema.enum.entries()) {\n const typeOfEnumValue = typeof enumValue;\n let enumType: SchemaType<SchemaObject> | undefined;\n\n if (\n typeOfEnumValue === 'string' ||\n typeOfEnumValue === 'number' ||\n typeOfEnumValue === 'boolean'\n ) {\n enumType = typeOfEnumValue;\n } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {\n enumType = 'array';\n } else if (enumValue === null) {\n // type must contain null\n if (schemaTypes.includes('null')) {\n enumType = 'null';\n }\n } else {\n console.warn(\n '๐Ÿšจ',\n `unhandled \"${typeOfEnumValue}\" typeof value \"${enumValue}\" for enum`,\n schema.enum,\n );\n }\n\n if (!enumType) {\n continue;\n }\n\n const irTypeSchema = parseOneType({\n context,\n schema: {\n const: enumValue,\n description: schema['x-enum-descriptions']?.[index],\n title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],\n type: enumType,\n },\n state,\n });\n\n schemaItems.push(irTypeSchema);\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseOneOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'oneOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n let schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n const compositionSchemas = schema.oneOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n required: [schema.discriminator.propertyName],\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n // since we know oneOf will be using \"or\" logical operator, if the parsed\n // composition schema also has an \"or\" operator, we can bring it up\n // to avoid unnecessary brackets\n if (\n irCompositionSchema.logicalOperator === 'or' &&\n irCompositionSchema.type !== 'array' &&\n irCompositionSchema.items\n ) {\n schemaItems = schemaItems.concat(irCompositionSchema.items);\n } else {\n schemaItems.push(irCompositionSchema);\n }\n }\n\n if (schemaTypes.includes('null')) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaTypes.includes('object')) {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseRef = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, '$ref'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/components/schemas/Foo/properties/bar)\n // to avoid generating orphaned named types or referencing unregistered symbols\n const isComponentsRef = isTopLevelComponent(schema.$ref);\n if (!isComponentsRef) {\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n const irSchema = schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n return irSchema;\n }\n // Fallback to preserving the ref if circular\n }\n\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n const irRefSchema: IR.SchemaObject = {};\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n irRefSchema.$ref = decodeURI(schema.$ref);\n\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [];\n schemaItems.push(irRefSchema);\n\n if (schema.type && typeof schema.type !== 'string') {\n if (schema.type.includes('null')) {\n schemaItems.push({ type: 'null' });\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseOneType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: Omit<SchemaObject, 'type'> & {\n type: SchemaType<SchemaObject>;\n };\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n }\n\n switch (schema.type) {\n case 'array':\n return parseArray({\n context,\n irSchema,\n schema,\n state,\n });\n case 'boolean':\n return parseBoolean({\n context,\n irSchema,\n schema,\n });\n case 'integer':\n case 'number':\n return parseNumber({\n context,\n irSchema,\n schema,\n });\n case 'null':\n return parseNull({\n context,\n irSchema,\n schema,\n });\n case 'object':\n return parseObject({\n context,\n irSchema,\n schema,\n state,\n });\n case 'string':\n return parseString({\n context,\n irSchema,\n schema,\n });\n default:\n // gracefully handle invalid type\n return parseUnknown({ context, irSchema, schema });\n }\n};\n\nconst parseManyTypes = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: Omit<SchemaObject, 'type'> & {\n type: ReadonlyArray<SchemaType<SchemaObject>>;\n };\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n const typeIrSchema: IR.SchemaObject = {};\n\n parseSchemaMeta({ irSchema: typeIrSchema, schema });\n\n if (schema.type.includes('null') && typeIrSchema.default === null) {\n // clear to avoid duplicate default inside the non-null schema.\n // this would produce incorrect validator output\n delete typeIrSchema.default;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [];\n\n for (const type of schema.type) {\n if (type === 'null') {\n schemaItems.push({ type: 'null' });\n } else {\n const irTypeSchema = parseOneType({\n context,\n irSchema: { ...typeIrSchema },\n schema: {\n ...schema,\n type,\n },\n state,\n });\n\n schemaItems.push(irTypeSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseType = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n\n const schemaTypes = getSchemaTypes({ schema });\n\n if (schemaTypes.length === 1) {\n return parseOneType({\n context,\n irSchema,\n schema: {\n ...schema,\n type: schemaTypes[0]!,\n },\n state,\n });\n }\n\n return parseManyTypes({\n context,\n irSchema,\n schema: {\n ...schema,\n type: schemaTypes,\n },\n state,\n });\n};\n\nconst parseUnknown = ({\n irSchema,\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n irSchema.type = 'unknown';\n\n parseSchemaMeta({ irSchema, schema });\n\n return irSchema;\n};\n\nexport const schemaToIrSchema = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaObject;\n state: SchemaState | undefined;\n}): IR.SchemaObject => {\n if (!state) {\n state = {\n circularReferenceTracker: new Set(),\n };\n }\n\n if (state.$ref) {\n state.circularReferenceTracker.add(state.$ref);\n }\n\n if (schema.$ref) {\n return parseRef({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, '$ref'>,\n state,\n });\n }\n\n if (schema.enum) {\n return parseEnum({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'enum'>,\n state,\n });\n }\n\n if (schema.allOf) {\n return parseAllOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'allOf'>,\n state,\n });\n }\n\n if (schema.anyOf) {\n return parseAnyOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'anyOf'>,\n state,\n });\n }\n\n if (schema.oneOf) {\n return parseOneOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'oneOf'>,\n state,\n });\n }\n\n // infer object based on the presence of properties\n if (schema.type || schema.properties) {\n return parseType({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n // infer string with binary format based on contentMediaType\n if (schema.contentMediaType && isMediaTypeFileLike({ mediaType: schema.contentMediaType })) {\n return parseType({\n context,\n schema: { ...schema, type: 'string' } as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n return parseUnknown({ context, schema });\n};\n\nexport const parseSchema = ({\n $ref,\n context,\n schema,\n}: {\n $ref: string;\n context: Context;\n schema: SchemaObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.schemas) {\n context.ir.components.schemas = {};\n }\n\n context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({\n context,\n schema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { getPaginationKeywordsRegExp } from '../../../ir/pagination';\nimport type { SchemaType } from '../../../openApi/shared/types/schema';\nimport type { ParameterObject, RequestBodyObject } from '../types/spec';\nimport type { SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { getSchemaTypes } from './schema';\n\nconst isPaginationType = (schemaTypes: ReadonlyArray<SchemaType<SchemaObject>>): boolean =>\n schemaTypes.includes('boolean') ||\n schemaTypes.includes('integer') ||\n schemaTypes.includes('number') ||\n schemaTypes.includes('string');\n\n// We handle only simple values for now, up to 1 nested field\nexport const paginationField = ({\n context,\n name,\n schema,\n}: {\n context: Context;\n name: string;\n schema: SchemaObject;\n}): boolean | string => {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n if (paginationRegExp.test(name)) {\n return true;\n }\n\n if (schema.$ref) {\n const ref = context.resolveRef<ParameterObject | RequestBodyObject | SchemaObject>(schema.$ref);\n\n if ('content' in ref || 'in' in ref) {\n let refSchema: SchemaObject | undefined;\n\n if ('in' in ref) {\n refSchema = ref.schema;\n }\n\n if (!refSchema) {\n // parameter or body\n const contents = mediaTypeObjects({ content: ref.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content?.schema) {\n refSchema = content.schema;\n }\n }\n\n if (!refSchema) {\n return false;\n }\n\n return paginationField({\n context,\n name,\n schema: refSchema,\n });\n }\n\n return paginationField({\n context,\n name,\n schema: ref,\n });\n }\n\n for (const name in schema.properties) {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n\n if (paginationRegExp.test(name)) {\n const property = schema.properties[name]!;\n\n if (typeof property !== 'boolean') {\n // TODO: resolve deeper references\n const schemaTypes = getSchemaTypes({ schema: property });\n\n if (!schemaTypes.length) {\n const compositionSchemas = property.anyOf ?? property.oneOf;\n const nonNullCompositionSchemas = (compositionSchemas ?? []).filter(\n (schema) => schema.type !== 'null',\n );\n if (nonNullCompositionSchemas.length === 1) {\n const schemaTypes = getSchemaTypes({\n schema: nonNullCompositionSchemas[0]!,\n });\n if (isPaginationType(schemaTypes)) {\n return name;\n }\n }\n }\n\n if (isPaginationType(schemaTypes)) {\n return name;\n }\n }\n }\n }\n\n for (const allOf of schema.allOf ?? []) {\n const pagination = paginationField({\n context,\n name,\n schema: allOf,\n });\n if (pagination) {\n return pagination;\n }\n }\n\n return false;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type { State } from '../../../openApi/shared/types/state';\nimport type { httpMethods } from '../../../openApi/shared/utils/operation';\nimport { operationToId } from '../../../openApi/shared/utils/operation';\nimport type {\n OperationObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { contentToSchema, mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ninterface Operation\n extends Omit<OperationObject, 'parameters'>, Pick<IR.OperationObject, 'parameters'> {}\n\nconst parseOperationJsDoc = ({\n irOperation,\n operation,\n}: {\n irOperation: IR.OperationObject;\n operation: Operation;\n}) => {\n if (operation.deprecated !== undefined) {\n irOperation.deprecated = operation.deprecated;\n }\n\n if (operation.description) {\n irOperation.description = operation.description;\n }\n\n if (operation.summary) {\n irOperation.summary = operation.summary;\n }\n\n if (operation.tags?.length) {\n irOperation.tags = operation.tags;\n }\n};\n\nconst initIrOperation = ({\n context,\n method,\n operation,\n path,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n state: State;\n}): IR.OperationObject => {\n const irOperation: IR.OperationObject = {\n id: operationToId({\n context,\n id: operation.operationId,\n method,\n path,\n state,\n }),\n method,\n path,\n };\n\n if (operation.operationId) {\n irOperation.operationId = operation.operationId;\n }\n\n parseOperationJsDoc({\n irOperation,\n operation,\n });\n\n parseExtensions({\n source: operation,\n target: irOperation,\n });\n\n return irOperation;\n};\n\nconst operationToIrOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}): IR.OperationObject => {\n const irOperation = initIrOperation({\n context,\n method,\n operation,\n path,\n state,\n });\n\n if (operation.parameters) {\n irOperation.parameters = operation.parameters;\n }\n\n if (operation.requestBody) {\n const requestBody =\n '$ref' in operation.requestBody\n ? context.resolveRef<RequestBodyObject>(operation.requestBody.$ref)\n : operation.requestBody;\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n const pagination = paginationField({\n context,\n name: '',\n schema: {\n description: requestBody.description,\n ...content.schema,\n },\n });\n\n irOperation.body = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: requestBody.description,\n ...('$ref' in operation.requestBody ? operation.requestBody : content.schema),\n },\n state: undefined,\n }),\n };\n\n if (pagination) {\n irOperation.body.pagination = pagination;\n }\n\n if (requestBody.required) {\n irOperation.body.required = requestBody.required;\n }\n\n if (content.type) {\n irOperation.body.type = content.type;\n }\n }\n }\n\n for (const name in operation.responses) {\n if (name.startsWith('x-')) continue;\n\n if (!irOperation.responses) {\n irOperation.responses = {};\n }\n\n const response = operation.responses[name]! as ResponseObject | ReferenceObject;\n const responseObject =\n '$ref' in response ? context.resolveRef<ResponseObject>(response.$ref) : response;\n const contents = mediaTypeObjects({ content: responseObject.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n irOperation.responses[name] = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: responseObject.description,\n ...contentToSchema({ content }),\n },\n state: undefined,\n }),\n };\n } else {\n irOperation.responses[name] = {\n schema: {\n description: responseObject.description,\n // TODO: parser - cover all statues with empty response bodies\n // 1xx, 204, 205, 304\n type: name === '204' ? 'void' : 'unknown',\n },\n };\n }\n }\n\n if (operation.security) {\n const securitySchemeObjects: Map<string, IR.SecurityObject> = new Map();\n\n for (const securityRequirementObject of operation.security) {\n for (const name in securityRequirementObject) {\n const securitySchemeObject = securitySchemesMap.get(name);\n\n if (!securitySchemeObject) {\n continue;\n }\n\n securitySchemeObjects.set(name, securitySchemeObject);\n }\n }\n\n if (securitySchemeObjects.size) {\n irOperation.security = Array.from(securitySchemeObjects.values());\n }\n }\n\n // TODO: parser - handle servers\n // qux: operation.servers\n\n return irOperation;\n};\n\nconst parseOperationObject = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: {\n context: Context;\n method: (typeof httpMethods)[number];\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (operation.servers) {\n context.ir.servers = [...(context.ir.servers ?? []), ...operation.servers];\n }\n\n const parsed = operationToIrOperation({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n });\n\n return { parsed };\n};\n\nexport const parsePathOperation = ({\n context,\n method,\n path,\n ...options\n}: {\n context: Context;\n method: (typeof httpMethods)[number];\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.paths) {\n context.ir.paths = {};\n }\n\n if (!context.ir.paths[path]) {\n context.ir.paths[path] = {};\n }\n\n const { parsed } = parseOperationObject({\n context,\n method,\n path,\n ...options,\n });\n\n context.ir.paths[path][method] = parsed;\n};\n\nexport const parseWebhookOperation = ({\n context,\n key,\n method,\n ...options\n}: {\n context: Context;\n key: string;\n method: (typeof httpMethods)[number];\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.webhooks) {\n context.ir.webhooks = {};\n }\n\n if (!context.ir.webhooks[key]) {\n context.ir.webhooks[key] = {};\n }\n\n const { parsed } = parseOperationObject({\n context,\n method,\n path: key as `/${string}`,\n ...options,\n });\n\n context.ir.webhooks[key][method] = parsed;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { ParameterObject, ReferenceObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\n/**\n * Returns default parameter `allowReserved` based on value of `in`.\n */\nconst defaultAllowReserved = (_in: ParameterObject['in']): boolean | undefined => {\n switch (_in) {\n // this keyword only applies to parameters with an `in` value of `query`\n case 'query':\n return false;\n default:\n return;\n }\n};\n\n/**\n * Returns default parameter `explode` based on value of `style`.\n */\nconst defaultExplode = (style: Required<ParameterObject>['style']): boolean => {\n switch (style) {\n // default value for `deepObject` is `false`, but that behavior is undefined\n // so we use `true` to make this work with the `client-fetch` package\n case 'deepObject':\n case 'form':\n return true;\n default:\n return false;\n }\n};\n\n/**\n * Returns default parameter `style` based on value of `in`.\n */\nconst defaultStyle = (_in: ParameterObject['in']): Required<ParameterObject>['style'] => {\n switch (_in) {\n case 'header':\n case 'path':\n return 'simple';\n case 'cookie':\n case 'query':\n return 'form';\n }\n};\n\nexport const parametersArrayToObject = ({\n context,\n parameters,\n}: {\n context: Context;\n parameters?: ReadonlyArray<ParameterObject | ReferenceObject>;\n}): IR.ParametersObject | undefined => {\n if (!parameters || !Object.keys(parameters).length) {\n return;\n }\n\n const parametersObject: IR.ParametersObject = {};\n\n for (const parameterOrReference of parameters) {\n const parameter =\n '$ref' in parameterOrReference\n ? context.dereference<ParameterObject>(parameterOrReference)\n : parameterOrReference;\n\n if (!parametersObject[parameter.in]) {\n parametersObject[parameter.in] = {};\n }\n\n // lowercase keys for case insensitive access\n parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({\n $ref: `#/todo/real/path/to/parameter/${parameter.name}`,\n context,\n parameter,\n });\n }\n\n return parametersObject;\n};\n\nconst parameterToIrParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}): IR.ParameterObject => {\n // TODO: parser - fix\n let schema = parameter.schema;\n\n if (!schema) {\n const contents = mediaTypeObjects({ content: parameter.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content) {\n schema = content.schema;\n }\n }\n\n const finalSchema: SchemaObject = {\n deprecated: parameter.deprecated,\n description: parameter.description,\n ...schema,\n };\n\n const pagination = paginationField({\n context,\n name: parameter.name,\n schema: finalSchema,\n });\n\n const style = parameter.style || defaultStyle(parameter.in);\n const explode = parameter.explode !== undefined ? parameter.explode : defaultExplode(style);\n const allowReserved =\n parameter.allowReserved !== undefined\n ? parameter.allowReserved\n : defaultAllowReserved(parameter.in);\n\n const irParameter: IR.ParameterObject = {\n allowReserved,\n explode,\n location: parameter.in,\n name: parameter.name,\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n style,\n };\n\n if (parameter.deprecated) {\n irParameter.deprecated = parameter.deprecated;\n }\n\n if (parameter.description) {\n irParameter.description = parameter.description;\n }\n\n if (pagination) {\n irParameter.pagination = pagination;\n }\n\n if (parameter.required) {\n irParameter.required = parameter.required;\n }\n\n parseExtensions({\n source: parameter,\n target: irParameter,\n });\n\n return irParameter;\n};\n\nexport const parseParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.parameters) {\n context.ir.components.parameters = {};\n }\n\n context.ir.components.parameters[refToName($ref)] = parameterToIrParameter({\n $ref,\n context,\n parameter,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { RequestBodyObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { schemaToIrSchema } from './schema';\n\nconst requestBodyToIrRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}): IR.RequestBodyObject => {\n // TODO: parser - fix\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n const schema = content ? content.schema : undefined;\n\n const finalSchema: SchemaObject = {\n description: requestBody.description,\n ...schema,\n };\n\n const irRequestBody: IR.RequestBodyObject = {\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n };\n\n if (requestBody.description) {\n irRequestBody.description = requestBody.description;\n }\n\n if (requestBody.required) {\n irRequestBody.required = requestBody.required;\n }\n\n return irRequestBody;\n};\n\nexport const parseRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.requestBodies) {\n context.ir.components.requestBodies = {};\n }\n\n context.ir.components.requestBodies[refToName($ref)] = requestBodyToIrRequestBody({\n $ref,\n context,\n requestBody,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { parseUrl } from '../../../utils/url';\n\nexport const parseServers = ({ context }: { context: Context }) => {\n if (context.spec.servers) {\n context.ir.servers = context.spec.servers;\n return;\n }\n\n for (const input of context.config.input) {\n if (typeof input.path === 'string') {\n const url = parseUrl(input.path);\n context.ir.servers = [\n {\n url: `${url.protocol ? `${url.protocol}://` : ''}${url.host}${url.port ? `:${url.port}` : ''}`,\n },\n ];\n }\n }\n\n if (!context.ir.servers) {\n context.ir.servers = [\n {\n url: '/',\n },\n ];\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type { OpenApiV3_1_X, PathItemObject, PathsObject } from '../types/spec';\n\nexport const validateOpenApiSpec = (spec: OpenApiV3_1_X, logger: Logger): ValidatorResult => {\n const eventValidate = logger.timeEvent('validate');\n const issues: Array<ValidatorIssue> = [];\n const operationIds = new Map();\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const operationKey = createOperationKey({ method, path });\n\n if (operation.operationId) {\n if (!operationIds.has(operation.operationId)) {\n operationIds.set(operation.operationId, operationKey);\n } else {\n issues.push({\n code: 'duplicate_key',\n context: {\n key: 'operationId',\n value: operation.operationId,\n },\n message: 'Duplicate `operationId` found. Each `operationId` must be unique.',\n path: ['paths', path, method, 'operationId'],\n severity: 'error',\n });\n }\n }\n }\n }\n }\n\n if (spec.servers) {\n if (typeof spec.servers !== 'object' || !Array.isArray(spec.servers)) {\n issues.push({\n code: 'invalid_type',\n message: '`servers` must be an array.',\n path: [],\n severity: 'error',\n });\n }\n\n for (let index = 0; index < spec.servers.length; index++) {\n const server = spec.servers[index];\n if (!server || typeof server !== 'object') {\n issues.push({\n code: 'invalid_type',\n context: {\n actual: typeof server,\n expected: 'object',\n },\n message: 'Each entry in `servers` must be an object.',\n path: ['servers', index],\n severity: 'error',\n });\n } else {\n if (!server.url) {\n issues.push({\n code: 'missing_required_field',\n context: {\n field: 'url',\n },\n message: 'Missing required field `url` in server object.',\n path: ['servers', index],\n severity: 'error',\n });\n }\n }\n }\n }\n\n eventValidate.timeEnd();\n return {\n issues,\n valid: !issues.some((issue) => issue.severity === 'error'),\n };\n};\n","import type { Context } from '../../../ir/context';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport type { OpenApiV3_1_X, PathItemObject } from '../types/spec';\nimport { parseWebhookOperation } from './operation';\nimport { parametersArrayToObject } from './parameter';\n\nexport const parseWebhooks = ({\n context,\n securitySchemesMap,\n}: Pick<Parameters<typeof parseWebhookOperation>[0], 'securitySchemesMap'> & {\n context: Context<OpenApiV3_1_X>;\n}) => {\n const state: Parameters<typeof parseWebhookOperation>[0]['state'] = {\n ids: new Map(),\n };\n\n for (const key in context.spec.webhooks) {\n const webhook = context.spec.webhooks[key]!;\n\n const finalWebhook =\n '$ref' in webhook\n ? {\n ...context.resolveRef<PathItemObject>(webhook.$ref!),\n ...webhook,\n }\n : webhook;\n\n const operationArgs: Omit<Parameters<typeof parseWebhookOperation>[0], 'method'> = {\n context,\n key,\n operation: {\n description: finalWebhook.description,\n parameters: parametersArrayToObject({\n context,\n parameters: finalWebhook.parameters,\n }),\n security: context.spec.security,\n servers: finalWebhook.servers,\n summary: finalWebhook.summary,\n },\n securitySchemesMap,\n state,\n };\n\n if (finalWebhook.delete) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.delete,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.get) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.get,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.head) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.head,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.options) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.options,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.patch) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.patch,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.post) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.post,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.put) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.put,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.trace) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'trace',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.trace,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.trace.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n }\n};\n","import type { Context } from '../../../ir/context';\nimport { buildResourceMetadata } from '../../../openApi/shared/graph/meta';\nimport { transformOpenApiSpec } from '../../../openApi/shared/transforms';\nimport type { State } from '../../../openApi/shared/types/state';\nimport {\n createFilteredDependencies,\n createFilters,\n hasFilters,\n} from '../../../openApi/shared/utils/filter';\nimport { buildGraph } from '../../../openApi/shared/utils/graph';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport { handleValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type {\n OpenApiV3_1_X,\n ParameterObject,\n PathItemObject,\n PathsObject,\n RequestBodyObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { filterSpec } from './filter';\nimport { parsePathOperation } from './operation';\nimport { parametersArrayToObject, parseParameter } from './parameter';\nimport { parseRequestBody } from './requestBody';\nimport { parseSchema } from './schema';\nimport { parseServers } from './server';\nimport { validateOpenApiSpec } from './validate';\nimport { parseWebhooks } from './webhook';\n\nexport const parseV3_1_X = (context: Context<OpenApiV3_1_X>) => {\n if (context.config.parser.validate_EXPERIMENTAL) {\n const result = validateOpenApiSpec(context.spec, context.logger);\n handleValidatorResult({ context, result });\n }\n\n const shouldFilterSpec = hasFilters(context.config.parser.filters);\n if (shouldFilterSpec) {\n const filters = createFilters(context.config.parser.filters, context.spec, context.logger);\n const { graph } = buildGraph(context.spec, context.logger);\n const { resourceMetadata } = buildResourceMetadata(graph, context.logger);\n const sets = createFilteredDependencies({\n filters,\n logger: context.logger,\n resourceMetadata,\n });\n filterSpec({\n ...sets,\n logger: context.logger,\n preserveOrder: filters.preserveOrder,\n spec: context.spec,\n });\n }\n\n transformOpenApiSpec({ context });\n\n const state: State = {\n ids: new Map(),\n };\n const securitySchemesMap = new Map<string, SecuritySchemeObject>();\n\n // TODO: parser - handle more component types, old parser handles only parameters and schemas\n if (context.spec.components) {\n for (const name in context.spec.components.securitySchemes) {\n const securityOrReference = context.spec.components.securitySchemes[name]!;\n const securitySchemeObject =\n '$ref' in securityOrReference\n ? context.resolveRef<SecuritySchemeObject>(securityOrReference.$ref)\n : securityOrReference;\n securitySchemesMap.set(name, securitySchemeObject);\n }\n\n for (const name in context.spec.components.parameters) {\n const $ref = `#/components/parameters/${name}`;\n const parameterOrReference = context.spec.components.parameters[name]!;\n const parameter =\n '$ref' in parameterOrReference\n ? context.resolveRef<ParameterObject>(parameterOrReference.$ref)\n : parameterOrReference;\n\n parseParameter({\n $ref,\n context,\n parameter,\n });\n }\n\n for (const name in context.spec.components.requestBodies) {\n const $ref = `#/components/requestBodies/${name}`;\n const requestBodyOrReference = context.spec.components.requestBodies[name]!;\n const requestBody =\n '$ref' in requestBodyOrReference\n ? context.resolveRef<RequestBodyObject>(requestBodyOrReference.$ref)\n : requestBodyOrReference;\n\n parseRequestBody({\n $ref,\n context,\n requestBody,\n });\n }\n\n for (const name in context.spec.components.schemas) {\n const $ref = `#/components/schemas/${name}`;\n const schema = context.spec.components.schemas[name]!;\n\n parseSchema({\n $ref,\n context,\n schema,\n });\n }\n }\n\n parseServers({ context });\n\n for (const path in context.spec.paths) {\n if (path.startsWith('x-')) continue;\n const pathItem = context.spec.paths[path as keyof PathsObject]! as PathItemObject;\n\n const finalPathItem = pathItem.$ref\n ? {\n ...context.resolveRef<PathItemObject>(pathItem.$ref),\n ...pathItem,\n }\n : pathItem;\n\n const operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'> = {\n context,\n operation: {\n description: finalPathItem.description,\n parameters: parametersArrayToObject({\n context,\n parameters: finalPathItem.parameters,\n }),\n security: context.spec.security,\n servers: finalPathItem.servers,\n summary: finalPathItem.summary,\n },\n path: path as `/${string}`,\n securitySchemesMap,\n state,\n };\n\n if (finalPathItem.delete) {\n parsePathOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.delete,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.get) {\n parsePathOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.get,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.head) {\n parsePathOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.head,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.options) {\n parsePathOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.options,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.patch) {\n parsePathOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.patch,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.post) {\n parsePathOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.post,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.put) {\n parsePathOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.put,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.trace) {\n parsePathOperation({\n ...operationArgs,\n method: 'trace',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.trace,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.trace.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n }\n\n parseWebhooks({ context, securitySchemesMap });\n};\n","import { satisfies } from '../config/utils/dependencies';\nimport type { Context } from '../ir/context';\nimport { parseV2_0_X } from './2.0.x';\nimport { parseV3_0_X } from './3.0.x';\nimport { parseV3_1_X } from './3.1.x';\nimport type { OpenApi } from './types';\n\n/**\n * @internal\n * Parse the resolved OpenAPI specification. This will populate and return\n * `context` with intermediate representation obtained from the parsed spec.\n */\nexport function parseOpenApiSpec(context: Context): Context {\n if ('swagger' in context.spec) {\n parseV2_0_X(context as Context<OpenApi.V2_0_X>);\n return context;\n }\n\n if (satisfies(context.spec.openapi, '>=3.0.0 <3.1.0')) {\n parseV3_0_X(context as Context<OpenApi.V3_0_X>);\n return context;\n }\n\n if (satisfies(context.spec.openapi, '>=3.1.0')) {\n parseV3_1_X(context as Context<OpenApi.V3_1_X>);\n return context;\n }\n\n throw new Error('Unsupported OpenAPI specification');\n}\n","import type { StructureLocation } from '@hey-api/codegen-core';\n\nimport type { IR } from '../../../ir/types';\n\n/**\n * A function that derives path segments from an operation.\n *\n * Used by location strategies to build paths within containers.\n */\nexport type OperationPathStrategy = (operation: IR.OperationObject) => ReadonlyArray<string>;\n\n/**\n * A function that determines where an operation appears in the structure.\n *\n * Returns one or more locations, each with a full path.\n */\nexport type OperationStructureStrategy = (\n operation: IR.OperationObject,\n) => ReadonlyArray<StructureLocation['path']>;\n\nexport type OperationsStrategy = 'byTags' | 'flat' | 'single' | OperationStructureStrategy;\n\n/**\n * Built-in strategies for operations.\n */\nexport const OperationStrategy = {\n /**\n * Creates one root container per operation tag.\n *\n * Operations with multiple tags appear in multiple root containers.\n * Operations without tags use the fallback root container.\n *\n * @example\n * // Operation with tags: ['users', 'admin']\n * // Path function returns: ['list']\n * // Result: [{ path: ['users', 'list'], shell }, { path: ['admin', 'list'], shell }]\n */\n byTags:\n (config: {\n /**\n * Root name for operations without tags.\n */\n fallback: string;\n /**\n * Derives path segments from the operation.\n *\n * @default OperationPath.id()\n */\n path?: OperationPathStrategy;\n }): OperationStructureStrategy =>\n (operation) => {\n const tags = operation.tags && operation.tags.length > 0 ? operation.tags : [config.fallback];\n const path = config.path ?? OperationPath.id();\n const pathSegments = path(operation);\n return tags.map((tag) => [tag, ...pathSegments]);\n },\n\n /**\n * Creates flat functions without any container.\n *\n * Each operation becomes a standalone function at the root level.\n * No shell is applied.\n *\n * @example\n * // Operation id: 'getUsers'\n * // Result: [{ path: ['getUsers'] }]\n */\n flat:\n (config?: {\n /**\n * Derives path segments within the root from the operation.\n *\n * @default OperationPath.id()\n */\n path?: OperationPathStrategy;\n }): OperationStructureStrategy =>\n (operation) => {\n const path = config?.path ?? OperationPath.id();\n const pathSegments = path(operation);\n return [[pathSegments[pathSegments.length - 1]!]];\n },\n\n /**\n * Places all operations under a single root container.\n *\n * @example\n * // Root: 'Sdk', path function returns: ['users', 'list']\n * // Result: [{ path: ['Sdk', 'users', 'list'], shell }]\n */\n single:\n (config: {\n /**\n * Derives path segments within the root from the operation.\n *\n * @default OperationPath.id()\n */\n path?: OperationPathStrategy;\n /**\n * Name of the container.\n */\n root: string;\n }): OperationStructureStrategy =>\n (operation) => {\n const path = config.path ?? OperationPath.id();\n const pathSegments = path(operation);\n return [[config.root, ...pathSegments]];\n },\n};\n\n/**\n * Built-in path derivation helpers for operations.\n */\nexport const OperationPath = {\n /**\n * Splits operationId by delimiters to create nested paths.\n *\n * @example\n * // operationId: 'users.accounts.list'\n * // Result: ['users', 'accounts', 'list']\n *\n * @example\n * // operationId: 'users/accounts/getAll'\n * // Result: ['users', 'accounts', 'getAll']\n */\n fromOperationId:\n (config?: {\n /**\n * Pattern to split operationId.\n *\n * @default /[./]/\n */\n delimiters?: RegExp;\n /**\n * Fallback strategy if operationId is missing.\n *\n * @default OperationPath.id()\n */\n fallback?: OperationPathStrategy;\n }): OperationPathStrategy =>\n (operation) => {\n const fallback = config?.fallback ?? OperationPath.id();\n if (!operation.operationId) return fallback(operation);\n const delimiters = config?.delimiters ?? /[./]/;\n const segments = operation.operationId.split(delimiters).filter(Boolean);\n return segments.length === 0 ? fallback(operation) : segments;\n },\n\n /**\n * Splits path by delimiters to create nested paths.\n *\n * Can include the method as a prefix or suffix segment.\n *\n * @example\n * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\\/{}]+/, methodPosition: 'none'\n * // Result: ['users', 'id', 'accounts']\n *\n * @example\n * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\\/{}]+/, methodPosition: 'prefix'\n * // Result: ['get', 'users', 'id', 'accounts']\n *\n * @example\n * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\\/{}]+/, methodPosition: 'suffix'\n * // Result: ['users', 'id', 'accounts', 'get']\n */\n fromPath:\n (config?: {\n /**\n * Pattern to split the path.\n *\n * @default /[./]/\n */\n delimiters?: RegExp;\n /**\n * Position of the method segment.\n *\n * @default 'none'\n */\n methodPosition?: 'prefix' | 'suffix';\n }): OperationPathStrategy =>\n (operation) => {\n const delimiters = config?.delimiters ?? /[./]/;\n const segments = operation.path.split(delimiters).filter(Boolean);\n switch (config?.methodPosition) {\n case 'prefix':\n segments.unshift(operation.method.toLowerCase());\n break;\n case 'suffix':\n segments.push(operation.method.toLowerCase());\n break;\n default:\n break;\n }\n return segments;\n },\n\n /**\n * Uses operation.id as a single path segment.\n *\n * @example\n * // operation.id: 'getUserById'\n * // Result: ['getUserById']\n */\n id: (): OperationPathStrategy => (operation) => [operation.id],\n};\n","import type { Patch } from '../../../config/parser/patch';\nimport type { OpenApi } from '../../../openApi/types';\n\nexport async function patchOpenApiSpec({\n patchOptions,\n spec: _spec,\n}: {\n patchOptions: Patch | undefined;\n spec: unknown;\n}) {\n if (!patchOptions) {\n return;\n }\n\n const spec = _spec as OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X;\n\n if (typeof patchOptions === 'function') {\n await patchOptions(spec);\n return;\n }\n\n if (patchOptions.input) {\n await patchOptions.input(spec);\n }\n\n if ('swagger' in spec) {\n if (patchOptions.version && spec.swagger) {\n spec.swagger = (\n typeof patchOptions.version === 'string'\n ? patchOptions.version\n : patchOptions.version(spec.swagger)\n ) as typeof spec.swagger;\n }\n\n if (patchOptions.meta && spec.info) {\n patchOptions.meta(spec.info);\n }\n\n if (patchOptions.schemas && spec.definitions) {\n if (typeof patchOptions.schemas === 'function') {\n for (const [key, schema] of Object.entries(spec.definitions)) {\n if (schema && typeof schema === 'object') {\n await patchOptions.schemas(key, schema);\n }\n }\n } else {\n for (const key in patchOptions.schemas) {\n const schema = spec.definitions[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.schemas[key]!;\n await patchFn(schema);\n }\n }\n }\n\n if (patchOptions.operations && spec.paths) {\n if (typeof patchOptions.operations === 'function') {\n // Bulk callback: iterate all operations\n for (const [path, pathItem] of Object.entries(spec.paths)) {\n if (!pathItem || typeof pathItem !== 'object') continue;\n for (const method of [\n 'get',\n 'put',\n 'post',\n 'delete',\n 'options',\n 'head',\n 'patch',\n 'trace',\n ]) {\n const operation = pathItem[method as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n await patchOptions.operations(method, path, operation as any);\n }\n }\n } else {\n // Record-based: iterate named operations\n for (const key in patchOptions.operations) {\n const [method, path] = key.split(' ');\n if (!method || !path) continue;\n\n const pathItem = spec.paths[path as keyof typeof spec.paths];\n if (!pathItem) continue;\n\n const operation =\n pathItem[method.toLocaleLowerCase() as keyof typeof pathItem] ||\n pathItem[method.toLocaleUpperCase() as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n\n const patchFn = patchOptions.operations[key]!;\n await patchFn(operation as any);\n }\n }\n }\n return;\n }\n\n if (patchOptions.version && spec.openapi) {\n spec.openapi = (\n typeof patchOptions.version === 'string'\n ? patchOptions.version\n : patchOptions.version(spec.openapi)\n ) as typeof spec.openapi;\n }\n\n if (patchOptions.meta && spec.info) {\n patchOptions.meta(spec.info);\n }\n\n if (spec.components) {\n if (patchOptions.schemas && spec.components.schemas) {\n if (typeof patchOptions.schemas === 'function') {\n for (const [key, schema] of Object.entries(spec.components.schemas)) {\n if (schema && typeof schema === 'object') {\n await patchOptions.schemas(key, schema as Parameters<typeof patchOptions.schemas>[1]);\n }\n }\n } else {\n for (const key in patchOptions.schemas) {\n const schema = spec.components.schemas[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.schemas[key]!;\n await patchFn(schema as Parameters<typeof patchFn>[0]);\n }\n }\n }\n\n if (patchOptions.parameters && spec.components.parameters) {\n for (const key in patchOptions.parameters) {\n const schema = spec.components.parameters[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.parameters[key]!;\n patchFn(schema);\n }\n }\n\n if (patchOptions.requestBodies && spec.components.requestBodies) {\n for (const key in patchOptions.requestBodies) {\n const schema = spec.components.requestBodies[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.requestBodies[key]!;\n patchFn(schema);\n }\n }\n\n if (patchOptions.responses && spec.components.responses) {\n for (const key in patchOptions.responses) {\n const schema = spec.components.responses[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.responses[key]!;\n patchFn(schema);\n }\n }\n }\n\n if (patchOptions.operations && spec.paths) {\n if (typeof patchOptions.operations === 'function') {\n // Bulk callback: iterate all operations\n for (const [path, pathItem] of Object.entries(spec.paths)) {\n if (!pathItem || typeof pathItem !== 'object') continue;\n for (const method of [\n 'get',\n 'put',\n 'post',\n 'delete',\n 'options',\n 'head',\n 'patch',\n 'trace',\n ]) {\n const operation = pathItem[method as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n await patchOptions.operations(method, path, operation as any);\n }\n }\n } else {\n // Record-based: iterate named operations\n for (const key in patchOptions.operations) {\n const [method, path] = key.split(' ');\n if (!method || !path) continue;\n\n const pathItem = spec.paths[path as keyof typeof spec.paths];\n if (!pathItem) continue;\n\n const operation =\n pathItem[method.toLocaleLowerCase() as keyof typeof pathItem] ||\n pathItem[method.toLocaleUpperCase() as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n\n const patchFn = patchOptions.operations[key]!;\n await patchFn(operation as any);\n }\n }\n }\n}\n","import type { Plugin } from '../../../plugins/types';\n\nexport const definePluginConfig =\n <T extends Plugin.Types>(defaultConfig: Plugin.Config<T>) =>\n (\n userConfig?: Omit<T['config'], 'name'>,\n ): Omit<Plugin.Config<T>, 'name'> & {\n /**\n * Cast name to `any` so it doesn't throw type error in `plugins` array.\n * We could allow any `string` as plugin `name` in the object syntax, but\n * that TypeScript trick would cause all string methods to appear as\n * suggested auto completions, which is undesirable.\n */\n name: any;\n } => ({\n ...defaultConfig,\n config: {\n ...defaultConfig.config,\n ...userConfig,\n },\n });\n\n/**\n * Reusable mappers for `enabled` and `name` fields.\n */\nexport const mappers = {\n boolean: (enabled: boolean) => ({ enabled }),\n function: (name: (...args: Array<any>) => any) => ({ name }),\n string: (name: string) => ({ name }),\n} as const;\n","import { EOL } from 'node:os';\n\nexport function escapeComment(value: string) {\n return value\n .replace(/\\*\\//g, '*')\n .replace(/\\/\\*/g, '*')\n .replace(/\\r?\\n(.*)/g, (_l, w) => EOL + w.trim());\n}\n","import { toCase } from './naming/naming';\nimport type { Casing } from './naming/types';\n\n/**\n * Utilities shared across the package.\n */\nexport const utils = {\n /**\n * @deprecated use `toCase` instead\n */\n stringCase({\n case: casing,\n stripLeadingSeparators,\n value,\n }: {\n readonly case: Casing | undefined;\n /**\n * If leading separators have a semantic meaning, we might not want to\n * remove them.\n */\n stripLeadingSeparators?: boolean;\n value: string;\n }) {\n return toCase(value, casing, { stripLeadingSeparators });\n },\n /**\n * Converts the given string to the specified casing.\n */\n toCase,\n};\n","/**\n * After these structural segments, the next segment has a known role.\n * This is what makes a property literally named \"properties\" safe โ€”\n * it occupies the name position, never the structural position.\n */\nconst STRUCTURAL_ROLE: Record<string, 'name' | 'index'> = {\n items: 'index',\n patternProperties: 'name',\n properties: 'name',\n};\n\n/**\n * These structural segments have no following name/index โ€”\n * they are the terminal structural node. Append a suffix\n * to disambiguate from the parent.\n */\nconst STRUCTURAL_SUFFIX: Record<string, string> = {\n additionalProperties: 'Value',\n};\n\ntype RootContextConfig = {\n /** How many consecutive semantic segments follow before structural walking begins */\n names: number;\n /** How many leading segments to skip (the root keyword + any category segment) */\n skip: number;\n};\n\n/**\n * Root context configuration.\n */\nconst ROOT_CONTEXT: Record<string | number, RootContextConfig> = {\n components: { names: 1, skip: 2 }, // components/schemas/{name}\n definitions: { names: 1, skip: 1 }, // definitions/{name}\n paths: { names: 2, skip: 1 }, // paths/{path}/{method}\n webhooks: { names: 2, skip: 1 }, // webhooks/{name}/{method}\n};\n\n/**\n * Sanitizes a path segment for use in a derived name.\n *\n * Handles API path segments like `/api/v1/users/{id}` โ†’ `ApiV1UsersId`.\n */\nfunction sanitizeSegment(segment: string | number): string {\n const str = String(segment);\n if (str.startsWith('/')) {\n return str\n .split('/')\n .filter(Boolean)\n .map((part) => {\n const clean = part.replace(/[{}]/g, '');\n return clean.charAt(0).toUpperCase() + clean.slice(1);\n })\n .join('');\n }\n return str;\n}\n\nexport interface PathToNameOptions {\n /**\n * When provided, replaces the root semantic segments with this anchor.\n * Structural suffixes are still derived from path.\n */\n anchor?: string;\n}\n\n/**\n * Derives a composite name from a path.\n *\n * Examples:\n * .../User โ†’ 'User'\n * .../User/properties/address โ†’ 'UserAddress'\n * .../User/properties/properties โ†’ 'UserProperties'\n * .../User/properties/address/properties/city โ†’ 'UserAddressCity'\n * .../Pet/additionalProperties โ†’ 'PetValue'\n * .../Order/properties/items/items/0 โ†’ 'OrderItems'\n * paths//event/get/properties/query โ†’ 'EventGetQuery'\n *\n * With anchor:\n * paths//event/get/properties/query, { anchor: 'event.subscribe' }\n * โ†’ 'event.subscribe-Query'\n */\nexport function pathToName(\n path: ReadonlyArray<string | number>,\n options?: PathToNameOptions,\n): string {\n const names: Array<string> = [];\n let index = 0;\n\n const rootContext = ROOT_CONTEXT[path[0]!];\n if (rootContext) {\n index = rootContext.skip;\n\n if (options?.anchor) {\n // Use anchor as base name, skip past root semantic segments\n names.push(options.anchor);\n index += rootContext.names;\n } else {\n // Collect consecutive semantic name segments\n for (let n = 0; n < rootContext.names && index < path.length; n++) {\n names.push(sanitizeSegment(path[index]!));\n index++;\n }\n }\n } else {\n // Unknown root\n if (options?.anchor) {\n names.push(options.anchor);\n index++;\n } else if (index < path.length) {\n names.push(sanitizeSegment(path[index]!));\n index++;\n }\n }\n\n while (index < path.length) {\n const segment = String(path[index]);\n\n const role = STRUCTURAL_ROLE[segment];\n if (role === 'name') {\n // Next segment is a semantic name โ€” collect it\n index++;\n if (index < path.length) {\n names.push(sanitizeSegment(path[index]!));\n }\n } else if (role === 'index') {\n // Next segment is a numeric index โ€” skip it\n index++;\n if (index < path.length && typeof path[index] === 'number') {\n index++;\n }\n continue;\n } else if (STRUCTURAL_SUFFIX[segment]) {\n names.push(STRUCTURAL_SUFFIX[segment]);\n }\n\n index++;\n }\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n return decodeURI(names.join('-'));\n}\n"],"mappings":";;;;;;;;;;;AAMA,SAAgB,gBAAgB,YAAyC;CACvE,IAAI,MAAM;AACV,QAAO,QAAQ,KAAK,QAAQ,IAAI,EAAE;EAEhC,MAAM,aADQ,GAAG,YAAY,IAAI,CACR,QAAQ,SAAS,SAAS,eAAe;AAElE,MAAI,WAAW,IAAI;GACjB,MAAM,kBAAkB,KAAK,KAAK,KAAK,WAAW,GAAG;AACrD,UAAO,KAAK,MACV,GAAG,aAAa,iBAAiB,EAC/B,UAAU,QACX,CAAC,CACH;;AAGH,QAAM,KAAK,QAAQ,IAAI;;;AAc3B,SAAgB,gBAAgB,YAA6C;CAC3E,MAAM,cAAc,gBAAgB,WAAW;CAE/C,MAAMA,cAA2B;EAC/B,MAAM,EACJ,KAAK,IACN;EACD,MAAM;EACN,SAAS;EACV;AAED,KAAI,eAAe,OAAO,gBAAgB,UAAU;AAClD,MAAI,UAAU,eAAe,OAAO,YAAY,SAAS,SACvD,aAAY,OAAO,YAAY;AAGjC,MAAI,aAAa,eAAe,OAAO,YAAY,YAAY,SAC7D,aAAY,UAAU,YAAY;AAGpC,MAAI,UAAU,eAAe,YAAY,QAAQ,OAAO,YAAY,SAAS,UAC3E;OAAI,SAAS,YAAY,QAAQ,OAAO,YAAY,KAAK,QAAQ,UAAU;AACzE,gBAAY,KAAK,MAAM,YAAY,KAAK;AACxC,QAAI,YAAY,KAAK,OAAO,CAAC,YAAY,KAAK,IAAI,SAAS,IAAI,CAC7D,aAAY,KAAK,OAAO;;;;AAMhC,KAAI,CAAC,YAAY,KAAM;AAEvB,QAAO;;AAGT,SAAgB,iBAAiB,SAAiB,cAAgD;AAChG,KAAI,iBAAiB,KACnB,QAAO;AAGT,KAAI,cAAc;EAChB,MAAM,WAAW,KAAK,WAAW,aAAa,GAC1C,eACA,KAAK,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KAAK,QAAQ,OAAO;AAC1B,YAAS,YAAY;QAGrB,MAAK,IAAI,IAAI,GAAG,IAAI,YAAY,SAAS,QAAQA,OAAK,QAAQ,KAAK;AACjE,SAAM,KAAK,gBAAgBA,OAAK,OAAQ,CAAC;AACzC;;YAKA,SAAS,QAAQ;AACnB,QAAM,KAAK,QAAQ,OAAO;AAC1B;YACS,QAAQA,OAAK,QAAQ;AAC9B,QAAM,KAAK,gBAAgBA,OAAK,OAAQ,CAAC;AACzC;;AAIJ,QAAO,QAAQA,OAAK,QAAQ;EAC1B,MAAM,UAAU,OAAOA,OAAK,OAAO;EAEnC,MAAM,OAAO,gBAAgB;AAC7B,MAAI,SAAS,QAAQ;AAEnB;AACA,OAAI,QAAQA,OAAK,OACf,OAAM,KAAK,gBAAgBA,OAAK,OAAQ,CAAC;aAElC,SAAS,SAAS;AAE3B;AACA,OAAI,QAAQA,OAAK,UAAU,OAAOA,OAAK,WAAW,SAChD;AAEF;aACS,kBAAkB,SAC3B,OAAM,KAAK,kBAAkB,SAAS;AAGxC;;AAKF,QAAO,UAAU,MAAM,KAAK,IAAI,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["safePackage: PackageJson","lines: Array<string>","path","registryRegExp","getRegistryUrl","parseShorthand","queryParams: string | undefined","registryRegExp","getRegistryUrl","namespace","parseShorthand","defaultWatch: Watch","inputs: Array<Input>","input: Input","result: Pick<\n Partial<Input>,\n | 'api_key'\n | 'branch'\n | 'commit_sha'\n | 'organization'\n | 'project'\n | 'registry'\n | 'tags'\n | 'version'\n > &\n Pick<Input, 'path'>","path","queryParams: Array<string>","lines: Array<string>","logs: Logs","valueToObject: ValueToObject","mappers","fields","defaultValue","satisfies: typeof semver.satisfies","graph","uniqueItems: Array<IR.SchemaObject>","typeIds: Array<string>","path","result: OperationResponsesMap","errors: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'>","responses: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'>","defaultResponse: IR.ResponseObject | undefined","result: string","path","ir","section","path","entries: Array<[string, string]>","arrayBuffer: ArrayBuffer | undefined","hasChanged: boolean | undefined","response: Response | undefined","declIndex: Map<string, number>","walkDeclarations: WalkFn","graph","walkTopological: WalkFn","order: Array<string>","getGroup: GetPointerPriorityFn","walk: WalkFn","matchIrPointerToGroup: MatchPointerToGroupFn<IrTopLevelKind>","patterns: Record<IrTopLevelKind, RegExp>","kind","kindPriority: KindPriority","partial: Partial<KindPriority>","getIrPointerPriority: GetPointerPriorityFn","path","defaultGetKind: Required<Required<Hooks>['operations']>['getKind']","callback: (event: WalkEvent<TKind>) => void","events: ReadonlyArray<TKind>","options: WalkOptions<TKind>","event: WalkEvent | undefined","baseEvent: BaseEvent","symbolIn: SymbolIn","result: EventHooks","path","contextTags: ReadonlyArray<string> | undefined","contextAnchor: string | undefined","path","walk: Walker<TResult, TPlugin>","walk","namespace","keys: Array<string>","regexps: Array<RegExp>","path","filters: Filters","dependencies: Set<string> | undefined","resourceMetadata: ResourceMetadata","graph","path","namespace","path","walkSchemas","path","rootEnums: Record<string, unknown>","rootEnumSignatures: Record<string, string>","inlineEnums: Array<{\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n signature: string;\n }>","signatureToName: Record<string, string | undefined>","signatureToSchema: Record<string, unknown>","path","graph","childResult: Partial<PointerDependenciesResult>","worklist: Set<string>","graph: Graph","walk","path","deprecated: boolean | undefined","tags: Set<string> | undefined","cache: Cache","path","originals: OriginalSchemas","graph","contextVariant: Scope | null","variants: SplitMapping[keyof SplitMapping]","updatedMapping: Record<string, string>","split: SplitSchemas","deepEqual","walk","renameMap: Record<string, string>","path","filterSpec","filtered: typeof spec.definitions","path","contentToSchema","mediaTypeObjects","objects: Array<Content>","values: Array<string>","getSchemaType","parseSchemaJsDoc","parseSchemaMeta","parseArray","schemaItems: Array<IR.SchemaObject>","schemaToIrSchema","parseBoolean","parseNumber","parseObject","schemaProperties: Record<string, IR.SchemaObject>","parseString","parseExtensions","initIrSchema","irSchema: IR.SchemaObject","parseAllOf","ref","valueSchemas: ReadonlyArray<IR.SchemaObject>","irDiscriminatorSchema: IR.SchemaObject","parseOneType","nestedItems: Array<IR.SchemaObject>","parseEnum","enumType: SchemaType<SchemaObject> | 'null' | undefined","parseRef","irSchema","parseNullableType","typeIrSchema: IR.SchemaObject","parseType","parseUnknown","parseSchema","isPaginationType","paginationField","ref","name","getSchemaType","parseOperationJsDoc","initIrOperation","irOperation: IR.OperationObject","operationToIrOperation","requestBodyObject: IR.BodyObject","requestBodyObjectRequired: Array<string>","schema: SchemaObject","mediaTypeObjects","content","paginationField","schemaToIrSchema","contentToSchema","securitySchemeObjects: Map<string, IR.SecurityObject>","irSecuritySchemeObject: IR.SecurityObject | undefined","parsePathOperation","path","defaultExplode","defaultStyle","parametersArrayToObject","parametersObject: IR.ParametersObject","parameterToIrParameter","finalSchema: SchemaObject","paginationField","irParameter: IR.ParameterObject","schemaToIrSchema","errorResponse: Url","path","parseServers","schemes: ReadonlyArray<string>","path","validateOpenApiSpec","issues: Array<ValidatorIssue>","path","validateOpenApiSpec","graph","state: State","path","commonOperation: OperationObject","operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'>","parametersArrayToObject","filterSpec","filtered: typeof spec.components.parameters","filtered: typeof spec.components.requestBodies","filtered: typeof spec.components.responses","filtered: typeof spec.components.schemas","path","contentToSchema","mediaTypeObjects","objects: Array<Content>","findDiscriminatorPropertyType","findDiscriminatorsInSchema","resolvedSchema: SchemaObject","getAllDiscriminatorValues","values: Array<string>","parseSchemaJsDoc","parseSchemaMeta","parseArray","schemaItems: Array<IR.SchemaObject>","schemaToIrSchema","parseBoolean","parseNumber","parseObject","schemaProperties: Record<string, IR.SchemaObject>","parseString","parseExtensions","initIrSchema","irSchema: IR.SchemaObject","parseAllOf","discriminatorsToAdd: Array<DiscriminatorInfo>","ref","valueSchemas: ReadonlyArray<IR.SchemaObject>","discriminatorProperty: IR.SchemaObject","inlineSchema: IR.SchemaObject | undefined","irDiscriminatorSchema: IR.SchemaObject","parseOneType","nestedItems: Array<IR.SchemaObject>","parseAnyOf","parseEnum","enumType: SchemaType<SchemaObject> | 'null' | undefined","parseOneOf","parseRef","irSchema","typeIrSchema: IR.SchemaObject","parseType","parseUnknown","parseSchema","isPaginationType","paginationField","ref","refSchema: SchemaObject | ReferenceObject | undefined","mediaTypeObjects","content","name","parseOperationJsDoc","initIrOperation","irOperation: IR.OperationObject","operationToIrOperation","mediaTypeObjects","content","paginationField","schemaToIrSchema","contentToSchema","securitySchemeObjects: Map<string, IR.SecurityObject>","parsePathOperation","path","defaultAllowReserved","defaultExplode","defaultStyle","parametersArrayToObject","parametersObject: IR.ParametersObject","parameterToIrParameter","mediaTypeObjects","content","finalSchema: SchemaObject","paginationField","irParameter: IR.ParameterObject","schemaToIrSchema","parseParameter","requestBodyToIrRequestBody","mediaTypeObjects","content","irRequestBody: IR.RequestBodyObject","schemaToIrSchema","parseRequestBody","parseServers","validateOpenApiSpec","issues: Array<ValidatorIssue>","path","validateOpenApiSpec","graph","state: State","path","operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method' | 'operation'> & {\n operation: Omit<Parameters<typeof parsePathOperation>[0]['operation'], 'responses'>;\n }","parametersArrayToObject","filtered: typeof spec.components.parameters","filtered: typeof spec.components.requestBodies","filtered: typeof spec.components.responses","filtered: typeof spec.components.schemas","path","objects: Array<Content>","resolvedSchema: SchemaObject","values: Array<string>","schemaItems: Array<IR.SchemaObject>","schemaProperties: Record<string, IR.SchemaObject>","patternProperties: Record<string, IR.SchemaObject>","irSchema: IR.SchemaObject","discriminatorsToAdd: Array<DiscriminatorInfo>","ref","valueSchemas: ReadonlyArray<IR.SchemaObject>","discriminatorProperty: IR.SchemaObject","inlineSchema: IR.SchemaObject | undefined","irDiscriminatorSchema: IR.SchemaObject","nestedItems: Array<IR.SchemaObject>","enumType: SchemaType<SchemaObject> | undefined","irSchema","irRefSchema: IR.SchemaObject","typeIrSchema: IR.SchemaObject","ref","refSchema: SchemaObject | undefined","content","name","schema","irOperation: IR.OperationObject","content","securitySchemeObjects: Map<string, IR.SecurityObject>","path","parametersObject: IR.ParametersObject","content","finalSchema: SchemaObject","irParameter: IR.ParameterObject","content","irRequestBody: IR.RequestBodyObject","issues: Array<ValidatorIssue>","path","state: Parameters<typeof parseWebhookOperation>[0]['state']","operationArgs: Omit<Parameters<typeof parseWebhookOperation>[0], 'method'>","graph","state: State","path","operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'>","path","STRUCTURAL_ROLE: Record<string, 'name' | 'index'>","STRUCTURAL_SUFFIX: Record<string, string>","ROOT_CONTEXT: Record<string | number, RootContextConfig>","names: Array<string>","path"],"sources":["../src/tsConfig.ts","../src/cli.ts","../src/fs.ts","../src/error.ts","../src/config/engine.ts","../src/utils/input/heyApi.ts","../src/utils/input/readme.ts","../src/utils/input/scalar.ts","../src/utils/input/index.ts","../src/config/input/input.ts","../src/config/input/path.ts","../src/config/logs.ts","../src/config/output/postprocess.ts","../src/config/utils/config.ts","../src/config/output/source/config.ts","../src/config/parser/config.ts","../src/config/utils/dependencies.ts","../src/debug/graph.ts","../src/ir/parameter.ts","../src/ir/schema.ts","../src/ir/utils.ts","../src/ir/operation.ts","../src/utils/naming/naming.ts","../src/openApi/shared/utils/operation.ts","../src/debug/ir.ts","../src/debug/index.ts","../src/getSpec.ts","../src/utils/minHeap.ts","../src/graph/walk.ts","../src/ir/graph.ts","../src/utils/ref.ts","../src/plugins/shared/utils/instance.ts","../src/ir/context.ts","../src/ir/intents.ts","../src/ir/schema-processor.ts","../src/ir/schema-walker.ts","../src/openApi/shared/utils/filter.ts","../src/openApi/shared/graph/meta.ts","../src/openApi/shared/utils/schema.ts","../src/openApi/shared/utils/schemaChildRelationships.ts","../src/openApi/shared/utils/transforms.ts","../src/openApi/shared/transforms/utils.ts","../src/openApi/shared/transforms/enums.ts","../src/openApi/shared/transforms/propertiesRequiredByDefault.ts","../src/openApi/shared/utils/deepEqual.ts","../src/openApi/shared/utils/graph.ts","../src/openApi/shared/transforms/readWrite.ts","../src/openApi/shared/transforms/schemas.ts","../src/openApi/shared/transforms/index.ts","../src/openApi/shared/utils/parameter.ts","../src/openApi/shared/utils/validator.ts","../src/openApi/2.0.x/parser/filter.ts","../src/ir/mediaType.ts","../src/openApi/2.0.x/parser/mediaType.ts","../src/ir/pagination.ts","../src/openApi/shared/utils/discriminator.ts","../src/openApi/2.0.x/parser/schema.ts","../src/openApi/2.0.x/parser/pagination.ts","../src/openApi/2.0.x/parser/operation.ts","../src/openApi/2.0.x/parser/parameter.ts","../src/utils/url.ts","../src/openApi/2.0.x/parser/server.ts","../src/openApi/2.0.x/parser/validate.ts","../src/openApi/2.0.x/parser/index.ts","../src/openApi/3.0.x/parser/filter.ts","../src/openApi/3.0.x/parser/mediaType.ts","../src/openApi/3.0.x/parser/schema.ts","../src/openApi/3.0.x/parser/pagination.ts","../src/openApi/3.0.x/parser/operation.ts","../src/openApi/3.0.x/parser/parameter.ts","../src/openApi/3.0.x/parser/requestBody.ts","../src/openApi/3.0.x/parser/server.ts","../src/openApi/3.0.x/parser/validate.ts","../src/openApi/3.0.x/parser/index.ts","../src/openApi/3.1.x/parser/filter.ts","../src/openApi/3.1.x/parser/mediaType.ts","../src/openApi/3.1.x/parser/schema.ts","../src/openApi/3.1.x/parser/pagination.ts","../src/openApi/3.1.x/parser/operation.ts","../src/openApi/3.1.x/parser/parameter.ts","../src/openApi/3.1.x/parser/requestBody.ts","../src/openApi/3.1.x/parser/server.ts","../src/openApi/3.1.x/parser/validate.ts","../src/openApi/3.1.x/parser/webhook.ts","../src/openApi/3.1.x/parser/index.ts","../src/openApi/index.ts","../src/openApi/shared/locations/operation.ts","../src/openApi/shared/utils/patch.ts","../src/plugins/shared/utils/config.ts","../src/plugins/symbol.ts","../src/utils/escape.ts","../src/utils/exports.ts","../src/utils/header.ts","../src/utils/path.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { AnyString } from '@hey-api/types';\nimport ts from 'typescript';\n\nexport function findPackageJson(initialDir: string): unknown | undefined {\n let dir = initialDir;\n while (dir !== path.dirname(dir)) {\n const files = fs.readdirSync(dir);\n const candidates = files.filter((file) => file === 'package.json');\n\n if (candidates[0]) {\n const packageJsonPath = path.join(dir, candidates[0]);\n return JSON.parse(\n fs.readFileSync(packageJsonPath, {\n encoding: 'utf8',\n }),\n );\n }\n\n dir = path.dirname(dir);\n }\n\n return;\n}\n\ntype PackageJson = {\n bugs: {\n url: string;\n };\n name: string;\n version: string;\n};\n\nexport function loadPackageJson(initialDir: string): PackageJson | undefined {\n const packageJson = findPackageJson(initialDir);\n\n const safePackage: PackageJson = {\n bugs: {\n url: '',\n },\n name: '',\n version: '',\n };\n\n if (packageJson && typeof packageJson === 'object') {\n if ('name' in packageJson && typeof packageJson.name === 'string') {\n safePackage.name = packageJson.name;\n }\n\n if ('version' in packageJson && typeof packageJson.version === 'string') {\n safePackage.version = packageJson.version;\n }\n\n if ('bugs' in packageJson && packageJson.bugs && typeof packageJson.bugs === 'object') {\n if ('url' in packageJson.bugs && typeof packageJson.bugs.url === 'string') {\n safePackage.bugs.url = packageJson.bugs.url;\n if (safePackage.bugs.url && !safePackage.bugs.url.endsWith('/')) {\n safePackage.bugs.url += '/';\n }\n }\n }\n }\n\n if (!safePackage.name) return;\n\n return safePackage;\n}\n\nexport function findTsConfigPath(baseDir: string, tsConfigPath?: AnyString | null): string | null {\n if (tsConfigPath === null) {\n return null;\n }\n\n if (tsConfigPath) {\n const resolved = path.isAbsolute(tsConfigPath)\n ? tsConfigPath\n : path.resolve(baseDir, tsConfigPath);\n return fs.existsSync(resolved) ? resolved : null;\n }\n\n let dir = baseDir;\n while (dir !== path.dirname(dir)) {\n const files = fs.readdirSync(dir);\n const candidates = files\n .filter((file) => file.startsWith('tsconfig') && file.endsWith('.json'))\n .sort((file) => (file === 'tsconfig.json' ? -1 : 1));\n\n if (candidates[0]) {\n return path.join(dir, candidates[0]);\n }\n\n dir = path.dirname(dir);\n }\n\n return null;\n}\n\nexport function loadTsConfig(configPath: string | null): ts.ParsedCommandLine | null {\n if (!configPath) {\n return null;\n }\n\n const raw = ts.readConfigFile(configPath, ts.sys.readFile);\n\n if (raw.error) {\n throw new Error(`Couldn't read tsconfig from path: ${configPath}`);\n }\n\n return ts.parseJsonConfigFileContent(raw.config, ts.sys, path.dirname(configPath));\n}\n","import colors from 'ansi-colors';\n\nimport { loadPackageJson } from './tsConfig';\n\nconst textAscii = `\n888 | e 888~-_ 888\n888___| e88~~8e Y88b / d8b 888 \\\\ 888\n888 | d888 88b Y888/ /Y88b 888 | 888\n888 | 8888__888 Y8/ / Y88b 888 / 888\n888 | Y888 , Y /____Y88b 888_-~ 888\n888 | \"88___/ / / Y88b 888 888\n _/\n`;\n\nconst asciiToLines = (\n ascii: string,\n options?: {\n padding?: number;\n },\n) => {\n const lines: Array<string> = [];\n const padding = Array.from<string>({ length: options?.padding ?? 0 }).fill('');\n lines.push(...padding);\n let maxLineLength = 0;\n let line = '';\n for (const char of ascii) {\n if (char === '\\n') {\n if (line) {\n lines.push(line);\n maxLineLength = Math.max(maxLineLength, line.length);\n line = '';\n }\n } else {\n line += char;\n }\n }\n lines.push(...padding);\n return { lines, maxLineLength };\n};\n\n/**\n * Checks the current environment based on the HEYAPI_CODEGEN_ENV environment variable.\n */\nexport function isEnvironment(value: 'development'): boolean {\n return process.env.HEYAPI_CODEGEN_ENV === value;\n}\n\n// TODO: show ascii logo only in `--help` and `--version` commands\nexport function printCliIntro(initialDir: string, showLogo: boolean = false): void {\n const packageJson = loadPackageJson(initialDir);\n if (packageJson) {\n if (showLogo) {\n const text = asciiToLines(textAscii, { padding: 1 });\n for (const line of text.lines) {\n console.log(colors.cyan(line));\n }\n }\n const versionString = isEnvironment('development')\n ? '[DEVELOPMENT]'\n : `v${packageJson.version}`;\n console.log(colors.gray(`${packageJson.name} ${versionString}`));\n }\n console.log('');\n}\n","import type { PathLike } from 'node:fs';\nimport fs from 'node:fs';\n\nexport function ensureDirSync(path: PathLike): void {\n if (!fs.existsSync(path)) {\n fs.mkdirSync(path, { recursive: true });\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport colors from 'ansi-colors';\n\nimport { ensureDirSync } from './fs';\nimport { loadPackageJson } from './tsConfig';\n\ntype IJobError = {\n error: Error;\n jobIndex: number;\n};\n\n/**\n * Represents a single configuration error.\n *\n * Used for reporting issues with a specific config instance.\n */\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Aggregates multiple config errors with their job indices for reporting.\n */\nexport class ConfigValidationError extends Error {\n readonly errors: ReadonlyArray<IJobError>;\n\n constructor(errors: Array<IJobError>) {\n super(`Found ${errors.length} configuration ${errors.length === 1 ? 'error' : 'errors'}.`);\n this.name = 'ConfigValidationError';\n this.errors = errors;\n }\n}\n\n/**\n * Represents a runtime error originating from a specific job.\n *\n * Used for reporting job-level failures that are not config validation errors.\n */\nexport class JobError extends Error {\n readonly originalError: IJobError;\n\n constructor(message: string, error: IJobError) {\n super(message);\n this.name = 'JobError';\n this.originalError = error;\n }\n}\n\nexport class HeyApiError extends Error {\n args: ReadonlyArray<unknown>;\n event: string;\n pluginName: string;\n\n constructor({\n args,\n error,\n event,\n name,\n pluginName,\n }: {\n args: unknown[];\n error: Error;\n event: string;\n name: string;\n pluginName: string;\n }) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n super(message);\n\n this.args = args;\n this.cause = error.cause;\n this.event = event;\n this.name = name || error.name;\n this.pluginName = pluginName;\n this.stack = error.stack;\n }\n}\n\nexport function logCrashReport(error: unknown, logsDir: string): string | undefined {\n if (error instanceof ConfigError || error instanceof ConfigValidationError) {\n return;\n }\n\n if (error instanceof JobError) {\n error = error.originalError.error;\n }\n\n const logName = `openapi-ts-error-${Date.now()}.log`;\n const fullDir = path.resolve(process.cwd(), logsDir);\n ensureDirSync(fullDir);\n const logPath = path.resolve(fullDir, logName);\n\n let logContent = `[${new Date().toISOString()}] `;\n\n if (error instanceof HeyApiError) {\n logContent += `${error.name} during event \"${error.event}\"\\n`;\n if (error.pluginName) {\n logContent += `Plugin: ${error.pluginName}\\n`;\n }\n logContent += `Arguments: ${JSON.stringify(error.args, null, 2)}\\n\\n`;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n logContent += `Error: ${message}\\n`;\n if (stack) {\n logContent += `Stack:\\n${stack}\\n`;\n }\n\n fs.writeFileSync(logPath, logContent);\n\n return logPath;\n}\n\nexport async function openGitHubIssueWithCrashReport(\n error: unknown,\n initialDir: string,\n): Promise<void> {\n const packageJson = loadPackageJson(initialDir);\n if (!packageJson?.bugs.url) return;\n\n if (error instanceof JobError) {\n error = error.originalError.error;\n }\n\n let body = '';\n\n if (error instanceof HeyApiError) {\n if (error.pluginName) {\n body += `**Plugin**: \\`${error.pluginName}\\`\\n`;\n }\n body += `**Event**: \\`${error.event}\\`\\n`;\n body += `**Arguments**:\\n\\`\\`\\`ts\\n${JSON.stringify(error.args, null, 2)}\\n\\`\\`\\`\\n\\n`;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n const stack = error instanceof Error ? error.stack : undefined;\n\n body += `**Error**: \\`${message}\\`\\n`;\n if (stack) {\n body += `\\n**Stack Trace**:\\n\\`\\`\\`\\n${stack}\\n\\`\\`\\``;\n }\n\n const search = new URLSearchParams({\n body,\n labels: 'bug ๐Ÿ”ฅ',\n title: 'Crash Report',\n });\n const url = `${packageJson.bugs.url}new?${search.toString()}`;\n const open = (await import('open')).default;\n await open(url);\n}\n\nexport function printCrashReport({\n error,\n logPath,\n}: {\n error: unknown;\n logPath: string | undefined;\n}): void {\n if (error instanceof ConfigValidationError && error.errors.length) {\n const groupByJob = new Map<number, Array<Error>>();\n for (const { error: err, jobIndex } of error.errors) {\n if (!groupByJob.has(jobIndex)) {\n groupByJob.set(jobIndex, []);\n }\n groupByJob.get(jobIndex)!.push(err);\n }\n\n for (const [jobIndex, errors] of groupByJob.entries()) {\n const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `);\n const count = errors.length;\n const baseString = colors.red(\n `Found ${count} configuration ${count === 1 ? 'error' : 'errors'}:`,\n );\n console.error(`${jobPrefix}โ—๏ธ ${baseString}`);\n errors.forEach((err, index) => {\n const itemPrefixStr = ` [${index + 1}] `;\n const itemPrefix = colors.red(itemPrefixStr);\n console.error(`${jobPrefix}${itemPrefix}${colors.white(err.message)}`);\n });\n }\n } else {\n let jobPrefix = colors.gray('[root] ');\n if (error instanceof JobError) {\n jobPrefix = colors.gray(`[Job ${error.originalError.jobIndex + 1}] `);\n error = error.originalError.error;\n }\n\n const baseString = colors.red('Failed with the message:');\n console.error(`${jobPrefix}โŒ ${baseString}`);\n const itemPrefixStr = ` `;\n const itemPrefix = colors.red(itemPrefixStr);\n console.error(\n `${jobPrefix}${itemPrefix}${typeof error === 'string' ? error : error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n\n if (logPath) {\n const jobPrefix = colors.gray('[root] ');\n console.error(`${jobPrefix}${colors.cyan('๐Ÿ“„ Crash log saved to:')} ${colors.gray(logPath)}`);\n }\n}\n\nexport async function shouldReportCrash({\n error,\n isInteractive,\n}: {\n error: unknown;\n isInteractive: boolean | undefined;\n}): Promise<boolean> {\n if (!isInteractive || error instanceof ConfigError || error instanceof ConfigValidationError) {\n return false;\n }\n\n return new Promise((resolve) => {\n const jobPrefix = colors.gray('[root] ');\n console.log(\n `${jobPrefix}${colors.yellow('๐Ÿ“ข Open a GitHub issue with crash details? (y/N):')}`,\n );\n process.stdin.setEncoding('utf8');\n process.stdin.once('data', (data: string) => {\n resolve(data.trim().toLowerCase() === 'y');\n });\n });\n}\n","import { ConfigError } from '../error';\n\nexport function checkNodeVersion(): void {\n if (typeof Bun !== 'undefined') {\n const [major] = Bun.version.split('.').map(Number);\n if (major! < 1) {\n throw new ConfigError(\n `Unsupported Bun version ${Bun.version}. Please use Bun 1.0.0 or newer.`,\n );\n }\n } else if (typeof process !== 'undefined' && process.versions?.node) {\n const [major] = process.versions.node.split('.').map(Number);\n if (major! < 20) {\n throw new ConfigError(\n `Unsupported Node version ${process.versions.node}. Please use Node 20 or newer.`,\n );\n }\n }\n}\n","import type { Input } from '../../config/input/types';\n\n// Regular expression to match Hey API Registry input formats:\n// - {organization}/{project}?{queryParams}\nconst registryRegExp = /^([\\w-]+)\\/([\\w-]+)(?:\\?([\\w=&.-]*))?$/;\n\nexport const heyApiRegistryBaseUrl = 'https://get.heyapi.dev';\n\n/**\n * Creates a full Hey API Registry URL.\n *\n * @param organization - Hey API organization slug\n * @param project - Hey API project slug\n * @param queryParams - Optional query parameters\n * @returns The full Hey API registry URL.\n */\nexport function getRegistryUrl(\n organization: string,\n project: string,\n queryParams?: string,\n): string {\n return `${heyApiRegistryBaseUrl}/${organization}/${project}${queryParams ? `?${queryParams}` : ''}`;\n}\n\nexport type Parsed = {\n organization: string;\n project: string;\n queryParams?: string;\n};\n\n/**\n * Parses a Hey API input string and extracts components.\n *\n * @param input - Hey API configuration input\n * @returns Parsed Hey API input components\n * @throws Error if the input format is invalid\n */\nexport function parseShorthand(\n input: Input & {\n path: string;\n },\n): Parsed {\n let organization = input.organization;\n let project = input.project;\n let queryParams: string | undefined;\n\n if (input.path) {\n const match = input.path.match(registryRegExp);\n\n if (!match) {\n throw new Error(\n `Invalid Hey API shorthand format. Expected \"organization/project?queryParams\" or \"organization/project\", received: ${input.path}`,\n );\n }\n\n organization = match[1];\n project = match[2];\n queryParams = match[3];\n }\n\n if (!organization) {\n throw new Error('The Hey API organization cannot be empty.');\n }\n\n if (!project) {\n throw new Error('The Hey API project cannot be empty.');\n }\n\n const result: Parsed = {\n organization,\n project,\n queryParams,\n };\n\n return result;\n}\n\n/**\n * Transforms a Hey API shorthand string to the corresponding API URL.\n *\n * @param input - Hey API configuration input\n * @returns The Hey API Registry URL\n */\nexport function inputToHeyApiPath(\n input: Input & {\n path: string;\n },\n): Partial<Input> {\n const parsed = parseShorthand(input);\n return {\n path: getRegistryUrl(parsed.organization, parsed.project, parsed.queryParams),\n registry: 'hey-api',\n };\n}\n","import type { Input } from '../../config/input/types';\n\n// Regular expression to match ReadMe API Registry input formats:\n// - @{organization}/{project}#{uuid}\n// - {uuid}\nconst registryRegExp = /^(@([\\w-]+)\\/([\\w\\-.]+)#)?([\\w-]+)$/;\n\n/**\n * Creates a full ReadMe API Registry URL.\n *\n * @param uuid - ReadMe UUID\n * @returns The full ReadMe API registry URL.\n */\nexport function getRegistryUrl(uuid: string): string {\n return `https://dash.readme.com/api/v1/api-registry/${uuid}`;\n}\n\nexport type Parsed = {\n organization?: string;\n project?: string;\n uuid: string;\n};\n\nconst namespace = 'readme';\n\n/**\n * Parses a ReadMe input string and extracts components.\n *\n * @param shorthand - ReadMe format string (@org/project#uuid or uuid)\n * @returns Parsed ReadMe input components\n * @throws Error if the input format is invalid\n */\nexport function parseShorthand(shorthand: string): Parsed {\n const match = shorthand.match(registryRegExp);\n\n if (!match) {\n throw new Error(\n `Invalid ReadMe shorthand format. Expected \"${namespace}:@organization/project#uuid\" or \"${namespace}:uuid\", received: ${namespace}:${shorthand}`,\n );\n }\n\n const [, , organization, project, uuid] = match;\n\n if (!uuid) {\n throw new Error('The ReadMe UUID cannot be empty.');\n }\n\n const result: Parsed = {\n organization,\n project,\n uuid,\n };\n\n return result;\n}\n\n/**\n * Transforms a ReadMe shorthand string to the corresponding API URL.\n *\n * @param input - ReadMe format string\n * @returns The ReadMe API Registry URL\n */\nexport function inputToReadmePath(input: string): Partial<Input> {\n const shorthand = input.slice(`${namespace}:`.length);\n const parsed = parseShorthand(shorthand);\n return {\n ...parsed,\n path: getRegistryUrl(parsed.uuid),\n registry: 'readme',\n };\n}\n","import type { Input } from '../../config/input/types';\n\n// Regular expression to match Scalar API Registry input formats:\n// - @{organization}/{project}\nconst registryRegExp = /^(@[\\w-]+)\\/([\\w.-]+)$/;\n\n/**\n * Creates a full Scalar API Registry URL.\n *\n * @param organization - Scalar organization slug\n * @param project - Scalar project slug\n * @returns The full Scalar API registry URL.\n */\nexport function getRegistryUrl(organization: string, project: string): string {\n return `https://registry.scalar.com/${organization}/apis/${project}/latest?format=json`;\n}\n\nexport type Parsed = {\n organization: string;\n project: string;\n};\n\nconst namespace = 'scalar';\n\n/**\n * Parses a Scalar input string and extracts components.\n *\n * @param shorthand - Scalar format string (@org/project)\n * @returns Parsed Scalar input components\n * @throws Error if the input format is invalid\n */\nexport function parseShorthand(shorthand: string): Parsed {\n const match = shorthand.match(registryRegExp);\n\n if (!match) {\n throw new Error(\n `Invalid Scalar shorthand format. Expected \"${namespace}:@organization/project\", received: ${namespace}:${shorthand}`,\n );\n }\n\n const [, organization, project] = match;\n\n if (!organization) {\n throw new Error('The Scalar organization cannot be empty.');\n }\n\n if (!project) {\n throw new Error('The Scalar project cannot be empty.');\n }\n\n const result: Parsed = {\n organization,\n project,\n };\n\n return result;\n}\n\n/**\n * Transforms a Scalar shorthand string to the corresponding API URL.\n *\n * @param input - Scalar format string\n * @returns The Scalar API Registry URL\n */\nexport function inputToScalarPath(input: string): Partial<Input> {\n const shorthand = input.slice(`${namespace}:`.length);\n const parsed = parseShorthand(shorthand);\n return {\n ...parsed,\n path: getRegistryUrl(parsed.organization, parsed.project),\n registry: 'scalar',\n };\n}\n","import type { Input } from '../../config/input/types';\nimport { heyApiRegistryBaseUrl, inputToHeyApiPath } from './heyApi';\nimport { inputToReadmePath } from './readme';\nimport { inputToScalarPath } from './scalar';\n\nexport function inputToApiRegistry(\n input: Input & {\n path: string;\n },\n) {\n if (input.path.startsWith('readme:')) {\n Object.assign(input, inputToReadmePath(input.path));\n return;\n }\n\n if (input.path.startsWith('scalar:')) {\n Object.assign(input, inputToScalarPath(input.path));\n return;\n }\n\n if (input.path.startsWith('.')) {\n return;\n }\n\n if (input.path.startsWith(heyApiRegistryBaseUrl)) {\n input.path = input.path.slice(heyApiRegistryBaseUrl.length + 1);\n Object.assign(input, inputToHeyApiPath(input as Input & { path: string }));\n return;\n }\n\n const parts = input.path.split('/');\n if (parts.length === 2 && parts.filter(Boolean).length === 2) {\n Object.assign(input, inputToHeyApiPath(input as Input & { path: string }));\n return;\n }\n}\n","import type { MaybeArray } from '@hey-api/types';\n\nimport { inputToApiRegistry } from '../../utils/input';\nimport { heyApiRegistryBaseUrl } from '../../utils/input/heyApi';\nimport type { Input, UserInput, UserWatch, Watch } from './types';\n\nconst defaultWatch: Watch = {\n enabled: false,\n interval: 1_000,\n timeout: 60_000,\n};\n\n// watch only remote files\nfunction getWatch(input: Pick<Input, 'path' | 'watch'>): Watch {\n let watch = { ...defaultWatch };\n\n // we cannot watch spec passed as an object\n if (typeof input.path !== 'string') {\n return watch;\n }\n\n if (typeof input.watch === 'boolean') {\n watch.enabled = input.watch;\n } else if (typeof input.watch === 'number') {\n watch.enabled = true;\n watch.interval = input.watch;\n } else if (input.watch) {\n watch = {\n ...watch,\n ...input.watch,\n };\n }\n\n return watch;\n}\n\nexport function getInput(userConfig: {\n input: MaybeArray<UserInput | Required<UserInput>['path']>;\n watch?: UserWatch;\n}): ReadonlyArray<Input> {\n const userInputs = userConfig.input instanceof Array ? userConfig.input : [userConfig.input];\n\n const inputs: Array<Input> = [];\n\n for (const userInput of userInputs) {\n let input: Input = {\n path: '',\n watch: defaultWatch,\n };\n\n if (typeof userInput === 'string') {\n input.path = userInput;\n } else if (\n userInput &&\n (userInput.path !== undefined || userInput.organization !== undefined)\n ) {\n // @ts-expect-error\n input = {\n ...input,\n path: heyApiRegistryBaseUrl,\n ...userInput,\n };\n\n if (input.watch !== undefined) {\n input.watch = getWatch(input);\n }\n } else {\n input = {\n ...input,\n path: userInput,\n };\n }\n\n if (typeof input.path === 'string') {\n inputToApiRegistry(input as Input & { path: string });\n }\n\n if (\n userConfig.watch !== undefined &&\n input.watch.enabled === defaultWatch.enabled &&\n input.watch.interval === defaultWatch.interval &&\n input.watch.timeout === defaultWatch.timeout\n ) {\n input.watch = getWatch({\n path: input.path,\n // @ts-expect-error\n watch: userConfig.watch,\n });\n }\n\n if (input.path) {\n inputs.push(input);\n }\n }\n\n return inputs;\n}\n","import colors from 'ansi-colors';\n\nimport type { Input } from './types';\n\nexport function compileInputPath(input: Omit<Input, 'watch'>) {\n const result: Pick<\n Partial<Input>,\n | 'api_key'\n | 'branch'\n | 'commit_sha'\n | 'organization'\n | 'project'\n | 'registry'\n | 'tags'\n | 'version'\n > &\n Pick<Input, 'path'> = {\n ...input,\n path: '',\n };\n\n if (input.path && (typeof input.path !== 'string' || input.registry !== 'hey-api')) {\n result.path = input.path;\n return result;\n }\n\n const [basePath, baseQuery] = input.path.split('?');\n const queryParts = (baseQuery || '').split('&');\n const queryPath = queryParts.map((part) => part.split('='));\n\n let path = basePath || '';\n if (path.endsWith('/')) {\n path = path.slice(0, path.length - 1);\n }\n\n const [, pathUrl] = path.split('://');\n const [baseUrl, organization, project] = (pathUrl || '').split('/');\n result.organization = organization || input.organization;\n result.project = project || input.project;\n\n const queryParams: Array<string> = [];\n\n const kApiKey = 'api_key';\n result.api_key =\n queryPath.find(([key]) => key === kApiKey)?.[1] || input.api_key || process.env.HEY_API_TOKEN;\n if (result.api_key) {\n queryParams.push(`${kApiKey}=${result.api_key}`);\n }\n\n const kBranch = 'branch';\n result.branch = queryPath.find(([key]) => key === kBranch)?.[1] || input.branch;\n if (result.branch) {\n queryParams.push(`${kBranch}=${result.branch}`);\n }\n\n const kCommitSha = 'commit_sha';\n result.commit_sha = queryPath.find(([key]) => key === kCommitSha)?.[1] || input.commit_sha;\n if (result.commit_sha) {\n queryParams.push(`${kCommitSha}=${result.commit_sha}`);\n }\n\n const kTags = 'tags';\n result.tags = queryPath.find(([key]) => key === kTags)?.[1]?.split(',') || input.tags;\n if (result.tags?.length) {\n queryParams.push(`${kTags}=${result.tags.join(',')}`);\n }\n\n const kVersion = 'version';\n result.version = queryPath.find(([key]) => key === kVersion)?.[1] || input.version;\n if (result.version) {\n queryParams.push(`${kVersion}=${result.version}`);\n }\n\n if (!result.organization) {\n throw new Error(\n 'missing organization - from which Hey API Platform organization do you want to generate your output?',\n );\n }\n\n if (!result.project) {\n throw new Error(\n 'missing project - from which Hey API Platform project do you want to generate your output?',\n );\n }\n\n const query = queryParams.join('&');\n const platformUrl = baseUrl || 'get.heyapi.dev';\n const isLocalhost = platformUrl.startsWith('localhost');\n const platformUrlWithProtocol = [isLocalhost ? 'http' : 'https', platformUrl].join('://');\n const compiledPath = isLocalhost\n ? [platformUrlWithProtocol, 'v1', 'get', result.organization, result.project].join('/')\n : [platformUrlWithProtocol, result.organization, result.project].join('/');\n result.path = query ? `${compiledPath}?${query}` : compiledPath;\n\n return result;\n}\n\nexport function logInputPaths(\n inputPaths: ReadonlyArray<ReturnType<typeof compileInputPath>>,\n jobIndex: number,\n): void {\n const lines: Array<string> = [];\n\n const jobPrefix = colors.gray(`[Job ${jobIndex + 1}] `);\n const count = inputPaths.length;\n const baseString = colors.cyan(`Generating from ${count} ${count === 1 ? 'input' : 'inputs'}:`);\n lines.push(`${jobPrefix}โณ ${baseString}`);\n\n inputPaths.forEach((inputPath, index) => {\n const itemPrefixStr = ` [${index + 1}] `;\n const itemPrefix = colors.cyan(itemPrefixStr);\n const detailIndent = ' '.repeat(itemPrefixStr.length);\n\n if (typeof inputPath.path !== 'string') {\n lines.push(`${jobPrefix}${itemPrefix}raw OpenAPI specification`);\n return;\n }\n\n switch (inputPath.registry) {\n case 'hey-api': {\n const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/');\n lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);\n if (inputPath.branch) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('branch:')} ${colors.green(\n inputPath.branch,\n )}`,\n );\n }\n if (inputPath.commit_sha) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('commit:')} ${colors.green(\n inputPath.commit_sha,\n )}`,\n );\n }\n if (inputPath.tags?.length) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('tags:')} ${colors.green(\n inputPath.tags.join(', '),\n )}`,\n );\n }\n if (inputPath.version) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('version:')} ${colors.green(\n inputPath.version,\n )}`,\n );\n }\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('Hey API')}`,\n );\n break;\n }\n case 'readme': {\n const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/');\n if (!baseInput) {\n lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`);\n } else {\n lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);\n }\n // @ts-expect-error\n if (inputPath.uuid) {\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('uuid:')} ${colors.green(\n // @ts-expect-error\n inputPath.uuid,\n )}`,\n );\n }\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('ReadMe')}`,\n );\n break;\n }\n case 'scalar': {\n const baseInput = [inputPath.organization, inputPath.project].filter(Boolean).join('/');\n lines.push(`${jobPrefix}${itemPrefix}${baseInput}`);\n lines.push(\n `${jobPrefix}${detailIndent}${colors.gray('registry:')} ${colors.green('Scalar')}`,\n );\n break;\n }\n default:\n lines.push(`${jobPrefix}${itemPrefix}${inputPath.path}`);\n break;\n }\n });\n\n for (const line of lines) {\n console.log(line);\n }\n}\n","import type { Logs } from '../types/logs';\n\nexport function getLogs(userLogs: string | Logs | undefined): Logs {\n let logs: Logs = {\n file: true,\n level: 'info',\n path: process.cwd(),\n };\n\n if (typeof userLogs === 'string') {\n logs.path = userLogs;\n } else {\n logs = {\n ...logs,\n ...userLogs,\n };\n }\n\n return logs;\n}\n","import colors from 'ansi-colors';\nimport { sync } from 'cross-spawn';\n\ntype Output = {\n /**\n * The absolute path to the output folder.\n */\n path: string;\n /**\n * Post-processing commands to run on the output folder, executed in order.\n */\n postProcess: ReadonlyArray<string | UserPostProcessor>;\n};\n\nexport type UserPostProcessor = {\n /**\n * Arguments to pass to the command. Use `{{path}}` as a placeholder\n * for the output directory path.\n *\n * @example ['format', '--write', '{{path}}']\n */\n args: ReadonlyArray<string>;\n /**\n * The command to run (e.g., 'biome', 'prettier', 'eslint').\n */\n command: string;\n /**\n * Display name for logging. Defaults to the command name.\n */\n name?: string;\n};\n\nexport type PostProcessor = {\n /**\n * Arguments to pass to the command.\n */\n args: ReadonlyArray<string>;\n /**\n * The command to run.\n */\n command: string;\n /**\n * Display name for logging.\n */\n name: string;\n};\n\nexport function postprocessOutput(\n config: Output,\n postProcessors: Record<string, PostProcessor>,\n jobPrefix: string,\n): void {\n for (const processor of config.postProcess) {\n const resolved = typeof processor === 'string' ? postProcessors[processor] : processor;\n\n // TODO: show warning\n if (!resolved) continue;\n\n const name = resolved.name ?? resolved.command;\n const args = resolved.args.map((arg) => arg.replace('{{path}}', config.path));\n\n console.log(`${jobPrefix}๐Ÿงน Running ${colors.cyanBright(name)}`);\n sync(resolved.command, args);\n }\n}\n","type ObjectType<T> =\n Extract<T, Record<string, any>> extends never\n ? Record<string, any>\n : Extract<T, Record<string, any>>;\n\ntype NotArray<T> = T extends Array<any> ? never : T;\ntype NotFunction<T> = T extends (...args: Array<any>) => any ? never : T;\ntype PlainObject<T> = T extends object\n ? NotFunction<T> extends never\n ? never\n : NotArray<T> extends never\n ? never\n : T\n : never;\n\ntype MappersType<T> = {\n boolean: T extends boolean ? (value: boolean) => Partial<ObjectType<T>> : never;\n function: T extends (...args: Array<any>) => any\n ? (value: (...args: Array<any>) => any) => Partial<ObjectType<T>>\n : never;\n number: T extends number ? (value: number) => Partial<ObjectType<T>> : never;\n object?: PlainObject<T> extends never\n ? never\n : (value: Partial<PlainObject<T>>, defaultValue: PlainObject<T>) => Partial<ObjectType<T>>;\n string: T extends string ? (value: string) => Partial<ObjectType<T>> : never;\n} extends infer U\n ? { [K in keyof U as U[K] extends never ? never : K]: U[K] }\n : never;\n\ntype IsObjectOnly<T> = T extends Record<string, any> | undefined\n ? Extract<T, string | boolean | number | ((...args: Array<any>) => any)> extends never\n ? true\n : false\n : false;\n\nexport type ValueToObject = <\n T extends\n | undefined\n | string\n | boolean\n | number\n | ((...args: Array<any>) => any)\n | Record<string, any>,\n>(\n args: {\n defaultValue: ObjectType<T>;\n value: T;\n } & (IsObjectOnly<T> extends true\n ? {\n mappers?: MappersType<T>;\n }\n : {\n mappers: MappersType<T>;\n }),\n) => PlainObject<T>;\n\nconst isPlainObject = (value: unknown): value is Record<string, any> =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n typeof value !== 'function';\n\nconst mergeResult = <T>(result: ObjectType<T>, mapped: Record<string, any>): ObjectType<T> => {\n for (const [key, value] of Object.entries(mapped)) {\n if (value !== undefined && value !== '') {\n (result as Record<string, any>)[key] = value;\n }\n }\n return result;\n};\n\nexport const valueToObject: ValueToObject = ({ defaultValue, mappers, value }) => {\n let result = { ...defaultValue };\n\n switch (typeof value) {\n case 'boolean':\n if (mappers && 'boolean' in mappers) {\n const mapper = mappers.boolean as (value: boolean) => Record<string, any>;\n result = mergeResult(result, mapper(value));\n }\n break;\n case 'function':\n if (mappers && 'function' in mappers) {\n const mapper = mappers.function as (\n value: (...args: Array<any>) => any,\n ) => Record<string, any>;\n result = mergeResult(result, mapper(value as (...args: Array<any>) => any));\n }\n break;\n case 'number':\n if (mappers && 'number' in mappers) {\n const mapper = mappers.number as (value: number) => Record<string, any>;\n result = mergeResult(result, mapper(value));\n }\n break;\n case 'string':\n if (mappers && 'string' in mappers) {\n const mapper = mappers.string as (value: string) => Record<string, any>;\n result = mergeResult(result, mapper(value));\n }\n break;\n case 'object':\n if (isPlainObject(value)) {\n if (mappers && 'object' in mappers && typeof mappers.object === 'function') {\n const mapper = mappers.object as (\n value: Record<string, any>,\n defaultValue: ObjectType<any>,\n ) => Partial<ObjectType<any>>;\n result = mergeResult(result, mapper(value, defaultValue));\n } else {\n result = mergeResult(result, value);\n }\n }\n break;\n }\n\n return result as any;\n};\n","import { valueToObject } from '../../utils/config';\nimport type { SourceConfig, UserSourceConfig } from './types';\n\nexport function resolveSource(config: { source?: boolean | UserSourceConfig }): SourceConfig {\n const source = valueToObject({\n defaultValue: {\n enabled: Boolean(config.source),\n extension: 'json',\n fileName: 'source',\n serialize: (input) => JSON.stringify(input, null, 2),\n },\n mappers: {\n boolean: (enabled) => ({ enabled }),\n },\n value: config.source,\n });\n if (source.path === undefined || source.path === true) {\n source.path = '';\n } else if (source.path === false) {\n source.path = null;\n }\n return source as SourceConfig;\n}\n","import { valueToObject } from '../utils/config';\nimport type { Parser, UserParser } from './types';\n\nexport const defaultPaginationKeywords = [\n 'after',\n 'before',\n 'cursor',\n 'offset',\n 'page',\n 'start',\n] as const;\n\nexport function getParser(userConfig: { parser?: UserParser }): Parser {\n const parser = valueToObject({\n defaultValue: {\n hooks: {},\n pagination: {\n keywords: defaultPaginationKeywords,\n },\n transforms: {\n enums: {\n case: 'PascalCase',\n enabled: false,\n mode: 'root',\n name: '{{name}}Enum',\n },\n propertiesRequiredByDefault: false,\n readWrite: {\n enabled: true,\n requests: {\n case: 'preserve',\n name: '{{name}}Writable',\n },\n responses: {\n case: 'preserve',\n name: '{{name}}',\n },\n },\n schemaName: undefined,\n },\n validate_EXPERIMENTAL: false,\n },\n mappers: {\n object: (fields, defaultValue) => ({\n ...fields,\n pagination: valueToObject({\n defaultValue: {\n ...(defaultValue.pagination as Extract<\n typeof defaultValue.pagination,\n Record<string, unknown>\n >),\n },\n value: fields.pagination,\n }),\n transforms: valueToObject({\n defaultValue: {\n ...(defaultValue.transforms as Extract<\n typeof defaultValue.transforms,\n Record<string, unknown>\n >),\n },\n mappers: {\n object: (fields, defaultValue) => ({\n ...fields,\n enums: valueToObject({\n defaultValue: {\n ...(defaultValue.enums as Extract<\n typeof defaultValue.enums,\n Record<string, unknown>\n >),\n enabled:\n fields.enums !== undefined\n ? Boolean(fields.enums)\n : (\n defaultValue.enums as Extract<\n typeof defaultValue.enums,\n Record<string, unknown>\n >\n ).enabled,\n },\n mappers: {\n boolean: (enabled) => ({ enabled }),\n string: (mode) => ({ mode }),\n },\n value: fields.enums,\n }),\n propertiesRequiredByDefault:\n fields.propertiesRequiredByDefault !== undefined\n ? fields.propertiesRequiredByDefault\n : defaultValue.propertiesRequiredByDefault,\n readWrite: valueToObject({\n defaultValue: {\n ...(defaultValue.readWrite as Extract<\n typeof defaultValue.readWrite,\n Record<string, unknown>\n >),\n enabled:\n fields.readWrite !== undefined\n ? Boolean(fields.readWrite)\n : (\n defaultValue.readWrite as Extract<\n typeof defaultValue.readWrite,\n Record<string, unknown>\n >\n ).enabled,\n },\n mappers: {\n boolean: (enabled) => ({ enabled }),\n object: (fields, defaultValue) => ({\n ...fields,\n requests: valueToObject({\n defaultValue: {\n ...(defaultValue.requests as Extract<\n typeof defaultValue.requests,\n Record<string, unknown>\n >),\n },\n mappers: {\n function: (name) => ({ name }),\n string: (name) => ({ name }),\n },\n value: fields.requests,\n }),\n responses: valueToObject({\n defaultValue: {\n ...(defaultValue.responses as Extract<\n typeof defaultValue.responses,\n Record<string, unknown>\n >),\n },\n mappers: {\n function: (name) => ({ name }),\n string: (name) => ({ name }),\n },\n value: fields.responses,\n }),\n }),\n },\n value: fields.readWrite,\n }),\n schemaName:\n fields.schemaName !== undefined ? fields.schemaName : defaultValue.schemaName,\n }),\n },\n value: fields.transforms,\n }),\n validate_EXPERIMENTAL:\n fields.validate_EXPERIMENTAL === true ? 'warn' : fields.validate_EXPERIMENTAL,\n }),\n },\n value: userConfig.parser,\n });\n return parser as Parser;\n}\n","import type { RangeOptions, SemVer } from 'semver';\nimport * as semver from 'semver';\n\nexport type Dependency = {\n /**\n * Get the installed version of a package.\n * @param name The name of the package to get the version for.\n * @returns A SemVer object containing version information, or undefined if the package is not installed\n * or the version string is invalid.\n */\n getVersion: (name: string) => SemVer | undefined;\n /**\n * Check if a given package is installed in the project.\n * @param name The name of the package to check.\n */\n isInstalled: (name: string) => boolean;\n /**\n * Check if the installed version of a package or a given SemVer object satisfies a semver range.\n * @param nameOrVersion The name of the package to check, or a SemVer object.\n * @param range The semver range to check against.\n * @returns True if the version satisfies the range, false otherwise.\n */\n satisfies: (\n nameOrVersion: string | SemVer,\n range: string,\n optionsOrLoose?: boolean | RangeOptions,\n ) => boolean;\n};\n\nexport const satisfies: typeof semver.satisfies = (...args) => semver.satisfies(...args);\n\nexport function dependencyFactory(dependencies: Record<string, string>): Dependency {\n return {\n getVersion: (name) => {\n const version = dependencies[name];\n if (!version) return;\n try {\n let parsed = semver.parse(version);\n if (parsed) return parsed;\n\n const min = semver.minVersion(version);\n if (min) return min;\n\n parsed = semver.coerce(version);\n if (parsed) return parsed;\n } catch {\n // noop\n }\n return;\n },\n isInstalled: (name) => Boolean(dependencies[name]),\n satisfies: (nameOrVersion, range, optionsOrLoose) => {\n const version =\n typeof nameOrVersion === 'string' ? dependencies[nameOrVersion] : nameOrVersion;\n return version ? satisfies(version, range, optionsOrLoose) : false;\n },\n };\n}\n","import type { Graph } from '../graph';\n\nconst analyzeStructure = (graph: Graph) => {\n let maxDepth = 0;\n let maxChildren = 0;\n\n const computeDepth = (pointer: string, depth: number): void => {\n maxDepth = Math.max(maxDepth, depth);\n\n const children = Array.from(graph.nodes.entries())\n .filter(([, nodeInfo]) => nodeInfo.parentPointer === pointer)\n .map(([childPointer]) => childPointer);\n\n maxChildren = Math.max(maxChildren, children.length);\n\n for (const childPointer of children) {\n computeDepth(childPointer, depth + 1);\n }\n };\n\n const totalNodes = graph.nodes.size;\n if (graph.nodes.has('#')) {\n computeDepth('#', 1);\n }\n\n return { maxChildren, maxDepth, totalNodes };\n};\n\nconst exportForVisualization = (graph: Graph) => {\n const childrenMap = new Map<string, string[]>();\n\n for (const [pointer, nodeInfo] of graph.nodes) {\n if (!nodeInfo.parentPointer) continue;\n if (!childrenMap.has(nodeInfo.parentPointer)) {\n childrenMap.set(nodeInfo.parentPointer, []);\n }\n childrenMap.get(nodeInfo.parentPointer)!.push(pointer);\n }\n\n const nodes = Array.from(graph.nodes.keys()).map((pointer) => ({\n children: childrenMap.get(pointer)?.length ?? 0,\n childrenPointers: childrenMap.get(pointer) || [],\n pointer,\n }));\n\n return nodes;\n};\n\nexport const graph = {\n analyzeStructure,\n exportForVisualization,\n} as const;\n","import type { Context } from './context';\nimport type { Pagination } from './pagination';\nimport type { IR } from './types';\n\nconst getPaginationSchema = ({\n context,\n parameter,\n}: {\n context: Context;\n parameter: IR.ParameterObject;\n}): IR.SchemaObject | undefined => {\n if (!parameter.pagination) {\n return;\n }\n\n if (parameter.pagination === true) {\n return parameter.schema;\n }\n\n let schema = parameter.schema;\n if (schema.$ref) {\n schema = context.resolveIrRef<IR.SchemaObject>(schema.$ref);\n }\n\n return schema.properties![parameter.pagination]!;\n};\n\nexport const hasParameterGroupObjectRequired = (\n parameterGroup?: Record<string, IR.ParameterObject>,\n): boolean => {\n for (const name in parameterGroup) {\n if (parameterGroup[name]!.required) {\n return true;\n }\n }\n\n return false;\n};\n\nexport const hasParametersObjectRequired = (\n parameters: IR.ParametersObject | undefined,\n): boolean => {\n if (!parameters) {\n return false;\n }\n\n if (hasParameterGroupObjectRequired(parameters.cookie)) {\n return true;\n }\n\n if (hasParameterGroupObjectRequired(parameters.header)) {\n return true;\n }\n\n if (hasParameterGroupObjectRequired(parameters.path)) {\n return true;\n }\n\n if (hasParameterGroupObjectRequired(parameters.query)) {\n return true;\n }\n\n return false;\n};\n\nexport const parameterWithPagination = ({\n context,\n parameters,\n}: {\n context: Context;\n parameters: IR.ParametersObject | undefined;\n}): Pagination | undefined => {\n if (!parameters) {\n return;\n }\n\n for (const name in parameters.cookie) {\n const parameter = parameters.cookie[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n for (const name in parameters.header) {\n const parameter = parameters.header[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n for (const name in parameters.path) {\n const parameter = parameters.path[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n for (const name in parameters.query) {\n const parameter = parameters.query[name]!;\n if (parameter.pagination) {\n return {\n in: parameter.location,\n name:\n parameter.pagination === true\n ? parameter.name\n : `${parameter.name}.${parameter.pagination}`,\n schema: getPaginationSchema({ context, parameter })!,\n };\n }\n }\n\n return;\n};\n","import type { IR } from './types';\n\n/**\n * Ensure we don't produce redundant types, e.g. string | string.\n */\nexport function deduplicateSchema<T extends IR.SchemaObject>({\n detectFormat = true,\n schema,\n}: {\n detectFormat?: boolean;\n schema: T;\n}): T {\n if (!schema.items) {\n return schema;\n }\n\n const uniqueItems: Array<IR.SchemaObject> = [];\n const typeIds: Array<string> = [];\n\n for (const item of schema.items) {\n // skip nested schemas for now, handle if necessary\n if ((!item.type && item.items) || schema.type === 'tuple') {\n uniqueItems.push(item);\n continue;\n }\n\n if (\n // no `type` might still include `$ref` or `const`\n !item.type ||\n item.type === 'boolean' ||\n item.type === 'integer' ||\n item.type === 'null' ||\n item.type === 'number' ||\n item.type === 'string' ||\n item.type === 'unknown' ||\n item.type === 'void'\n ) {\n // const needs namespace to handle empty string values, otherwise\n // fallback would equal an actual value and we would skip an item\n const constant = item.const !== undefined ? `const-${item.const}` : '';\n const format = item.format !== undefined && detectFormat ? `format-${item.format}` : '';\n\n // Include validation constraints in the type ID to avoid incorrect deduplication\n const constraints = [\n item.minLength !== undefined ? `minLength-${item.minLength}` : '',\n item.maxLength !== undefined ? `maxLength-${item.maxLength}` : '',\n item.minimum !== undefined ? `minimum-${item.minimum}` : '',\n item.maximum !== undefined ? `maximum-${item.maximum}` : '',\n item.exclusiveMinimum !== undefined ? `exclusiveMinimum-${item.exclusiveMinimum}` : '',\n item.exclusiveMaximum !== undefined ? `exclusiveMaximum-${item.exclusiveMaximum}` : '',\n item.minItems !== undefined ? `minItems-${item.minItems}` : '',\n item.maxItems !== undefined ? `maxItems-${item.maxItems}` : '',\n item.pattern !== undefined ? `pattern-${item.pattern}` : '',\n ].join('');\n\n const typeId = `${item.$ref ?? ''}${item.type ?? ''}${constant}${format}${constraints}`;\n if (!typeIds.includes(typeId)) {\n typeIds.push(typeId);\n uniqueItems.push(item);\n }\n continue;\n }\n\n uniqueItems.push(item);\n }\n\n let result = { ...schema };\n result.items = uniqueItems;\n\n if (\n result.items.length <= 1 &&\n result.type !== 'array' &&\n result.type !== 'enum' &&\n result.type !== 'tuple'\n ) {\n // bring the only item up to clean up the schema\n const liftedSchema = result.items[0];\n delete result.logicalOperator;\n delete result.items;\n result = {\n ...result,\n ...liftedSchema,\n };\n }\n\n // exclude unknown if it's the only type left\n if (result.type === 'unknown') {\n return {} as T;\n }\n\n return result;\n}\n","import type { IR } from './types';\n\n/**\n * Simply adds `items` to the schema. Also handles setting the logical operator\n * and avoids setting it for a single item or tuples.\n */\nexport function addItemsToSchema({\n items,\n logicalOperator = 'or',\n mutateSchemaOneItem = false,\n schema,\n}: {\n items: Array<IR.SchemaObject>;\n logicalOperator?: IR.SchemaObject['logicalOperator'];\n mutateSchemaOneItem?: boolean;\n schema: IR.SchemaObject;\n}): IR.SchemaObject {\n if (!items.length) {\n return schema;\n }\n\n if (schema.type === 'tuple') {\n schema.items = items;\n return schema;\n }\n\n if (items.length !== 1) {\n schema.items = items;\n schema.logicalOperator = logicalOperator;\n return schema;\n }\n\n if (mutateSchemaOneItem) {\n // bring composition up to avoid extraneous brackets\n schema = {\n ...schema,\n ...items[0],\n };\n return schema;\n }\n\n schema.items = items;\n return schema;\n}\n","import type { Context } from './context';\nimport type { Pagination } from './pagination';\nimport { hasParametersObjectRequired, parameterWithPagination } from './parameter';\nimport { deduplicateSchema } from './schema';\nimport type { IR } from './types';\nimport { addItemsToSchema } from './utils';\n\nexport const hasOperationDataRequired = (operation: IR.OperationObject): boolean => {\n if (hasParametersObjectRequired(operation.parameters)) {\n return true;\n }\n\n if (operation.body?.required) {\n return true;\n }\n\n return false;\n};\n\nexport const createOperationKey = ({ method, path }: { method: string; path: string }) =>\n `${method.toUpperCase()} ${path}`;\n\nexport const operationPagination = ({\n context,\n operation,\n}: {\n context: Context;\n operation: IR.OperationObject;\n}): Pagination | undefined => {\n const body = operation.body;\n\n if (!body || !body.pagination) {\n return parameterWithPagination({\n context,\n parameters: operation.parameters,\n });\n }\n\n if (body.pagination === true) {\n return {\n in: 'body',\n name: 'body',\n schema: body.schema,\n };\n }\n\n const schema = body.schema;\n const resolvedSchema = schema.$ref\n ? context.resolveIrRef<IR.RequestBodyObject | IR.SchemaObject>(schema.$ref)\n : schema;\n\n const finalSchema = 'schema' in resolvedSchema ? resolvedSchema.schema : resolvedSchema;\n const paginationProp = finalSchema?.properties?.[body.pagination];\n\n if (!paginationProp) {\n return parameterWithPagination({\n context,\n parameters: operation.parameters,\n });\n }\n\n return {\n in: 'body',\n name: body.pagination,\n schema: paginationProp,\n };\n};\n\ntype StatusGroup = '1XX' | '2XX' | '3XX' | '4XX' | '5XX' | 'default';\n\nexport const statusCodeToGroup = ({ statusCode }: { statusCode: string }): StatusGroup => {\n switch (statusCode) {\n case '1XX':\n return '1XX';\n case '2XX':\n return '2XX';\n case '3XX':\n return '3XX';\n case '4XX':\n return '4XX';\n case '5XX':\n return '5XX';\n case 'default':\n return 'default';\n default:\n return `${statusCode[0]}XX` as StatusGroup;\n }\n};\n\ninterface OperationResponsesMap {\n /**\n * A deduplicated union of all error types. Unknown types are omitted.\n */\n error?: IR.SchemaObject;\n /**\n * An object containing a map of status codes for each error type.\n */\n errors?: IR.SchemaObject;\n /**\n * A deduplicated union of all response types. Unknown types are omitted.\n */\n response?: IR.SchemaObject;\n /**\n * An object containing a map of status codes for each response type.\n */\n responses?: IR.SchemaObject;\n}\n\nexport const operationResponsesMap = (operation: IR.OperationObject): OperationResponsesMap => {\n const result: OperationResponsesMap = {};\n\n if (!operation.responses) {\n return result;\n }\n\n const errors: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'> = {\n properties: {},\n type: 'object',\n };\n\n const responses: Omit<IR.SchemaObject, 'properties'> &\n Pick<Required<IR.SchemaObject>, 'properties'> = {\n properties: {},\n type: 'object',\n };\n\n // store default response to be evaluated last\n let defaultResponse: IR.ResponseObject | undefined;\n\n for (const name in operation.responses) {\n const response = operation.responses[name]!;\n\n switch (statusCodeToGroup({ statusCode: name })) {\n case '1XX':\n case '3XX':\n // TODO: parser - handle informational and redirection status codes\n break;\n case '2XX':\n responses.properties[name] = response.schema;\n break;\n case '4XX':\n case '5XX':\n errors.properties[name] = response.schema;\n break;\n case 'default':\n defaultResponse = response;\n break;\n }\n }\n\n // infer default response type\n if (defaultResponse) {\n let inferred = false;\n\n // assume default is intended for success if none exists yet\n if (!Object.keys(responses.properties).length) {\n responses.properties.default = defaultResponse.schema;\n inferred = true;\n }\n\n const description = (defaultResponse.schema.description ?? '').toLocaleLowerCase();\n const $ref = (defaultResponse.schema.$ref ?? '').toLocaleLowerCase();\n\n // TODO: parser - this could be rewritten using regular expressions\n const successKeywords = ['success'];\n if (\n successKeywords.some((keyword) => description.includes(keyword) || $ref.includes(keyword))\n ) {\n responses.properties.default = defaultResponse.schema;\n inferred = true;\n }\n\n // TODO: parser - this could be rewritten using regular expressions\n const errorKeywords = ['error', 'problem'];\n if (errorKeywords.some((keyword) => description.includes(keyword) || $ref.includes(keyword))) {\n errors.properties.default = defaultResponse.schema;\n inferred = true;\n }\n\n // if no keyword match, assume default schema is intended for error\n if (!inferred) {\n errors.properties.default = defaultResponse.schema;\n }\n }\n\n const errorKeys = Object.keys(errors.properties);\n if (errorKeys.length) {\n errors.required = errorKeys;\n result.errors = errors;\n\n let errorUnion = addItemsToSchema({\n items: Object.values(errors.properties),\n mutateSchemaOneItem: true,\n schema: {},\n });\n errorUnion = deduplicateSchema({ schema: errorUnion });\n if (Object.keys(errorUnion).length && errorUnion.type !== 'unknown') {\n result.error = errorUnion;\n }\n }\n\n const responseKeys = Object.keys(responses.properties);\n if (responseKeys.length) {\n responses.required = responseKeys;\n result.responses = responses;\n\n let responseUnion = addItemsToSchema({\n items: Object.values(responses.properties),\n mutateSchemaOneItem: true,\n schema: {},\n });\n responseUnion = deduplicateSchema({ schema: responseUnion });\n if (Object.keys(responseUnion).length && responseUnion.type !== 'unknown') {\n result.response = responseUnion;\n }\n }\n\n return result;\n};\n","import type { Casing, NamingConfig, NamingRule } from './types';\n\nconst uppercaseRegExp = /[\\p{Lu}]/u;\nconst lowercaseRegExp = /[\\p{Ll}]/u;\nconst identifierRegExp = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst separatorsRegExp = /[_.$+:\\- `\\\\[\\](){}\\\\/]+/;\n\nconst leadingSeparatorsRegExp = new RegExp(`^${separatorsRegExp.source}`);\nconst separatorsAndIdentifierRegExp = new RegExp(\n `${separatorsRegExp.source}${identifierRegExp.source}`,\n 'gu',\n);\nconst numbersAndIdentifierRegExp = new RegExp(`\\\\d+${identifierRegExp.source}`, 'gu');\n\nconst preserveCase = (value: string, casing: Casing) => {\n let isLastCharLower = false;\n let isLastCharUpper = false;\n let isLastLastCharUpper = false;\n let isLastLastCharPreserved = false;\n\n const separator = casing === 'snake_case' || casing === 'SCREAMING_SNAKE_CASE' ? '_' : '-';\n\n for (let index = 0; index < value.length; index++) {\n const character = value[index]!;\n isLastLastCharPreserved = index > 2 ? value[index - 3] === separator : true;\n\n let nextIndex = index + 1;\n let nextCharacter = value[nextIndex];\n separatorsRegExp.lastIndex = 0;\n while (nextCharacter && separatorsRegExp.test(nextCharacter)) {\n nextIndex += 1;\n nextCharacter = value[nextIndex];\n }\n const isSeparatorBeforeNextCharacter = nextIndex !== index + 1;\n\n lowercaseRegExp.lastIndex = 0;\n uppercaseRegExp.lastIndex = 0;\n if (\n uppercaseRegExp.test(character) &&\n (isLastCharLower ||\n (nextCharacter &&\n !isSeparatorBeforeNextCharacter &&\n nextCharacter !== 's' &&\n lowercaseRegExp.test(nextCharacter)))\n ) {\n // insert separator behind character\n value = `${value.slice(0, index)}${separator}${value.slice(index)}`;\n index++;\n isLastLastCharUpper = isLastCharUpper;\n isLastCharLower = false;\n isLastCharUpper = true;\n } else if (\n isLastCharUpper &&\n isLastLastCharUpper &&\n lowercaseRegExp.test(character) &&\n !isLastLastCharPreserved &&\n // naive detection of plurals\n !(\n character === 's' &&\n (!nextCharacter || nextCharacter.toLocaleLowerCase() !== nextCharacter)\n )\n ) {\n // insert separator 2 characters behind\n value = `${value.slice(0, index - 1)}${separator}${value.slice(index - 1)}`;\n isLastLastCharUpper = isLastCharUpper;\n isLastCharLower = true;\n isLastCharUpper = false;\n } else {\n const characterLower = character.toLocaleLowerCase();\n const characterUpper = character.toLocaleUpperCase();\n isLastLastCharUpper = isLastCharUpper;\n isLastCharLower = characterLower === character && characterUpper !== character;\n isLastCharUpper = characterUpper === character && characterLower !== character;\n }\n }\n\n return value;\n};\n\n/**\n * Convert a string to the specified casing.\n *\n * @param value - The string to convert\n * @param casing - The target casing\n * @param options - Additional options\n * @returns The converted string\n */\nexport function toCase(\n value: string,\n casing: Casing | undefined,\n options: {\n /**\n * If leading separators have a semantic meaning, we might not want to\n * remove them.\n */\n stripLeadingSeparators?: boolean;\n } = {},\n): string {\n const stripLeadingSeparators = options.stripLeadingSeparators ?? true;\n\n let result = value.trim();\n\n if (!result.length || !casing || casing === 'preserve') {\n return result;\n }\n\n if (result.length === 1) {\n separatorsRegExp.lastIndex = 0;\n if (separatorsRegExp.test(result)) {\n return '';\n }\n\n return casing === 'PascalCase' || casing === 'SCREAMING_SNAKE_CASE'\n ? result.toLocaleUpperCase()\n : result.toLocaleLowerCase();\n }\n\n const hasUpperCase = result !== result.toLocaleLowerCase();\n\n if (hasUpperCase) {\n result = preserveCase(result, casing);\n }\n\n if (stripLeadingSeparators || result[0] !== value[0]) {\n result = result.replace(leadingSeparatorsRegExp, '');\n }\n\n result =\n casing === 'SCREAMING_SNAKE_CASE' ? result.toLocaleUpperCase() : result.toLocaleLowerCase();\n\n if (casing === 'PascalCase') {\n result = `${result.charAt(0).toLocaleUpperCase()}${result.slice(1)}`;\n }\n\n if (casing === 'snake_case' || casing === 'SCREAMING_SNAKE_CASE') {\n result = result.replaceAll(separatorsAndIdentifierRegExp, (match, identifier, offset) => {\n if (offset === 0 && !stripLeadingSeparators) {\n return match;\n }\n return `_${identifier}`;\n });\n\n if (result[result.length - 1] === '_') {\n // strip trailing underscore\n result = result.slice(0, result.length - 1);\n }\n } else {\n separatorsAndIdentifierRegExp.lastIndex = 0;\n numbersAndIdentifierRegExp.lastIndex = 0;\n\n result = result.replaceAll(numbersAndIdentifierRegExp, (match, _, offset) => {\n if (['_', '-', '.'].includes(result.charAt(offset + match.length))) {\n return match;\n }\n\n return match.toLocaleUpperCase();\n });\n\n result = result.replaceAll(separatorsAndIdentifierRegExp, (match, identifier, offset) => {\n if (offset === 0 && !stripLeadingSeparators && match[0] && value.startsWith(match[0])) {\n return match;\n }\n return identifier.toLocaleUpperCase();\n });\n }\n\n return result;\n}\n\n/**\n * Normalize a NamingRule to NamingConfig.\n */\nexport function resolveNaming(rule: NamingRule | undefined): NamingConfig {\n if (!rule) {\n return {};\n }\n if (typeof rule === 'string' || typeof rule === 'function') {\n return { name: rule };\n }\n return rule;\n}\n\n/**\n * Apply naming configuration to a value.\n *\n * Casing is applied first, then transformation.\n */\nexport function applyNaming(value: string, config: NamingConfig): string {\n let result = value;\n\n const casing = config.casing ?? config.case;\n\n if (config.name) {\n if (typeof config.name === 'function') {\n result = config.name(result);\n } else {\n // TODO: refactor so there's no need for separators?\n const separator = !casing || casing === 'preserve' ? '' : '-';\n result = config.name.replace('{{name}}', `${separator}${result}${separator}`);\n }\n }\n\n // TODO: apply case before name?\n return toCase(result, casing);\n}\n","import type { Context } from '../../../ir/context';\nimport { createOperationKey } from '../../../ir/operation';\nimport { toCase } from '../../../utils/naming/naming';\nimport type { State } from '../types/state';\n\nexport const httpMethods = [\n 'delete',\n 'get',\n 'head',\n 'options',\n 'patch',\n 'post',\n 'put',\n 'trace',\n] as const;\n\n/**\n * Sanitizes namespace identifiers so they are valid TypeScript identifiers of a certain form.\n *\n * 1: Remove any leading characters that are illegal as starting character of a typescript identifier.\n * 2: Replace illegal characters in remaining part of type name with hyphen (-).\n *\n * Step 1 should perhaps instead also replace illegal characters with underscore, or prefix with it, like sanitizeEnumName\n * does. The way this is now one could perhaps end up removing all characters, if all are illegal start characters. It\n * would be sort of a breaking change to do so, though, previously generated code might change then.\n *\n * JavaScript identifier regexp pattern retrieved from https://developer.mozilla.org/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers\n *\n * The output of this is expected to be converted to PascalCase\n *\n * @deprecated\n */\nexport const sanitizeNamespaceIdentifier = (name: string) =>\n name\n .replace(/^[^\\p{ID_Start}]+/u, '')\n .replace(/[^$\\u200c\\u200d\\p{ID_Continue}]/gu, '-')\n .replace(/[$+]/g, '-');\n\n/**\n * Returns an operation ID to use across the application. By default, we try\n * to use the provided ID. If it's not provided or the SDK is configured\n * to exclude it, we generate operation ID from its location.\n *\n * @deprecated\n */\nexport function operationToId({\n context,\n count = 1,\n id,\n method,\n path,\n state,\n}: {\n context: Context;\n count?: number;\n id: string | undefined;\n method: string;\n path: string;\n state: Pick<State, 'ids'>;\n}): string {\n let result: string;\n\n const { output } = context.config;\n const targetCase =\n (output !== undefined && typeof output === 'object' && 'case' in output\n ? output.case\n : undefined) ?? 'camelCase';\n\n if (\n id &&\n (!context.config.plugins['@hey-api/sdk'] ||\n // TODO: needs to be refactored...\n // @ts-expect-error\n (context.config.plugins['@hey-api/sdk'].config.operations &&\n // @ts-expect-error\n typeof context.config.plugins['@hey-api/sdk'].config.operations !== 'function' &&\n // @ts-expect-error\n typeof context.config.plugins['@hey-api/sdk'].config.operations === 'object' &&\n // @ts-expect-error\n context.config.plugins['@hey-api/sdk'].config.operations.nesting === 'operationId'))\n ) {\n result = toCase(sanitizeNamespaceIdentifier(id), targetCase);\n } else {\n const pathWithoutPlaceholders = path\n .replace(/{(.*?)}/g, 'by-$1')\n // replace slashes with hyphens for camelcase method at the end\n .replace(/[/:+]/g, '-');\n\n result = toCase(`${method}-${pathWithoutPlaceholders}`, targetCase);\n }\n\n if (count > 1) {\n result = `${result}${count}`;\n }\n\n if (state.ids.has(result)) {\n return operationToId({\n context,\n count: count + 1,\n id,\n method,\n path,\n state,\n });\n }\n\n state.ids.set(result, createOperationKey({ method, path }));\n\n return result;\n}\n","import colors from 'ansi-colors';\n\nimport type { IR } from '../ir/types';\nimport { httpMethods } from '../openApi/shared/utils/operation';\n\nexport interface PrintOptions {\n /**\n * Indentation depth for `JSON.stringify()` when printing objects.\n *\n * @default 2\n */\n depth?: number;\n /**\n * Which section of the IR to print. Use 'all' to print every section.\n *\n * @default 'all'\n */\n section?: keyof IR.Model | 'all';\n /**\n * How much detail to print.\n *\n * - `summary` โ†’ only keys, names, operationIds, status codes\n * - `full` โ†’ dump full JSON structures\n *\n * @default 'summary'\n */\n verbosity?: 'full' | 'summary';\n}\n\nconst indent = (level: number) => ' '.repeat(level);\n\nconst log = (message: string, level?: number) => console.log(`${indent(level ?? 0)}${message}`);\n\nconst print = (ir: IR.Model, options: PrintOptions = {}) => {\n const { depth = 2, section = 'all', verbosity = 'summary' } = options;\n\n const printObject = (\n obj: unknown,\n level: number,\n kind: 'responses' | 'requestBody' | 'schema' | 'generic' = 'generic',\n ) => {\n if (verbosity === 'summary' && obj && typeof obj === 'object') {\n if (kind === 'responses') {\n const count = Object.keys(obj).length;\n const noun = count === 1 ? 'code' : 'codes';\n log(`responses: ${colors.yellow(`${count} ${noun}`)}`, level);\n } else if (kind === 'requestBody') {\n log(`requestBody: ${Object.keys(obj).join(', ')}`, level);\n } else if (kind === 'schema') {\n log(`schema keys: ${Object.keys(obj).join(', ')}`, level);\n } else {\n log(`keys: ${Object.keys(obj).join(', ')}`, level);\n }\n } else {\n log(JSON.stringify(obj, null, depth), level);\n }\n };\n\n const printPathItem = (\n key: string,\n item: IR.PathItemObject | IR.ReferenceObject,\n base: number = 1,\n ) => {\n if ('$ref' in item) {\n log(`${colors.cyan(key)} is a $ref โ†’ ${colors.yellow(item.$ref)}`, base);\n return;\n }\n\n for (const method of Object.keys(item) as Array<keyof IR.PathItemObject>) {\n if (!httpMethods.includes(method)) continue;\n\n const operation = item[method]!;\n log(\n `${colors.green(method.toUpperCase())} ${colors.cyan(key)} (${colors.magenta(operation.operationId ?? '')})`,\n base,\n );\n\n if (operation.body) printObject(operation.body, base + 1, 'requestBody');\n if (operation.responses) printObject(operation.responses, base + 1, 'responses');\n }\n };\n\n const sections =\n section === 'all' ? (Object.keys(ir) as unknown as ReadonlyArray<keyof IR.Model>) : [section];\n\n for (const section of sections) {\n switch (section) {\n case 'components':\n if (ir.components?.schemas) {\n log(`Components: ${Object.keys(ir.components.schemas).length} schemas`);\n for (const [, schema] of Object.entries(ir.components.schemas)) {\n printObject(schema, 1, 'schema');\n }\n }\n break;\n case 'paths': {\n const paths = ir.paths || {};\n log(`paths (${Object.keys(paths).length} items):`);\n for (const [path, item] of Object.entries(paths)) {\n printPathItem(path, item);\n }\n break;\n }\n case 'servers':\n break;\n case 'webhooks': {\n const webhooks = ir.webhooks || {};\n log(`webhooks (${Object.keys(webhooks).length} items):`);\n for (const [path, item] of Object.entries(webhooks)) {\n printPathItem(path, item);\n }\n break;\n }\n }\n }\n};\n\nexport const ir = {\n print,\n} as const;\n","import { graph } from './graph';\nimport { ir } from './ir';\n\nexport const debugTools = {\n graph,\n ir,\n};\n","import { getResolvedInput, sendRequest } from '@hey-api/json-schema-ref-parser';\nimport type { MaybeArray } from '@hey-api/types';\n\nimport type { Input } from './config/input/types';\nimport type { WatchValues } from './types/watch';\n\nconst headersEntries = (headers: Headers): Array<[string, string]> => {\n const entries: Array<[string, string]> = [];\n headers.forEach((value, key) => {\n entries.push([key, value]);\n });\n return entries;\n};\n\nconst mergeHeaders = (\n ...headers: Array<\n | RequestInit['headers']\n | Record<string, MaybeArray<string | number | boolean> | null | undefined | unknown>\n | undefined\n >\n): Headers => {\n const mergedHeaders = new Headers();\n for (const header of headers) {\n if (!header) {\n continue;\n }\n\n const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);\n\n for (const [key, value] of iterator) {\n if (value === null) {\n mergedHeaders.delete(key);\n } else if (Array.isArray(value)) {\n for (const v of value) {\n mergedHeaders.append(key, v as string);\n }\n } else if (value !== undefined) {\n // assume object headers are meant to be JSON stringified, i.e. their\n // content value in OpenAPI specification is 'application/json'\n mergedHeaders.set(\n key,\n typeof value === 'object' ? JSON.stringify(value) : (value as string),\n );\n }\n }\n }\n return mergedHeaders;\n};\n\ntype SpecResponse = {\n arrayBuffer: ArrayBuffer | undefined;\n error?: never;\n resolvedInput: ReturnType<typeof getResolvedInput>;\n response?: never;\n};\n\ntype SpecError = {\n arrayBuffer?: never;\n error: 'not-modified' | 'not-ok';\n resolvedInput?: never;\n response: Response;\n};\n\n/**\n * @internal\n */\nexport async function getSpec({\n fetchOptions,\n inputPath,\n timeout,\n watch,\n}: {\n fetchOptions?: RequestInit;\n inputPath: Input['path'];\n timeout: number | undefined;\n watch: WatchValues;\n}): Promise<SpecResponse | SpecError> {\n const resolvedInput = getResolvedInput({ pathOrUrlOrSchema: inputPath });\n\n let arrayBuffer: ArrayBuffer | undefined;\n // boolean signals whether the file has **definitely** changed\n let hasChanged: boolean | undefined;\n let response: Response | undefined;\n\n if (resolvedInput.type === 'url') {\n // do NOT send HEAD request on first run or if unsupported\n if (watch.lastValue && watch.isHeadMethodSupported !== false) {\n try {\n const request = await sendRequest({\n fetchOptions: {\n method: 'HEAD',\n ...fetchOptions,\n headers: mergeHeaders(fetchOptions?.headers, watch.headers),\n },\n timeout,\n url: resolvedInput.path,\n });\n\n if (request.response.status >= 300) {\n return {\n error: 'not-ok',\n response: request.response,\n };\n }\n\n response = request.response;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: 'not-ok',\n response: new Response(message, { status: 500 }),\n };\n }\n\n if (!response.ok && watch.isHeadMethodSupported) {\n // assume the server is no longer running\n // do nothing, it might be restarted later\n return {\n error: 'not-ok',\n response,\n };\n }\n\n if (watch.isHeadMethodSupported === undefined) {\n watch.isHeadMethodSupported = response.ok;\n }\n\n if (response.status === 304) {\n return {\n error: 'not-modified',\n response,\n };\n }\n\n if (hasChanged === undefined) {\n const eTag = response.headers.get('ETag');\n if (eTag) {\n hasChanged = eTag !== watch.headers.get('If-None-Match');\n\n if (hasChanged) {\n watch.headers.set('If-None-Match', eTag);\n }\n }\n }\n\n if (hasChanged === undefined) {\n const lastModified = response.headers.get('Last-Modified');\n if (lastModified) {\n hasChanged = lastModified !== watch.headers.get('If-Modified-Since');\n\n if (hasChanged) {\n watch.headers.set('If-Modified-Since', lastModified);\n }\n }\n }\n\n // we definitely know the input has not changed\n if (hasChanged === false) {\n return {\n error: 'not-modified',\n response,\n };\n }\n }\n\n try {\n const request = await sendRequest({\n fetchOptions: {\n method: 'GET',\n ...fetchOptions,\n },\n timeout,\n url: resolvedInput.path,\n });\n\n if (request.response.status >= 300) {\n return {\n error: 'not-ok',\n response: request.response,\n };\n }\n\n response = request.response;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: 'not-ok',\n response: new Response(message, { status: 500 }),\n };\n }\n\n if (!response.ok) {\n // assume the server is no longer running\n // do nothing, it might be restarted later\n return {\n error: 'not-ok',\n response,\n };\n }\n\n arrayBuffer = response.body ? await response.arrayBuffer() : new ArrayBuffer(0);\n\n if (hasChanged === undefined) {\n const content = new TextDecoder().decode(arrayBuffer);\n hasChanged = content !== watch.lastValue;\n watch.lastValue = content;\n }\n } else {\n // we do not support watch mode for files or raw spec data\n if (!watch.lastValue) {\n watch.lastValue = resolvedInput.type;\n } else {\n hasChanged = false;\n }\n }\n\n if (hasChanged === false) {\n return {\n error: 'not-modified',\n response: response!,\n };\n }\n\n return {\n arrayBuffer,\n resolvedInput,\n };\n}\n","export class MinHeap {\n private heap: Array<string> = [];\n\n constructor(public declIndex: Map<string, number>) {}\n\n isEmpty(): boolean {\n return !this.heap.length;\n }\n\n pop(): string | undefined {\n const [top] = this.heap;\n if (!this.heap.length) return;\n const last = this.heap.pop()!;\n if (!this.heap.length) return top;\n this.heap[0] = last;\n this.sinkDown(0);\n return top;\n }\n\n push(item: string): void {\n this.heap.push(item);\n this.bubbleUp(this.heap.length - 1);\n }\n\n private bubbleUp(index: number): void {\n const heap = this.heap;\n while (index > 0) {\n const parent = Math.floor((index - 1) / 2);\n const parentVal = heap[parent]!;\n const curVal = heap[index]!;\n if (this.declIndex.get(parentVal)! <= this.declIndex.get(curVal)!) break;\n heap[parent] = curVal;\n heap[index] = parentVal;\n index = parent;\n }\n }\n\n private sinkDown(index: number): void {\n const heap = this.heap;\n const len = heap.length;\n while (true) {\n const left = 2 * index + 1;\n const right = 2 * index + 2;\n let smallest = index;\n if (left < len) {\n const leftVal = heap[left]!;\n const smallestVal = heap[smallest]!;\n if (this.declIndex.get(leftVal)! < this.declIndex.get(smallestVal)!) smallest = left;\n }\n if (right < len) {\n const rightVal = heap[right]!;\n const smallestVal = heap[smallest]!;\n if (this.declIndex.get(rightVal)! < this.declIndex.get(smallestVal)!) smallest = right;\n }\n if (smallest === index) break;\n const tmp = heap[smallest]!;\n heap[smallest] = heap[index]!;\n heap[index] = tmp;\n index = smallest;\n }\n }\n}\n","import { MinHeap } from '../utils/minHeap';\nimport type { GetPointerPriorityFn, WalkFn } from './types/walk';\n\n/**\n * Walk the nodes of the graph in declaration (insertion) order.\n * This is a cheap alternative to `walkTopological` when dependency ordering\n * is not required and the caller only wants nodes in the order they were\n * added to the graph.\n */\nconst walkDeclarations: WalkFn = (graph, callback, options) => {\n const pointers = Array.from(graph.nodes.keys());\n\n if (options?.preferGroups && options.preferGroups.length > 0) {\n // emit nodes that match each preferred group in order, preserving insertion order\n const emitted = new Set<string>();\n if (options.matchPointerToGroup) {\n for (const kind of options.preferGroups) {\n for (const pointer of pointers) {\n const result = options.matchPointerToGroup(pointer);\n if (!result.matched) continue;\n if (result.kind === kind) {\n emitted.add(pointer);\n callback(pointer, graph.nodes.get(pointer)!);\n }\n }\n }\n }\n\n // emit anything not covered by the preferGroups (in declaration order)\n for (const pointer of pointers) {\n if (emitted.has(pointer)) continue;\n callback(pointer, graph.nodes.get(pointer)!);\n }\n return;\n }\n\n // fallback: simple declaration order\n for (const pointer of pointers) {\n callback(pointer, graph.nodes.get(pointer)!);\n }\n};\n\n/**\n * Walks the nodes of the graph in topological order (dependencies before dependents).\n * Calls the callback for each node pointer in order.\n * Nodes in cycles are grouped together and emitted in arbitrary order within the group.\n *\n * @param graph - The dependency graph\n * @param callback - Function to call for each node pointer\n */\nconst walkTopological: WalkFn = (graph, callback, options) => {\n // stable Kahn's algorithm that respects declaration order as a tiebreaker.\n const pointers = Array.from(graph.nodes.keys());\n // base insertion order\n const baseIndex = new Map<string, number>();\n pointers.forEach((pointer, index) => baseIndex.set(pointer, index));\n\n // composite decl index: group priority then base insertion order\n const declIndex = new Map<string, number>();\n for (const pointer of pointers) {\n const priority = options?.getPointerPriority?.(pointer) ?? 10;\n const composite = priority * 1_000_000 + (baseIndex.get(pointer) ?? 0);\n declIndex.set(pointer, composite);\n }\n\n // build dependency sets for each pointer\n const depsOf = new Map<string, Set<string>>();\n for (const pointer of pointers) {\n const raw = graph.subtreeDependencies?.get(pointer) ?? new Set();\n const filtered = new Set<string>();\n for (const rawPointer of raw) {\n if (rawPointer === pointer) continue; // ignore self-dependencies for ordering\n if (graph.nodes.has(rawPointer)) {\n filtered.add(rawPointer);\n }\n }\n depsOf.set(pointer, filtered);\n }\n\n // build inDegree and dependents adjacency\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n for (const pointer of pointers) {\n inDegree.set(pointer, 0);\n }\n for (const [pointer, deps] of depsOf) {\n inDegree.set(pointer, deps.size);\n for (const d of deps) {\n if (!dependents.has(d)) {\n dependents.set(d, new Set());\n }\n dependents.get(d)!.add(pointer);\n }\n }\n\n // sort pointers by declaration order\n const sortByDecl = (arr: Array<string>) =>\n arr.sort((a, b) => declIndex.get(a)! - declIndex.get(b)!);\n\n // initialize queue with zero-inDegree nodes in declaration order\n // use min-heap prioritized by declaration index to avoid repeated full sorts\n const heap = new MinHeap(declIndex);\n for (const pointer of pointers) {\n if ((inDegree.get(pointer) ?? 0) === 0) {\n heap.push(pointer);\n }\n }\n\n const emitted = new Set<string>();\n const order: Array<string> = [];\n\n while (!heap.isEmpty()) {\n const cur = heap.pop()!;\n if (emitted.has(cur)) continue;\n emitted.add(cur);\n order.push(cur);\n\n const deps = dependents.get(cur);\n if (!deps) continue;\n\n for (const dep of deps) {\n const v = (inDegree.get(dep) ?? 0) - 1;\n inDegree.set(dep, v);\n if (v === 0) {\n heap.push(dep);\n }\n }\n }\n\n // emit remaining nodes (cycles) in declaration order\n const remaining = pointers.filter((pointer) => !emitted.has(pointer));\n sortByDecl(remaining);\n for (const pointer of remaining) {\n emitted.add(pointer);\n order.push(pointer);\n }\n\n // prefer specified groups when safe\n let finalOrder = order;\n if (options?.preferGroups && options.preferGroups.length > 0) {\n // build group priority map (lower = earlier)\n const groupPriority = new Map<string, number>();\n for (let i = 0; i < options.preferGroups.length; i++) {\n const k = options.preferGroups[i];\n if (k) {\n groupPriority.set(k, i);\n }\n }\n\n const getGroup: GetPointerPriorityFn = (pointer) => {\n if (options.matchPointerToGroup) {\n const result = options.matchPointerToGroup(pointer);\n if (result.matched) {\n return groupPriority.has(result.kind)\n ? groupPriority.get(result.kind)!\n : options.preferGroups!.length;\n }\n }\n return options.preferGroups!.length;\n };\n\n // proposed order: sort by (groupPriority, originalIndex)\n const proposed = [...order].sort((a, b) => {\n const ga = getGroup(a);\n const gb = getGroup(b);\n return ga !== gb ? ga - gb : order.indexOf(a) - order.indexOf(b);\n });\n\n // build quick lookup of original index and proposed index\n const proposedIndex = new Map<string, number>();\n for (let i = 0; i < proposed.length; i++) {\n proposedIndex.set(proposed[i]!, i);\n }\n\n // only validate edges where group(dep) > group(node)\n const violated = (() => {\n for (const [node, deps] of depsOf) {\n for (const dep of deps) {\n const gDep = getGroup(dep);\n const gNode = getGroup(node);\n if (gDep <= gNode) continue; // not a crossing edge, cannot be violated by grouping\n const pDep = proposedIndex.get(dep)!;\n const pNode = proposedIndex.get(node)!;\n if (pDep >= pNode) {\n return true;\n }\n }\n }\n return false;\n })();\n\n if (!violated) {\n finalOrder = proposed;\n }\n }\n\n for (const pointer of finalOrder) {\n callback(pointer, graph.nodes.get(pointer)!);\n }\n};\n\nexport const walk: WalkFn = (graph, callback, options) => {\n if (options?.order === 'topological') {\n return walkTopological(graph, callback, options);\n }\n return walkDeclarations(graph, callback, options);\n};\n","import type { GetPointerPriorityFn, MatchPointerToGroupFn } from '../graph';\n\nexport const irTopLevelKinds = [\n 'operation',\n 'parameter',\n 'requestBody',\n 'schema',\n 'server',\n 'webhook',\n] as const;\n\nexport type IrTopLevelKind = (typeof irTopLevelKinds)[number];\n\n/**\n * Checks if a pointer matches a known top-level IR component (schema, parameter, etc) and returns match info.\n *\n * @param pointer - The IR pointer string (e.g. '#/components/schemas/Foo')\n * @param kind - (Optional) The component kind to check\n * @returns { matched: true, kind: IrTopLevelKind } | { matched: false } - Whether it matched, and the matched kind if so\n */\nexport const matchIrPointerToGroup: MatchPointerToGroupFn<IrTopLevelKind> = (pointer, kind) => {\n const patterns: Record<IrTopLevelKind, RegExp> = {\n operation: /^#\\/paths\\/[^/]+\\/(get|put|post|delete|options|head|patch|trace)$/,\n parameter: /^#\\/components\\/parameters\\/[^/]+$/,\n requestBody: /^#\\/components\\/requestBodies\\/[^/]+$/,\n schema: /^#\\/components\\/schemas\\/[^/]+$/,\n server: /^#\\/servers\\/(\\d+|[^/]+)$/,\n webhook: /^#\\/webhooks\\/[^/]+\\/(get|put|post|delete|options|head|patch|trace)$/,\n };\n if (kind) {\n return patterns[kind].test(pointer) ? { kind, matched: true } : { matched: false };\n }\n for (const key of Object.keys(patterns)) {\n const kind = key as IrTopLevelKind;\n if (patterns[kind].test(pointer)) {\n return { kind, matched: true };\n }\n }\n return { matched: false };\n};\n\n// default grouping preference (earlier groups emitted first when safe)\nexport const preferGroups = [\n 'server',\n 'schema',\n 'parameter',\n 'requestBody',\n 'operation',\n 'webhook',\n] satisfies ReadonlyArray<IrTopLevelKind>;\n\ntype KindPriority = Record<IrTopLevelKind, number>;\n\n// default group priority (lower = earlier)\n// built from `preferGroups` so the priority order stays in sync with the prefer-groups array.\nconst kindPriority: KindPriority = (() => {\n const partial: Partial<KindPriority> = {};\n for (let i = 0; i < preferGroups.length; i++) {\n const k = preferGroups[i];\n if (k) partial[k] = i;\n }\n // Ensure all known kinds exist in the map (fall back to a high index).\n for (const k of irTopLevelKinds) {\n if (partial[k] === undefined) {\n partial[k] = preferGroups.length;\n }\n }\n return partial as KindPriority;\n})();\n\nconst defaultPriority = 10;\n\nexport const getIrPointerPriority: GetPointerPriorityFn = (pointer) => {\n const result = matchIrPointerToGroup(pointer);\n if (result.matched) {\n return kindPriority[result.kind] ?? defaultPriority;\n }\n return defaultPriority;\n};\n","const jsonPointerSlash = /~1/g;\nconst jsonPointerTilde = /~0/g;\n\n/**\n * Returns the reusable component name from `$ref`.\n */\nexport function refToName($ref: string): string {\n const path = jsonPointerToPath($ref);\n const name = path[path.length - 1]!;\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n return decodeURI(name);\n}\n\n/**\n * Encodes a path segment for use in a JSON Pointer (RFC 6901).\n *\n * - Replaces all '~' with '~0'.\n * - Replaces all '/' with '~1'.\n *\n * This ensures that path segments containing these characters are safely\n * represented in JSON Pointer strings.\n *\n * @param segment - The path segment (string or number) to encode.\n * @returns The encoded segment as a string.\n */\nexport function encodeJsonPointerSegment(segment: string | number): string {\n return String(segment).replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * Converts a JSON Pointer string (RFC 6901) to an array of path segments.\n *\n * - Removes the leading '#' if present.\n * - Splits the pointer on '/'.\n * - Decodes '~1' to '/' and '~0' to '~' in each segment.\n * - Returns an empty array for the root pointer ('#' or '').\n *\n * @param pointer - The JSON Pointer string to convert (e.g., '#/components/schemas/Foo').\n * @returns An array of decoded path segments.\n */\nexport function jsonPointerToPath(pointer: string): ReadonlyArray<string> {\n let clean = pointer.trim();\n if (clean.startsWith('#')) {\n clean = clean.slice(1);\n }\n if (clean.startsWith('/')) {\n clean = clean.slice(1);\n }\n if (!clean) {\n return [];\n }\n return clean\n .split('/')\n .map((part) => part.replace(jsonPointerSlash, '/').replace(jsonPointerTilde, '~'));\n}\n\n/**\n * Normalizes a JSON Pointer string to a canonical form.\n *\n * - Ensures the pointer starts with '#'.\n * - Removes trailing slashes (except for root).\n * - Collapses multiple consecutive slashes into one.\n * - Trims whitespace from the input.\n *\n * @param pointer - The JSON Pointer string to normalize.\n * @returns The normalized JSON Pointer string.\n */\nexport function normalizeJsonPointer(pointer: string): string {\n let normalized = pointer.trim();\n if (!normalized.startsWith('#')) {\n normalized = `#${normalized}`;\n }\n // Remove trailing slashes (except for root)\n if (normalized.length > 1 && normalized.endsWith('/')) {\n normalized = normalized.slice(0, -1);\n }\n // Collapse multiple slashes\n normalized = normalized.replace(/\\/+/g, '/');\n return normalized;\n}\n\n/**\n * Encode path as JSON Pointer (RFC 6901).\n *\n * @param path\n * @returns\n */\nexport function pathToJsonPointer(path: ReadonlyArray<string | number>): string {\n const segments = path.map(encodeJsonPointerSegment).join('/');\n return '#' + (segments ? `/${segments}` : '');\n}\n\n/**\n * Checks if a $ref or path points to a top-level component (not a deep path reference).\n *\n * Top-level component references:\n * - OpenAPI 3.x: #/components/{type}/{name} (3 segments)\n * - OpenAPI 2.0: #/definitions/{name} (2 segments)\n *\n * Deep path references (4+ segments for 3.x, 3+ for 2.0) should be inlined\n * because they don't have corresponding registered symbols.\n *\n * @param refOrPath - The $ref string or path array to check\n * @returns true if the ref points to a top-level component, false otherwise\n */\nexport function isTopLevelComponent(refOrPath: string | ReadonlyArray<string | number>): boolean {\n const path = refOrPath instanceof Array ? refOrPath : jsonPointerToPath(refOrPath);\n\n // OpenAPI 3.x: #/components/{type}/{name} = 3 segments\n if (path[0] === 'components') {\n return path.length === 3;\n }\n\n // OpenAPI 2.0: #/definitions/{name} = 2 segments\n if (path[0] === 'definitions') {\n return path.length === 2;\n }\n\n return false;\n}\n\nexport function resolveRef<T>({ $ref, spec }: { $ref: string; spec: Record<string, any> }): T {\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n const path = jsonPointerToPath(decodeURI($ref));\n\n let current = spec;\n\n for (const part of path) {\n const segment = part as keyof typeof current;\n if (current[segment] === undefined) {\n throw new Error(`Reference not found: ${$ref}`);\n }\n current = current[segment];\n }\n\n return current as T;\n}\n","import path from 'node:path';\n\nimport type {\n IProject,\n Node,\n Symbol,\n SymbolIdentifier,\n SymbolIn,\n SymbolMeta,\n} from '@hey-api/codegen-core';\n\nimport type { Dependency } from '../../../config/utils/dependencies';\nimport { HeyApiError } from '../../../error';\nimport type { MatchPointerToGroupFn, WalkOptions } from '../../../graph';\nimport { walk } from '../../../graph';\nimport type { Context } from '../../../ir/context';\nimport type { IrTopLevelKind } from '../../../ir/graph';\nimport {\n getIrPointerPriority,\n irTopLevelKinds,\n matchIrPointerToGroup,\n preferGroups,\n} from '../../../ir/graph';\nimport type { ExampleIntent } from '../../../ir/intents';\nimport type { IR } from '../../../ir/types';\nimport type { Hooks } from '../../../parser/hooks';\nimport type { Plugin, PluginConfigMap } from '../../../plugins/types';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport type { BaseEvent, WalkEvent } from '../types/instance';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface PluginInstanceTypes {}\n\n/**\n * Resolves the Node type, falling back to base Node if not augmented.\n */\ntype ResolvedNode = 'Node' extends keyof PluginInstanceTypes\n ? // @ts-expect-error ts cannot resolve conditional types properly here\n PluginInstanceTypes['Node']\n : Node;\n\n// TODO: abstract\nconst defaultGetFilePath = (symbol: Symbol): string | undefined => {\n if (!symbol.meta?.pluginName || typeof symbol.meta.pluginName !== 'string') {\n return;\n }\n if (symbol.meta.pluginName.startsWith('@hey-api/client-')) {\n return 'client';\n }\n if (symbol.meta.pluginName === '@hey-api/typescript') {\n return 'types';\n }\n if (symbol.meta.pluginName === '@hey-api/python-sdk') {\n return 'sdk';\n }\n if (symbol.meta.pluginName.startsWith('@hey-api/')) {\n return symbol.meta.pluginName.split('/')[1];\n }\n return symbol.meta.pluginName;\n};\n\nconst defaultGetKind: Required<Required<Hooks>['operations']>['getKind'] = (operation) => {\n switch (operation.method) {\n case 'delete':\n case 'patch':\n case 'post':\n case 'put':\n return ['mutation'];\n case 'get':\n return ['query'];\n default:\n return;\n }\n};\n\ntype EventHooks = {\n [K in keyof Required<NonNullable<Hooks['events']>>]: Array<\n NonNullable<NonNullable<Hooks['events']>[K]>\n >;\n};\n\nexport class PluginInstance<T extends Plugin.Types = Plugin.Types> {\n api: T['api'];\n config: Omit<T['resolvedConfig'], 'name'>;\n context: Context;\n dependencies: Required<Plugin.Config<T>>['dependencies'] = [];\n private eventHooks: EventHooks;\n gen: IProject;\n private handler: Plugin.Config<T>['handler'];\n name: T['resolvedConfig']['name'];\n /**\n * The package metadata and utilities for the current context, constructed\n * from the provided dependencies. Used for managing package-related\n * information such as name, version, and dependency resolution during\n * code generation.\n */\n package: Dependency;\n\n constructor(\n props: Pick<Required<Plugin.Config<T>>, 'config' | 'dependencies' | 'handler'> & {\n api?: T['api'];\n context: Context;\n gen: IProject;\n name: string;\n },\n ) {\n this.api = props.api ?? {};\n this.config = props.config;\n this.context = props.context;\n this.dependencies = props.dependencies;\n this.eventHooks = this.buildEventHooks();\n this.gen = props.gen;\n this.handler = props.handler;\n this.name = props.name;\n this.package = props.context.package;\n }\n\n external(\n resource: Required<SymbolMeta>['resource'],\n meta?: Omit<SymbolMeta, 'category' | 'resource'>,\n ): Symbol {\n return this.gen.symbols.reference({\n ...meta,\n category: 'external',\n resource,\n });\n }\n\n /**\n * Iterates over various input elements as specified by the event types, in\n * a specific order: servers, schemas, parameters, request bodies, then\n * operations.\n *\n * This ensures, for example, that schemas are always processed before\n * operations, which may reference them.\n *\n * @template TKind - The event type(s) to yield. Defaults to all event types.\n * @param events - The event types to walk over. If none are provided, all event types are included.\n * @param callback - Function to execute for each event.\n *\n * @example\n * // Iterate over all operations and schemas\n * plugin.forEach('operation', 'schema', (event) => {\n * if (event.type === 'operation') {\n * // handle operation\n * } else if (event.type === 'schema') {\n * // handle schema\n * }\n * });\n */\n forEach<TKind extends IrTopLevelKind = IrTopLevelKind>(\n ...args: [...events: ReadonlyArray<TKind>, callback: (event: WalkEvent<TKind>) => void]\n ): void;\n forEach<TKind extends IrTopLevelKind = IrTopLevelKind>(\n ...args: [\n ...events: ReadonlyArray<TKind>,\n callback: (event: WalkEvent<TKind>) => void,\n options: WalkOptions<TKind>,\n ]\n ): void;\n forEach<TKind extends IrTopLevelKind = IrTopLevelKind>(\n ...args: [\n ...events: ReadonlyArray<TKind>,\n callback: (event: WalkEvent<TKind>) => void,\n options: any,\n ]\n ): void {\n if (!this.context.graph) {\n throw new Error('No graph available in context');\n }\n\n let callback: (event: WalkEvent<TKind>) => void;\n let events: ReadonlyArray<TKind>;\n let options: WalkOptions<TKind> = {\n getPointerPriority: getIrPointerPriority,\n // default functions operate on the full union of kinds; cast them\n // to the WalkOptions generic to keep strict typing for callers.\n matchPointerToGroup: matchIrPointerToGroup as unknown as MatchPointerToGroupFn<TKind>,\n order: 'topological',\n preferGroups: preferGroups as unknown as ReadonlyArray<TKind>,\n };\n if (typeof args[args.length - 1] === 'function') {\n events = args.slice(0, -1);\n callback = args[args.length - 1];\n } else {\n events = args.slice(0, -2);\n callback = args[args.length - 2];\n options = {\n ...options,\n ...args[args.length - 1],\n };\n }\n const eventSet = new Set(events.length ? events : irTopLevelKinds);\n\n walk(\n this.context.graph,\n (pointer, nodeInfo) => {\n const result = matchIrPointerToGroup(pointer);\n if (!result.matched || !eventSet.has(result.kind)) return;\n let event: WalkEvent | undefined;\n const baseEvent: BaseEvent = {\n _path: jsonPointerToPath(pointer),\n pointer,\n tags: nodeInfo.tags ? Array.from(nodeInfo.tags) : undefined,\n };\n switch (result.kind) {\n case 'operation':\n event = {\n ...baseEvent,\n method: nodeInfo.key as keyof IR.PathItemObject,\n operation: nodeInfo.node as IR.OperationObject,\n path: baseEvent._path[1] as string,\n type: result.kind,\n } satisfies WalkEvent<'operation'>;\n break;\n case 'parameter':\n event = {\n ...baseEvent,\n name: nodeInfo.key as string,\n parameter: nodeInfo.node as IR.ParameterObject,\n type: result.kind,\n } satisfies WalkEvent<'parameter'>;\n break;\n case 'requestBody':\n event = {\n ...baseEvent,\n name: nodeInfo.key as string,\n requestBody: nodeInfo.node as IR.RequestBodyObject,\n type: result.kind,\n } satisfies WalkEvent<'requestBody'>;\n break;\n case 'schema':\n event = {\n ...baseEvent,\n name: nodeInfo.key as string,\n schema: nodeInfo.node as IR.SchemaObject,\n type: result.kind,\n } satisfies WalkEvent<'schema'>;\n break;\n case 'server':\n event = {\n ...baseEvent,\n server: nodeInfo.node as IR.ServerObject,\n type: result.kind,\n } satisfies WalkEvent<'server'>;\n break;\n case 'webhook':\n event = {\n ...baseEvent,\n key: baseEvent._path[1] as string,\n method: nodeInfo.key as keyof IR.PathItemObject,\n operation: nodeInfo.node as IR.OperationObject,\n type: result.kind,\n } satisfies WalkEvent<'webhook'>;\n break;\n }\n if (event) {\n try {\n callback(event as WalkEvent<TKind>);\n } catch (error) {\n this.forEachError(error, event);\n }\n }\n },\n options,\n );\n }\n\n /**\n * Retrieves a registered plugin instance by its name from the context. This\n * allows plugins to access other plugins that have been registered in the\n * same context, enabling cross-plugin communication and dependencies.\n *\n * @param name Plugin name as defined in the configuration.\n * @returns The plugin instance if found, undefined otherwise.\n */\n getPlugin<TName extends keyof PluginConfigMap>(\n name: TName,\n ): TName extends any ? PluginInstance<PluginConfigMap[TName]> | undefined : never {\n return this.context.plugins[name] as any;\n }\n\n /**\n * Retrieves a registered plugin instance by its name from the context. This\n * allows plugins to access other plugins that have been registered in the\n * same context, enabling cross-plugin communication and dependencies.\n *\n * @param name Plugin name as defined in the configuration.\n * @returns The plugin instance if found, throw otherwise.\n */\n getPluginOrThrow<TName extends keyof PluginConfigMap>(\n name: TName,\n ): TName extends any ? PluginInstance<PluginConfigMap[TName]> : never {\n const plugin = this.getPlugin(name);\n if (!plugin) throw new Error(`plugin not found ${name}`);\n return plugin as any;\n }\n\n getSymbol(identifier: SymbolIdentifier): Symbol | undefined {\n return this.gen.symbols.get(identifier);\n }\n\n hooks = {\n operation: {\n isMutation: (operation: IR.OperationObject): boolean =>\n this.isOperationKind(operation, 'mutation'),\n isQuery: (operation: IR.OperationObject): boolean => this.isOperationKind(operation, 'query'),\n },\n };\n\n /**\n * Registers an intent in the context's intent list.\n *\n * @param intent The intent to be registered.\n * @returns void\n */\n intent(intent: ExampleIntent): void {\n this.context.intents.push(intent);\n }\n\n isSymbolRegistered(identifier: SymbolIdentifier): boolean {\n return this.gen.symbols.isRegistered(identifier);\n }\n\n /**\n * Sets or adds a node to the project graph.\n *\n * @param node The node to be added or updated in the project graph.\n * @param index The index at which to update the node. If undefined, the node will be added.\n * @returns The index of the added node or void if updated.\n */\n node<T extends number | undefined = undefined>(\n node: Node | null,\n index?: T,\n ): T extends number ? void : number {\n for (const hook of this.eventHooks['node:set:before']) {\n hook({ node, plugin: this as any });\n }\n const result =\n index !== undefined ? this.gen.nodes.update(index, node) : this.gen.nodes.add(node);\n for (const hook of this.eventHooks['node:set:after']) {\n hook({ node, plugin: this as any });\n }\n return result as T extends number ? void : number;\n }\n\n querySymbol(filter: SymbolMeta): Symbol<ResolvedNode> | undefined {\n return this.gen.symbols.query(filter)[0] as Symbol<ResolvedNode> | undefined;\n }\n\n referenceSymbol(meta: SymbolMeta): Symbol<ResolvedNode> {\n return this.gen.symbols.reference(meta) as Symbol<ResolvedNode>;\n }\n\n /**\n * Alias for `symbol()` method with single argument.\n */\n registerSymbol(symbol: SymbolIn): Symbol<ResolvedNode> {\n return this.symbol(symbol.name, symbol) as Symbol<ResolvedNode>;\n }\n\n /**\n * Executes plugin's handler function.\n */\n async run(): Promise<void> {\n for (const hook of this.eventHooks['plugin:handler:before']) {\n hook({ plugin: this as any });\n }\n await this.handler({ plugin: this });\n for (const hook of this.eventHooks['plugin:handler:after']) {\n hook({ plugin: this as any });\n }\n }\n\n symbol(name: SymbolIn['name'], symbol?: Omit<SymbolIn, 'name'>): Symbol<ResolvedNode> {\n const symbolIn: SymbolIn = {\n ...symbol,\n meta: {\n pluginName: path.isAbsolute(this.name) ? 'custom' : this.name,\n ...symbol?.meta,\n },\n name,\n };\n if (symbolIn.getExportFromFilePath === undefined) {\n symbolIn.getExportFromFilePath = this.getSymbolExportFromFilePath.bind(this);\n }\n if (symbolIn.getFilePath === undefined) {\n symbolIn.getFilePath = this.getSymbolFilePath.bind(this);\n }\n for (const hook of this.eventHooks['symbol:register:before']) {\n hook({ plugin: this as any, symbol: symbolIn });\n }\n const symbolOut = this.gen.symbols.register(symbolIn);\n for (const hook of this.eventHooks['symbol:register:after']) {\n hook({ plugin: this as any, symbol: symbolOut });\n }\n return symbolOut as Symbol<ResolvedNode>;\n }\n\n /**\n * Registers a symbol only if it does not already exist based on the provided\n * metadata. This prevents duplicate symbols from being created in the project.\n */\n symbolOnce(name: SymbolIn['name'], symbol?: Omit<SymbolIn, 'name'>): Symbol {\n const meta = {\n ...symbol?.meta,\n };\n if (symbol?.external) {\n meta.category = 'external';\n meta.resource = symbol.external;\n }\n const existing = this.querySymbol(meta);\n if (existing) return existing;\n return this.symbol(name, { ...symbol, meta });\n }\n\n private buildEventHooks(): EventHooks {\n const result: EventHooks = {\n 'node:set:after': [],\n 'node:set:before': [],\n 'plugin:handler:after': [],\n 'plugin:handler:before': [],\n 'symbol:register:after': [],\n 'symbol:register:before': [],\n };\n const scopes = [this.config['~hooks']?.events, this.context.config.parser.hooks.events];\n for (const scope of scopes) {\n if (!scope) continue;\n for (const [key, value] of Object.entries(scope)) {\n if (value) {\n result[key as keyof typeof result].push(value.bind(scope) as any);\n }\n }\n }\n return result;\n }\n\n private forEachError(error: unknown, event: WalkEvent) {\n const originalError = error instanceof Error ? error : new Error(String(error));\n throw new HeyApiError({\n args: [event],\n error: originalError,\n event: event.type,\n name: 'Error',\n pluginName: this.name,\n });\n }\n\n private getSymbolExportFromFilePath(symbol: Symbol): ReadonlyArray<string> | undefined {\n const hooks = [this.config['~hooks']?.symbols, this.context.config.parser.hooks.symbols];\n for (const hook of hooks) {\n const result = hook?.getExportFromFilePath?.(symbol);\n if (result !== undefined) return result;\n }\n\n // default logic below\n const entryFile = this.context.config.output.indexFile ?? this.context.config.output.entryFile;\n if (symbol.external || !entryFile) return;\n\n const includeInEntry = this.config.exportFromIndex ?? this.config.includeInEntry;\n if (\n (typeof includeInEntry === 'boolean' && !includeInEntry) ||\n (typeof includeInEntry === 'function' && !includeInEntry(symbol))\n ) {\n return;\n }\n\n const language = symbol.node?.language;\n if (!language) return;\n\n const moduleEntryName = this.gen.moduleEntryNames[language];\n if (!moduleEntryName) return;\n\n return [moduleEntryName];\n }\n\n private getSymbolFilePath(symbol: Symbol): string | undefined {\n const hooks = [this.config['~hooks']?.symbols, this.context.config.parser.hooks.symbols];\n for (const hook of hooks) {\n const result = hook?.getFilePath?.(symbol);\n if (result !== undefined) return result;\n }\n return defaultGetFilePath(symbol);\n }\n\n private isOperationKind(operation: IR.OperationObject, kind: 'mutation' | 'query'): boolean {\n const method = kind === 'query' ? 'isQuery' : 'isMutation';\n const hooks = [\n this.config['~hooks']?.operations?.[method],\n this.config['~hooks']?.operations?.getKind,\n this.context.config.parser.hooks.operations?.[method],\n this.context.config.parser.hooks.operations?.getKind,\n defaultGetKind,\n ];\n for (const hook of hooks) {\n if (hook) {\n const result = hook(operation);\n if (result !== undefined) {\n return typeof result === 'boolean' ? result : result.includes(kind);\n }\n }\n }\n return false;\n }\n}\n","import type { Logger, Project } from '@hey-api/codegen-core';\n\nimport type { AnyConfig } from '../config/shared';\nimport type { Dependency } from '../config/utils/dependencies';\nimport { dependencyFactory } from '../config/utils/dependencies';\nimport type { Graph } from '../graph';\nimport { PluginInstance } from '../plugins/shared/utils/instance';\nimport type { Plugin, PluginConfigMap, PluginNames } from '../plugins/types';\nimport { resolveRef } from '../utils/ref';\nimport type { ExampleIntent } from './intents';\nimport type { IR } from './types';\n\nexport class Context<Spec extends Record<string, any> = any, Config extends AnyConfig = AnyConfig> {\n /**\n * Configuration for parsing and generating the output. This\n * is a mix of user-provided and default values.\n */\n config: Config;\n /**\n * The code generation project instance used to manage files, symbols,\n */\n gen: Project;\n /**\n * The dependency graph built from the intermediate representation.\n */\n graph: Graph | undefined;\n /**\n * Intents declared by plugins.\n */\n intents: Array<ExampleIntent> = [];\n /**\n * Intermediate representation model obtained from `spec`.\n */\n ir: IR.Model = {};\n /**\n * Logger instance.\n */\n logger: Logger;\n /**\n * The package metadata and utilities for the current context, constructed\n * from the provided dependencies. Used for managing package-related\n * information such as name, version, and dependency resolution during\n * code generation.\n */\n package: Dependency;\n /**\n * A map of registered plugin instances, keyed by plugin name. Plugins are\n * registered through the `registerPlugin` method and can be accessed by\n * their configured name from the config.\n */\n plugins: Partial<Record<PluginNames, PluginInstance<PluginConfigMap[keyof PluginConfigMap]>>> =\n {};\n /**\n * Resolved specification from `input`.\n */\n spec: Spec;\n\n constructor({\n config,\n dependencies,\n logger,\n project,\n spec,\n }: {\n config: Config;\n dependencies: Record<string, string>;\n logger: Logger;\n project: Project;\n spec: Spec;\n }) {\n this.config = config;\n this.gen = project;\n this.logger = logger;\n this.package = dependencyFactory(dependencies);\n this.spec = spec;\n }\n\n /**\n * Returns a resolved and dereferenced schema from `spec`.\n */\n dereference<T>(schema: { $ref: string }) {\n const resolved = this.resolveRef<T>(schema.$ref);\n const dereferenced = {\n ...schema,\n ...resolved,\n } as T;\n // @ts-expect-error\n delete dereferenced.$ref;\n return dereferenced;\n }\n\n /**\n * Registers a new plugin to the global context.\n *\n * @param name Plugin name.\n * @returns Registered plugin instance.\n */\n private registerPlugin<T extends PluginNames>(\n name: T,\n ): T extends keyof PluginConfigMap ? PluginInstance<PluginConfigMap[T]> : PluginInstance {\n const plugin = (this.config.plugins as Record<string, Plugin.Config<Plugin.Types>>)[name]!;\n const instance = new PluginInstance({\n api: plugin.api,\n config: plugin.config as any,\n context: this as any,\n dependencies: plugin.dependencies ?? [],\n gen: this.gen,\n handler: plugin.handler,\n name: plugin.name,\n });\n (this.plugins as Record<string, any>)[instance.name] = instance;\n return instance as T extends keyof PluginConfigMap\n ? PluginInstance<PluginConfigMap[T]>\n : PluginInstance;\n }\n\n /**\n * Registers all plugins in the order specified by the configuration and returns\n * an array of the registered PluginInstance objects. Each plugin is instantiated\n * and added to the context's plugins map.\n *\n * @returns {ReadonlyArray<PluginInstance>} An array of registered plugin instances in order.\n */\n registerPlugins(): ReadonlyArray<PluginInstance> {\n return this.config.pluginOrder.map((name) => this.registerPlugin(name));\n }\n\n // TODO: parser - works the same as resolveRef, but for IR schemas.\n // for now, they map 1:1, but if they diverge (like with OpenAPI 2.0),\n // we will want to rewrite $refs at parse time, so they continue pointing\n // to the correct IR location\n resolveIrRef<T>($ref: string) {\n return resolveRef<T>({\n $ref,\n spec: this.ir,\n });\n }\n\n /**\n * Returns a resolved reference from `spec`.\n */\n resolveRef<T>($ref: string) {\n return resolveRef<T>({\n $ref,\n spec: this.spec,\n });\n }\n}\n","import type { MaybePromise } from '@hey-api/types';\n\nimport type { CodeSampleObject } from '..//openApi/shared/types';\nimport type { IR } from './types';\n\nexport interface ExampleIntent {\n run(ctx: IntentContext): MaybePromise<void>;\n}\n\nexport class IntentContext<Spec extends Record<string, any> = any> {\n private spec: Spec;\n\n constructor(spec: Spec) {\n this.spec = spec;\n }\n\n private getOperation(path: string, method: string): Record<string, any> | undefined {\n const paths = (this.spec as any).paths;\n if (!paths) return;\n return paths[path]?.[method];\n }\n\n setExample(operation: IR.OperationObject, example: CodeSampleObject): void {\n const source = this.getOperation(operation.path, operation.method);\n if (!source) return;\n source['x-codeSamples'] ||= [];\n source['x-codeSamples'].push(example);\n }\n}\n","import { pathToJsonPointer } from '../utils/ref';\nimport type { IR } from './types';\n\nexport interface SchemaProcessor {\n /** Current inherited context (set by withContext) */\n readonly context: {\n readonly anchor: string | undefined;\n readonly tags: ReadonlyArray<string> | undefined;\n };\n /** Check if pointer was already emitted */\n hasEmitted: (path: ReadonlyArray<string | number>) => boolean;\n /** Mark pointer as emitted. Returns false if already emitted. */\n markEmitted: (path: ReadonlyArray<string | number>) => boolean;\n /** Execute with inherited context for nested extractions */\n withContext: <T>(ctx: { anchor?: string; tags?: ReadonlyArray<string> }, fn: () => T) => T;\n}\n\nexport interface SchemaProcessorContext {\n meta: { resource: string; resourceId: string; role?: string };\n namingAnchor?: string;\n path: ReadonlyArray<string | number>;\n schema: IR.SchemaObject;\n tags?: ReadonlyArray<string>;\n}\n\nexport interface SchemaProcessorResult<\n Context extends SchemaProcessorContext = SchemaProcessorContext,\n> {\n process: (ctx: Context) => void;\n}\n\nexport type SchemaExtractor<Context extends SchemaProcessorContext = SchemaProcessorContext> = (\n ctx: Context,\n) => IR.SchemaObject;\n\nexport function createSchemaProcessor(): SchemaProcessor {\n const emitted = new Set<string>();\n let contextTags: ReadonlyArray<string> | undefined;\n let contextAnchor: string | undefined;\n\n return {\n get context() {\n return {\n anchor: contextAnchor,\n tags: contextTags,\n };\n },\n hasEmitted(path) {\n return emitted.has(pathToJsonPointer(path));\n },\n markEmitted(path) {\n const pointer = pathToJsonPointer(path);\n if (emitted.has(pointer)) return false;\n emitted.add(pointer);\n return true;\n },\n withContext(ctx, fn) {\n const prevTags = contextTags;\n const prevAnchor = contextAnchor;\n contextTags = ctx.tags;\n contextAnchor = ctx.anchor;\n try {\n return fn();\n } finally {\n contextTags = prevTags;\n contextAnchor = prevAnchor;\n }\n },\n };\n}\n","import type { Ref } from '@hey-api/codegen-core';\nimport { fromRef, ref } from '@hey-api/codegen-core';\n\nimport type { SchemaWithType } from '../plugins/shared/types/schema';\nimport { deduplicateSchema } from './schema';\nimport type { IR } from './types';\n\n/**\n * Context passed to all visitor methods.\n */\nexport interface SchemaVisitorContext<TPlugin = unknown> {\n /** Current path in the schema tree. */\n path: Ref<ReadonlyArray<string | number>>;\n /** The plugin instance. */\n plugin: TPlugin;\n}\n\n/**\n * The walk function signature. Fully generic over TResult.\n */\nexport type Walker<TResult, TPlugin = unknown> = (\n schema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n) => TResult;\n\n/**\n * The visitor interface. Plugins define their own TResult type.\n *\n * The walker handles orchestration (dispatch, deduplication, path tracking).\n * Result shape and semantics are entirely plugin-defined.\n */\nexport interface SchemaVisitor<TResult, TPlugin = unknown> {\n /**\n * Apply modifiers to a result.\n */\n applyModifiers(\n result: TResult,\n ctx: SchemaVisitorContext<TPlugin>,\n context?: {\n /** Is this property optional? */\n optional?: boolean;\n },\n ): unknown;\n array(\n schema: SchemaWithType<'array'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n boolean(schema: SchemaWithType<'boolean'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n enum(\n schema: SchemaWithType<'enum'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n integer(schema: SchemaWithType<'integer'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n /**\n * Called before any dispatch logic. Return a result to short-circuit,\n * or undefined to continue normal dispatch.\n */\n intercept?(\n schema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult | undefined;\n /**\n * Handle intersection types. Receives already-walked child results.\n */\n intersection(\n items: Array<TResult>,\n schemas: ReadonlyArray<IR.SchemaObject>,\n parentSchema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n ): TResult;\n never(schema: SchemaWithType<'never'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n null(schema: SchemaWithType<'null'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n number(schema: SchemaWithType<'number'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n object(\n schema: SchemaWithType<'object'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n /**\n * Called after each typed schema visitor returns.\n */\n postProcess?(\n result: TResult,\n schema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n ): TResult;\n /**\n * Handle $ref to another schema.\n */\n reference($ref: string, schema: IR.SchemaObject, ctx: SchemaVisitorContext<TPlugin>): TResult;\n string(schema: SchemaWithType<'string'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n tuple(\n schema: SchemaWithType<'tuple'>,\n ctx: SchemaVisitorContext<TPlugin>,\n walk: Walker<TResult, TPlugin>,\n ): TResult;\n undefined(schema: SchemaWithType<'undefined'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n /**\n * Handle union types. Receives already-walked child results.\n */\n union(\n items: Array<TResult>,\n schemas: ReadonlyArray<IR.SchemaObject>,\n parentSchema: IR.SchemaObject,\n ctx: SchemaVisitorContext<TPlugin>,\n ): TResult;\n unknown(schema: SchemaWithType<'unknown'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n void(schema: SchemaWithType<'void'>, ctx: SchemaVisitorContext<TPlugin>): TResult;\n}\n\n/**\n * Create a schema walker from a visitor.\n *\n * The walker handles:\n * - Dispatch order ($ref โ†’ type โ†’ items โ†’ fallback)\n * - Deduplication of union/intersection schemas\n * - Path tracking for child schemas\n */\nexport function createSchemaWalker<TResult, TPlugin = unknown>(\n visitor: SchemaVisitor<TResult, TPlugin>,\n): Walker<TResult, TPlugin> {\n const walk: Walker<TResult, TPlugin> = (schema, ctx) => {\n // escape hatch\n if (visitor.intercept) {\n const intercepted = visitor.intercept(schema, ctx, walk);\n if (intercepted !== undefined) {\n return intercepted;\n }\n }\n\n if (schema.$ref) {\n return visitor.reference(schema.$ref, schema, ctx);\n }\n\n if (schema.type) {\n let result = visitTyped(schema as SchemaWithType, ctx, visitor, walk);\n if (visitor.postProcess) {\n result = visitor.postProcess(result, schema, ctx);\n }\n return result;\n }\n\n if (schema.items) {\n const deduplicated = deduplicateSchema({ schema });\n\n // deduplication might collapse to a single schema\n if (!deduplicated.items) {\n return walk(deduplicated, ctx);\n }\n\n const itemResults = deduplicated.items.map((item, index) =>\n walk(item, {\n ...ctx,\n path: ref([...fromRef(ctx.path), 'items', index]),\n }),\n );\n\n return deduplicated.logicalOperator === 'and'\n ? visitor.intersection(itemResults, deduplicated.items, schema, ctx)\n : visitor.union(itemResults, deduplicated.items, schema, ctx);\n }\n\n // fallback\n return visitor.unknown({ type: 'unknown' }, ctx);\n };\n\n return walk;\n}\n\n/**\n * Dispatch to the appropriate visitor method based on schema type.\n */\nfunction visitTyped<TResult, TPlugin>(\n schema: SchemaWithType,\n ctx: SchemaVisitorContext<TPlugin>,\n visitor: SchemaVisitor<TResult, TPlugin>,\n walk: Walker<TResult, TPlugin>,\n): TResult {\n switch (schema.type) {\n case 'array':\n return visitor.array(schema as SchemaWithType<'array'>, ctx, walk);\n case 'boolean':\n return visitor.boolean(schema as SchemaWithType<'boolean'>, ctx);\n case 'enum':\n return visitor.enum(schema as SchemaWithType<'enum'>, ctx, walk);\n case 'integer':\n return visitor.integer(schema as SchemaWithType<'integer'>, ctx);\n case 'never':\n return visitor.never(schema as SchemaWithType<'never'>, ctx);\n case 'null':\n return visitor.null(schema as SchemaWithType<'null'>, ctx);\n case 'number':\n return visitor.number(schema as SchemaWithType<'number'>, ctx);\n case 'object':\n return visitor.object(schema as SchemaWithType<'object'>, ctx, walk);\n case 'string':\n return visitor.string(schema as SchemaWithType<'string'>, ctx);\n case 'tuple':\n return visitor.tuple(schema as SchemaWithType<'tuple'>, ctx, walk);\n case 'undefined':\n return visitor.undefined(schema as SchemaWithType<'undefined'>, ctx);\n case 'unknown':\n return visitor.unknown(schema as SchemaWithType<'unknown'>, ctx);\n case 'void':\n return visitor.void(schema as SchemaWithType<'void'>, ctx);\n }\n}\n\n/**\n * Helper to create a child context with an extended path.\n */\nexport function childContext<TPlugin>(\n ctx: SchemaVisitorContext<TPlugin>,\n ...segments: ReadonlyArray<string | number>\n): SchemaVisitorContext<TPlugin> {\n return {\n ...ctx,\n path: ref([...fromRef(ctx.path), ...segments]),\n };\n}\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Parser } from '../../../config/parser/types';\nimport { createOperationKey } from '../../../ir/operation';\nimport type { PathItemObject, PathsObject } from '../../../openApi/3.1.x/types/spec';\nimport type { OpenApi } from '../../../openApi/types';\nimport type { ResourceMetadata } from '../graph/meta';\nimport { httpMethods } from './operation';\n\ntype FilterNamespace = 'body' | 'operation' | 'parameter' | 'response' | 'schema' | 'unknown';\n\nconst namespaceNeedle = '/';\n\nexport const addNamespace = (namespace: FilterNamespace, value: string = ''): string =>\n `${namespace}${namespaceNeedle}${value}`;\n\nexport const removeNamespace = (\n key: string,\n): {\n name: string;\n namespace: FilterNamespace;\n} => {\n const index = key.indexOf(namespaceNeedle);\n const name = key.slice(index + 1);\n return {\n name,\n namespace: key.slice(0, index)! as FilterNamespace,\n };\n};\n\n/**\n * Converts reference strings from OpenAPI $ref keywords into namespaces.\n *\n * @example '#/components/schemas/Foo' -> 'schema'\n */\nexport const stringToNamespace = (value: string): FilterNamespace => {\n switch (value) {\n case 'parameters':\n return 'parameter';\n case 'requestBodies':\n return 'body';\n case 'responses':\n return 'response';\n case 'definitions':\n case 'schemas':\n return 'schema';\n default:\n return 'unknown';\n }\n};\n\ntype FiltersConfigToState<T> = {\n [K in keyof T]-?: NonNullable<T[K]> extends ReadonlyArray<infer U>\n ? Set<U>\n : NonNullable<T[K]> extends object\n ? FiltersConfigToState<NonNullable<T[K]>>\n : T[K];\n};\n\nexport type Filters = FiltersConfigToState<NonNullable<Parser['filters']>>;\n\ninterface SetAndRegExps {\n regexps: Array<RegExp>;\n set: Set<string>;\n}\n\nconst createFiltersSetAndRegExps = (\n type: FilterNamespace,\n filters: ReadonlyArray<string> | undefined,\n): SetAndRegExps => {\n const keys: Array<string> = [];\n const regexps: Array<RegExp> = [];\n if (filters) {\n for (const value of filters) {\n if (value.startsWith('/') && value.endsWith('/')) {\n regexps.push(new RegExp(value.slice(1, value.length - 1)));\n } else {\n keys.push(addNamespace(type, value));\n }\n }\n }\n return {\n regexps,\n set: new Set(keys),\n };\n};\n\ninterface CollectFiltersSetFromRegExps {\n excludeOperations: SetAndRegExps;\n excludeParameters: SetAndRegExps;\n excludeRequestBodies: SetAndRegExps;\n excludeResponses: SetAndRegExps;\n excludeSchemas: SetAndRegExps;\n includeOperations: SetAndRegExps;\n includeParameters: SetAndRegExps;\n includeRequestBodies: SetAndRegExps;\n includeResponses: SetAndRegExps;\n includeSchemas: SetAndRegExps;\n}\n\nconst collectFiltersSetFromRegExpsOpenApiV2 = ({\n excludeOperations,\n excludeSchemas,\n includeOperations,\n includeSchemas,\n spec,\n}: CollectFiltersSetFromRegExps & {\n spec: OpenApi.V2_0_X;\n}) => {\n if ((excludeOperations.regexps.length || includeOperations.regexps.length) && spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = createOperationKey({ method, path });\n if (excludeOperations.regexps.some((regexp) => regexp.test(key))) {\n excludeOperations.set.add(addNamespace('operation', key));\n }\n if (includeOperations.regexps.some((regexp) => regexp.test(key))) {\n includeOperations.set.add(addNamespace('operation', key));\n }\n }\n }\n }\n\n if (spec.definitions) {\n // TODO: add parameters\n\n if (excludeSchemas.regexps.length || includeSchemas.regexps.length) {\n for (const key of Object.keys(spec.definitions)) {\n if (excludeSchemas.regexps.some((regexp) => regexp.test(key))) {\n excludeSchemas.set.add(addNamespace('schema', key));\n }\n if (includeSchemas.regexps.some((regexp) => regexp.test(key))) {\n includeSchemas.set.add(addNamespace('schema', key));\n }\n }\n }\n }\n};\n\nconst collectFiltersSetFromRegExpsOpenApiV3 = ({\n excludeOperations,\n excludeParameters,\n excludeRequestBodies,\n excludeResponses,\n excludeSchemas,\n includeOperations,\n includeParameters,\n includeRequestBodies,\n includeResponses,\n includeSchemas,\n spec,\n}: CollectFiltersSetFromRegExps & {\n spec: OpenApi.V3_0_X | OpenApi.V3_1_X;\n}) => {\n if ((excludeOperations.regexps.length || includeOperations.regexps.length) && spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = createOperationKey({ method, path });\n if (excludeOperations.regexps.some((regexp) => regexp.test(key))) {\n excludeOperations.set.add(addNamespace('operation', key));\n }\n if (includeOperations.regexps.some((regexp) => regexp.test(key))) {\n includeOperations.set.add(addNamespace('operation', key));\n }\n }\n }\n }\n\n if (spec.components) {\n if (\n (excludeParameters.regexps.length || includeParameters.regexps.length) &&\n spec.components.parameters\n ) {\n for (const key of Object.keys(spec.components.parameters)) {\n if (excludeParameters.regexps.some((regexp) => regexp.test(key))) {\n excludeParameters.set.add(addNamespace('parameter', key));\n }\n if (includeParameters.regexps.some((regexp) => regexp.test(key))) {\n includeParameters.set.add(addNamespace('parameter', key));\n }\n }\n }\n\n if (\n (excludeRequestBodies.regexps.length || includeRequestBodies.regexps.length) &&\n spec.components.requestBodies\n ) {\n for (const key of Object.keys(spec.components.requestBodies)) {\n if (excludeRequestBodies.regexps.some((regexp) => regexp.test(key))) {\n excludeRequestBodies.set.add(addNamespace('body', key));\n }\n if (includeRequestBodies.regexps.some((regexp) => regexp.test(key))) {\n includeRequestBodies.set.add(addNamespace('body', key));\n }\n }\n }\n\n if (\n (excludeResponses.regexps.length || includeResponses.regexps.length) &&\n spec.components.responses\n ) {\n for (const key of Object.keys(spec.components.responses)) {\n if (excludeResponses.regexps.some((regexp) => regexp.test(key))) {\n excludeResponses.set.add(addNamespace('response', key));\n }\n if (includeResponses.regexps.some((regexp) => regexp.test(key))) {\n includeResponses.set.add(addNamespace('response', key));\n }\n }\n }\n\n if (\n (excludeSchemas.regexps.length || includeSchemas.regexps.length) &&\n spec.components.schemas\n ) {\n for (const key of Object.keys(spec.components.schemas)) {\n if (excludeSchemas.regexps.some((regexp) => regexp.test(key))) {\n excludeSchemas.set.add(addNamespace('schema', key));\n }\n if (includeSchemas.regexps.some((regexp) => regexp.test(key))) {\n includeSchemas.set.add(addNamespace('schema', key));\n }\n }\n }\n }\n};\n\nconst collectFiltersSetFromRegExps = ({\n spec,\n ...filters\n}: CollectFiltersSetFromRegExps & {\n spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X;\n}): void => {\n if ('swagger' in spec) {\n collectFiltersSetFromRegExpsOpenApiV2({ ...filters, spec });\n } else {\n collectFiltersSetFromRegExpsOpenApiV3({ ...filters, spec });\n }\n};\n\nexport const createFilters = (\n config: Parser['filters'],\n spec: OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X,\n logger: Logger,\n): Filters => {\n const eventCreateFilters = logger.timeEvent('create-filters');\n const excludeOperations = createFiltersSetAndRegExps('operation', config?.operations?.exclude);\n const includeOperations = createFiltersSetAndRegExps('operation', config?.operations?.include);\n const excludeParameters = createFiltersSetAndRegExps('parameter', config?.parameters?.exclude);\n const includeParameters = createFiltersSetAndRegExps('parameter', config?.parameters?.include);\n const excludeRequestBodies = createFiltersSetAndRegExps('body', config?.requestBodies?.exclude);\n const includeRequestBodies = createFiltersSetAndRegExps('body', config?.requestBodies?.include);\n const excludeResponses = createFiltersSetAndRegExps('response', config?.responses?.exclude);\n const includeResponses = createFiltersSetAndRegExps('response', config?.responses?.include);\n const excludeSchemas = createFiltersSetAndRegExps('schema', config?.schemas?.exclude);\n const includeSchemas = createFiltersSetAndRegExps('schema', config?.schemas?.include);\n\n collectFiltersSetFromRegExps({\n excludeOperations,\n excludeParameters,\n excludeRequestBodies,\n excludeResponses,\n excludeSchemas,\n includeOperations,\n includeParameters,\n includeRequestBodies,\n includeResponses,\n includeSchemas,\n spec,\n });\n\n const filters: Filters = {\n deprecated: config?.deprecated ?? true,\n operations: {\n exclude: excludeOperations.set,\n include: includeOperations.set,\n },\n orphans: config?.orphans ?? false,\n parameters: {\n exclude: excludeParameters.set,\n include: includeParameters.set,\n },\n preserveOrder: config?.preserveOrder ?? false,\n requestBodies: {\n exclude: excludeRequestBodies.set,\n include: includeRequestBodies.set,\n },\n responses: {\n exclude: excludeResponses.set,\n include: includeResponses.set,\n },\n schemas: {\n exclude: excludeSchemas.set,\n include: includeSchemas.set,\n },\n tags: {\n exclude: new Set(config?.tags?.exclude),\n include: new Set(config?.tags?.include),\n },\n };\n eventCreateFilters.timeEnd();\n return filters;\n};\n\nexport const hasFilters = (config: Parser['filters']): boolean => {\n if (!config) {\n return false;\n }\n\n // we explicitly want to strip orphans or deprecated\n if (config.orphans === false || config.deprecated === false) {\n return true;\n }\n\n return Boolean(\n config.operations?.exclude?.length ||\n config.operations?.include?.length ||\n config.parameters?.exclude?.length ||\n config.parameters?.include?.length ||\n config.requestBodies?.exclude?.length ||\n config.requestBodies?.include?.length ||\n config.responses?.exclude?.length ||\n config.responses?.include?.length ||\n config.schemas?.exclude?.length ||\n config.schemas?.include?.length ||\n config.tags?.exclude?.length ||\n config.tags?.include?.length,\n );\n};\n\n/**\n * Collect operations that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectOperations = ({\n filters,\n parameters,\n requestBodies,\n resourceMetadata,\n responses,\n schemas,\n}: {\n filters: Filters;\n parameters: Set<string>;\n requestBodies: Set<string>;\n resourceMetadata: ResourceMetadata;\n responses: Set<string>;\n schemas: Set<string>;\n}): {\n operations: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.operations.include.size\n ? filters.operations.include\n : new Set(resourceMetadata.operations.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.operations.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.operations.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n if (\n filters.tags.exclude.size &&\n node.tags.size &&\n [...filters.tags.exclude].some((tag) => node.tags.has(tag))\n ) {\n continue;\n }\n\n if (\n filters.tags.include.size &&\n !new Set([...filters.tags.include].filter((tag) => node.tags.has(tag))).size\n ) {\n continue;\n }\n\n // skip operation if it references any component not included\n if (\n [...node.dependencies].some((dependency) => {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body':\n return !requestBodies.has(dependency);\n case 'parameter':\n return !parameters.has(dependency);\n case 'response':\n return !responses.has(dependency);\n case 'schema':\n return !schemas.has(dependency);\n default:\n return false;\n }\n })\n ) {\n continue;\n }\n\n finalSet.add(key);\n }\n return { operations: finalSet };\n};\n\n/**\n * Collect parameters that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectParameters = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): {\n parameters: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.parameters.include.size\n ? filters.parameters.include\n : new Set(resourceMetadata.parameters.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.parameters.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.parameters.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body': {\n if (filters.requestBodies.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n case 'schema': {\n if (filters.schemas.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!schemas.has(dependency)) {\n schemas.add(dependency);\n }\n break;\n }\n }\n }\n }\n return { parameters: finalSet };\n};\n\n/**\n * Collect request bodies that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectRequestBodies = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): {\n requestBodies: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.requestBodies.include.size\n ? filters.requestBodies.include\n : new Set(resourceMetadata.requestBodies.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.requestBodies.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.requestBodies.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body': {\n if (filters.requestBodies.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n case 'schema': {\n if (filters.schemas.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!schemas.has(dependency)) {\n schemas.add(dependency);\n }\n break;\n }\n }\n }\n }\n return { requestBodies: finalSet };\n};\n\n/**\n * Collect responses that satisfy the include/exclude filters and schema dependencies.\n */\nconst collectResponses = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): {\n responses: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.responses.include.size\n ? filters.responses.include\n : new Set(resourceMetadata.responses.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.responses.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.responses.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'body': {\n if (filters.requestBodies.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n case 'schema': {\n if (filters.schemas.exclude.has(dependency)) {\n finalSet.delete(key);\n } else if (!schemas.has(dependency)) {\n schemas.add(dependency);\n }\n break;\n }\n }\n }\n }\n return { responses: finalSet };\n};\n\n/**\n * Collect schemas that satisfy the include/exclude filters.\n */\nconst collectSchemas = ({\n filters,\n resourceMetadata,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n}): {\n schemas: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = filters.schemas.include.size\n ? filters.schemas.include\n : new Set(resourceMetadata.schemas.keys());\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (filters.schemas.exclude.has(key) || finalSet.has(key)) {\n continue;\n }\n\n const node = resourceMetadata.schemas.get(key);\n\n if (!node) {\n continue;\n }\n\n if (!filters.deprecated && node.deprecated) {\n continue;\n }\n\n finalSet.add(key);\n\n if (!node.dependencies.size) {\n continue;\n }\n\n for (const dependency of node.dependencies) {\n const { namespace } = removeNamespace(dependency);\n switch (namespace) {\n case 'schema': {\n if (!finalSet.has(dependency) && !filters.schemas.exclude.has(dependency)) {\n stack.push(dependency);\n }\n break;\n }\n }\n }\n }\n return { schemas: finalSet };\n};\n\n/**\n * Drop parameters that depend on already excluded parameters.\n */\nconst dropExcludedParameters = ({\n filters,\n parameters,\n resourceMetadata,\n}: {\n filters: Filters;\n parameters: Set<string>;\n resourceMetadata: ResourceMetadata;\n}): void => {\n if (!filters.parameters.exclude.size) {\n return;\n }\n\n for (const key of parameters) {\n const node = resourceMetadata.parameters.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.parameters.exclude) {\n if (node.dependencies.has(excludedKey)) {\n parameters.delete(key);\n break;\n }\n }\n }\n};\n\n/**\n * Drop request bodies that depend on already excluded request bodies.\n */\nconst dropExcludedRequestBodies = ({\n filters,\n requestBodies,\n resourceMetadata,\n}: {\n filters: Filters;\n requestBodies: Set<string>;\n resourceMetadata: ResourceMetadata;\n}): void => {\n if (!filters.requestBodies.exclude.size) {\n return;\n }\n\n for (const key of requestBodies) {\n const node = resourceMetadata.requestBodies.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.requestBodies.exclude) {\n if (node.dependencies.has(excludedKey)) {\n requestBodies.delete(key);\n break;\n }\n }\n }\n};\n\n/**\n * Drop responses that depend on already excluded responses.\n */\nconst dropExcludedResponses = ({\n filters,\n resourceMetadata,\n responses,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n responses: Set<string>;\n}): void => {\n if (!filters.responses.exclude.size) {\n return;\n }\n\n for (const key of responses) {\n const node = resourceMetadata.responses.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.responses.exclude) {\n if (node.dependencies.has(excludedKey)) {\n responses.delete(key);\n break;\n }\n }\n }\n};\n\n/**\n * Drop schemas that depend on already excluded schemas.\n */\nconst dropExcludedSchemas = ({\n filters,\n resourceMetadata,\n schemas,\n}: {\n filters: Filters;\n resourceMetadata: ResourceMetadata;\n schemas: Set<string>;\n}): void => {\n if (!filters.schemas.exclude.size) {\n return;\n }\n\n for (const key of schemas) {\n const node = resourceMetadata.schemas.get(key);\n\n if (!node?.dependencies.size) {\n continue;\n }\n\n for (const excludedKey of filters.schemas.exclude) {\n if (node.dependencies.has(excludedKey)) {\n schemas.delete(key);\n break;\n }\n }\n }\n};\n\nconst dropOrphans = ({\n operationDependencies,\n parameters,\n requestBodies,\n responses,\n schemas,\n}: {\n operationDependencies: Set<string>;\n parameters: Set<string>;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n}) => {\n for (const key of schemas) {\n if (!operationDependencies.has(key)) {\n schemas.delete(key);\n }\n }\n for (const key of parameters) {\n if (!operationDependencies.has(key)) {\n parameters.delete(key);\n }\n }\n for (const key of requestBodies) {\n if (!operationDependencies.has(key)) {\n requestBodies.delete(key);\n }\n }\n for (const key of responses) {\n if (!operationDependencies.has(key)) {\n responses.delete(key);\n }\n }\n};\n\nconst collectOperationDependencies = ({\n operations,\n resourceMetadata,\n}: {\n operations: Set<string>;\n resourceMetadata: ResourceMetadata;\n}): {\n operationDependencies: Set<string>;\n} => {\n const finalSet = new Set<string>();\n const initialSet = new Set(\n [...operations].flatMap((key) => [\n ...(resourceMetadata.operations.get(key)?.dependencies ?? []),\n ]),\n );\n const stack = [...initialSet];\n while (stack.length) {\n const key = stack.pop()!;\n\n if (finalSet.has(key)) {\n continue;\n }\n\n finalSet.add(key);\n\n const { namespace } = removeNamespace(key);\n let dependencies: Set<string> | undefined;\n if (namespace === 'body') {\n dependencies = resourceMetadata.requestBodies.get(key)?.dependencies;\n } else if (namespace === 'operation') {\n dependencies = resourceMetadata.operations.get(key)?.dependencies;\n } else if (namespace === 'parameter') {\n dependencies = resourceMetadata.parameters.get(key)?.dependencies;\n } else if (namespace === 'response') {\n dependencies = resourceMetadata.responses.get(key)?.dependencies;\n } else if (namespace === 'schema') {\n dependencies = resourceMetadata.schemas.get(key)?.dependencies;\n }\n\n if (!dependencies?.size) {\n continue;\n }\n\n for (const dependency of dependencies) {\n if (!finalSet.has(dependency)) {\n stack.push(dependency);\n }\n }\n }\n return { operationDependencies: finalSet };\n};\n\nexport const createFilteredDependencies = ({\n filters,\n logger,\n resourceMetadata,\n}: {\n filters: Filters;\n logger: Logger;\n resourceMetadata: ResourceMetadata;\n}): {\n operations: Set<string>;\n parameters: Set<string>;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n} => {\n const eventCreateFilteredDependencies = logger.timeEvent('create-filtered-dependencies');\n const { schemas } = collectSchemas({ filters, resourceMetadata });\n const { parameters } = collectParameters({\n filters,\n resourceMetadata,\n schemas,\n });\n const { requestBodies } = collectRequestBodies({\n filters,\n resourceMetadata,\n schemas,\n });\n const { responses } = collectResponses({\n filters,\n resourceMetadata,\n schemas,\n });\n\n dropExcludedSchemas({ filters, resourceMetadata, schemas });\n dropExcludedParameters({ filters, parameters, resourceMetadata });\n dropExcludedRequestBodies({ filters, requestBodies, resourceMetadata });\n dropExcludedResponses({ filters, resourceMetadata, responses });\n\n // collect operations after dropping components\n const { operations } = collectOperations({\n filters,\n parameters,\n requestBodies,\n resourceMetadata,\n responses,\n schemas,\n });\n\n if (!filters.orphans && operations.size) {\n const { operationDependencies } = collectOperationDependencies({\n operations,\n resourceMetadata,\n });\n dropOrphans({\n operationDependencies,\n parameters,\n requestBodies,\n responses,\n schemas,\n });\n }\n\n eventCreateFilteredDependencies.timeEnd();\n return {\n operations,\n parameters,\n requestBodies,\n responses,\n schemas,\n };\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Graph } from '../../../graph';\nimport { createOperationKey } from '../../../ir/operation';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport { addNamespace, stringToNamespace } from '../utils/filter';\nimport { httpMethods } from '../utils/operation';\n\nexport type ResourceMetadata = {\n operations: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n tags: Set<string>;\n }\n >;\n parameters: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n requestBodies: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n responses: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n schemas: Map<\n string,\n {\n dependencies: Set<string>;\n deprecated: boolean;\n }\n >;\n};\n\n/**\n * Builds a resource metadata map from a Graph, matching the old Graph interface\n * for compatibility with filtering code.\n */\nexport const buildResourceMetadata = (\n graph: Graph,\n logger: Logger,\n): {\n resourceMetadata: ResourceMetadata;\n} => {\n const eventBuildResourceMetadata = logger.timeEvent('build-resource-metadata');\n const resourceMetadata: ResourceMetadata = {\n operations: new Map(),\n parameters: new Map(),\n requestBodies: new Map(),\n responses: new Map(),\n schemas: new Map(),\n };\n\n const getDependencies = (pointer: string): Set<string> => {\n const dependencies = new Set<string>();\n const nodeDependencies = graph.transitiveDependencies.get(pointer);\n if (nodeDependencies?.size) {\n for (const dependency of nodeDependencies) {\n const path = jsonPointerToPath(dependency);\n const type = path[path.length - 2];\n const name = path[path.length - 1];\n if (type && name) {\n const namespace = stringToNamespace(type);\n if (namespace === 'unknown') {\n console.warn(`unsupported type: ${type}`);\n }\n dependencies.add(addNamespace(namespace, name));\n }\n }\n }\n return dependencies;\n };\n\n // Process each node to find top-level resources\n for (const [pointer, nodeInfo] of graph.nodes) {\n // const node = nodeInfo.node as Record<string, unknown>;\n const path = jsonPointerToPath(pointer);\n\n // OpenAPI 3.x\n if (path[0] === 'components') {\n if (path.length === 3) {\n if (path[1] === 'schemas') {\n // Schema: #/components/schemas/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.schemas.set(addNamespace('schema', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n } else if (path[1] === 'parameters') {\n // Parameter: #/components/parameters/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.parameters.set(addNamespace('parameter', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n } else if (path[1] === 'requestBodies') {\n // RequestBody: #/components/requestBodies/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.requestBodies.set(addNamespace('body', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n } else if (path[1] === 'responses') {\n // Response: #/components/responses/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.responses.set(addNamespace('response', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n }\n }\n continue;\n }\n\n if (path[0] === 'paths') {\n if (path.length === 3 && httpMethods.includes(path[2] as (typeof httpMethods)[number])) {\n // Operation: #/paths/{path}/{method}\n const method = path[path.length - 1]!;\n const operationPath = path.slice(1, -1).join('/');\n const operationKey = createOperationKey({\n method,\n path: operationPath,\n });\n resourceMetadata.operations.set(addNamespace('operation', operationKey), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n tags: nodeInfo.tags ?? new Set(),\n });\n }\n continue;\n }\n\n // OpenAPI 2.0\n if (path[0] === 'definitions') {\n if (path.length === 2) {\n // Schema: #/definitions/{name}\n const name = path[path.length - 1]!;\n resourceMetadata.schemas.set(addNamespace('schema', name), {\n dependencies: getDependencies(pointer),\n deprecated: nodeInfo.deprecated ?? false,\n });\n }\n continue;\n }\n }\n\n eventBuildResourceMetadata.timeEnd();\n return { resourceMetadata };\n};\n","export const deepClone = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));\n","export const childSchemaRelationships = [\n ['additionalProperties', 'single'],\n ['allOf', 'array'],\n ['anyOf', 'array'],\n ['contains', 'single'],\n ['dependentSchemas', 'objectMap'],\n ['else', 'single'],\n ['if', 'single'],\n ['items', 'singleOrArray'],\n ['oneOf', 'array'],\n ['patternProperties', 'objectMap'],\n ['properties', 'objectMap'],\n ['propertyNames', 'single'],\n ['then', 'single'],\n ['unevaluatedProperties', 'single'],\n] as const;\n","export const getSchemasObject = (spec: unknown): Record<string, unknown> | undefined => {\n if (hasComponentsSchemasObject(spec)) {\n return (spec as any).components.schemas;\n }\n if (hasDefinitionsObject(spec)) {\n return (spec as any).definitions;\n }\n return;\n};\n\n/**\n * Checks if the given spec has a valid OpenAPI 3.x components.schemas object.\n * Returns true if present, false otherwise.\n */\nexport const hasComponentsSchemasObject = (spec: unknown): boolean =>\n typeof spec === 'object' &&\n spec !== null &&\n 'components' in spec &&\n typeof (spec as any).components === 'object' &&\n (spec as any).components !== null &&\n 'schemas' in (spec as any).components &&\n typeof (spec as any).components.schemas === 'object' &&\n (spec as any).components.schemas !== null;\n\n/**\n * Checks if the given spec has a valid OpenAPI 2.0 definitions object.\n * Returns true if present, false otherwise.\n */\nexport const hasDefinitionsObject = (spec: unknown): boolean =>\n typeof spec === 'object' &&\n spec !== null &&\n 'definitions' in spec &&\n typeof (spec as any).definitions === 'object' &&\n (spec as any).definitions !== null;\n","type Obj = Record<string, unknown> | Set<string> | ReadonlyArray<string | undefined>;\n\nconst hasName = (obj: Obj, value: string): boolean => {\n if (obj instanceof Set) {\n return obj.has(value);\n }\n if (obj instanceof Array) {\n return obj.includes(value);\n }\n return value in obj;\n};\n\nexport const getUniqueComponentName = ({\n base,\n components,\n extraComponents,\n}: {\n base: string;\n /**\n * Input components.\n */\n components: Obj;\n /**\n * Temporary input components, waiting to be inserted for example.\n */\n extraComponents?: Obj;\n}): string => {\n let index = 2;\n let name = base;\n while (hasName(components, name) || (extraComponents && hasName(extraComponents, name))) {\n name = `${base}${index}`;\n index += 1;\n }\n return name;\n};\n\nexport const isPathRootSchema = (path: ReadonlyArray<string | number>) =>\n (path.length === 3 && path[0] === 'components' && path[1] === 'schemas') ||\n (path.length === 2 && path[0] === 'definitions');\n\nexport const specToSchemasPointerNamespace = (spec: unknown): string => {\n if (spec && typeof spec === 'object') {\n if ('swagger' in spec) {\n // #/definitions/SchemaName\n return '#/definitions/';\n }\n\n if ('openapi' in spec) {\n // #/components/schemas/SchemaName\n return '#/components/schemas/';\n }\n }\n\n return '';\n};\n","import type { Parser } from '../../../config/parser/types';\nimport { applyNaming } from '../../../utils/naming/naming';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport { deepClone } from '../utils/schema';\nimport { childSchemaRelationships } from '../utils/schemaChildRelationships';\nimport { getSchemasObject } from '../utils/transforms';\nimport { getUniqueComponentName, isPathRootSchema, specToSchemasPointerNamespace } from './utils';\n\ntype EnumsConfig = Parser['transforms']['enums'];\n\n/**\n * Generate a unique, structural signature for an enum schema for deduplication.\n * Only considers 'type' and sorted 'enum' values, ignoring other fields.\n *\n * @param schema - The schema object to analyze\n * @returns A string signature if the schema is an enum, otherwise undefined\n */\nconst getEnumSignature = (schema: unknown): string | undefined => {\n if (\n !schema ||\n typeof schema !== 'object' ||\n !('enum' in schema) ||\n !(schema.enum instanceof Array)\n ) {\n return;\n }\n // Use type + sorted enum values for signature\n const type = ('type' in schema ? schema.type : undefined) || '';\n const values = [...schema.enum].sort();\n return JSON.stringify({ type, values });\n};\n\ntype NodeInfo = {\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n};\n\n/**\n * Recursively walk all schemas in the OpenAPI spec, visiting every object/array\n * that could contain an enum. Calls the visitor with node info for each.\n *\n * @param key - The key of the current node\n * @param node - The current node\n * @param parent - The parent node\n * @param path - The path to the current node\n * @param visitor - Function to call for each visited node\n */\nconst walkSchemas = ({\n key,\n node,\n parent,\n path,\n visitor,\n}: NodeInfo & {\n visitor: (nodeInfo: NodeInfo) => void;\n}) => {\n if (!node || typeof node !== 'object' || node instanceof Array) return;\n\n const value = node as Record<string, unknown>;\n\n if (\n 'type' in value ||\n 'enum' in value ||\n childSchemaRelationships.some(([keyword]) => keyword in value)\n ) {\n visitor({ key, node, parent, path });\n }\n\n for (const [k, v] of Object.entries(value)) {\n if (typeof v === 'object' && v !== null) {\n if (v instanceof Array) {\n v.forEach((item, index) =>\n walkSchemas({\n key: index,\n node: item,\n parent: v,\n path: [...path, k, index],\n visitor,\n }),\n );\n } else {\n walkSchemas({\n key: k,\n node: v,\n parent: node,\n path: [...path, k],\n visitor,\n });\n }\n }\n }\n};\n\n/**\n * Inlines all root/top-level enums by replacing $refs to them with the actual enum schema,\n * and then removes the now-unreferenced root enums from the schemas object.\n *\n * @param spec - The OpenAPI spec object to transform\n */\nconst inlineMode = ({ spec }: { spec: unknown }) => {\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) {\n return;\n }\n\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n\n // Collect all root enums\n const rootEnums: Record<string, unknown> = {};\n for (const [name, schema] of Object.entries(schemasObj)) {\n const signature = getEnumSignature(schema);\n if (signature) {\n rootEnums[`${schemasPointerNamespace}${name}`] = schema;\n }\n }\n\n // Walk the spec and replace $refs to root enums with inline enum schemas\n const replaceEnumRefs = (node: unknown) => {\n if (node instanceof Array) {\n node.forEach(replaceEnumRefs);\n } else if (node && typeof node === 'object') {\n for (const [k, v] of Object.entries(node)) {\n if (k === '$ref' && typeof v === 'string' && v in rootEnums) {\n // Replace $ref with a deep clone of the enum schema\n Object.assign(node, deepClone(rootEnums[v]));\n delete (node as Record<string, unknown>)['$ref'];\n } else {\n replaceEnumRefs(v);\n }\n }\n }\n };\n replaceEnumRefs(spec);\n\n // Remove unreferenced root enums\n for (const pointer of Object.keys(rootEnums)) {\n const path = jsonPointerToPath(pointer);\n const name = path[path.length - 1]!;\n if (name) {\n delete schemasObj[name];\n }\n }\n};\n\n/**\n * Promotes all inline enums to reusable root components (if mode is 'root'),\n * deduplicates by signature, and replaces inline enums with $refs.\n *\n * Naming, casing, and deduplication are controlled by the enums transform config.\n * Existing root enums are reused if structurally identical.\n *\n * @param spec - The OpenAPI spec object to transform\n * @param config - The enums transform config\n */\nconst rootMode = ({ config, spec }: { config: EnumsConfig; spec: unknown }) => {\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) {\n return;\n }\n\n // Build a map of existing root enum signatures to their names for deduplication\n const rootEnumSignatures: Record<string, string> = {};\n for (const [name, schema] of Object.entries(schemasObj)) {\n const signature = getEnumSignature(schema);\n if (signature) {\n rootEnumSignatures[signature] = name;\n }\n }\n\n // Collect all inline enums (not at root schemas)\n const inlineEnums: Array<{\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n signature: string;\n }> = [];\n\n walkSchemas({\n key: null,\n node: spec,\n parent: null,\n path: [],\n visitor: (nodeInfo) => {\n if (!isPathRootSchema(nodeInfo.path)) {\n const signature = getEnumSignature(nodeInfo.node);\n if (signature) {\n inlineEnums.push({ ...nodeInfo, signature });\n }\n }\n },\n });\n\n // Deduplicate and assign unique names for promoted enums\n const signatureToName: Record<string, string | undefined> = {};\n const signatureToSchema: Record<string, unknown> = {};\n\n for (const { key, node, signature } of inlineEnums) {\n if (signature in signatureToName) {\n // Already handled\n continue;\n }\n\n // Use existing root enum if available\n if (signature in rootEnumSignatures) {\n signatureToName[signature] = rootEnumSignatures[signature];\n continue;\n }\n\n // Generate a unique name for the new root enum using config\n const base = applyNaming(\n typeof node === 'object' && node && 'title' in node && typeof node.title === 'string'\n ? node.title\n : String(key),\n config,\n );\n const name = getUniqueComponentName({\n base,\n components: schemasObj,\n extraComponents: Object.values(signatureToName),\n });\n signatureToName[signature] = name;\n signatureToSchema[signature] = node;\n }\n\n // Add new root enums to the schemas object\n for (const [signature, name] of Object.entries(signatureToName)) {\n // Only add if not already present\n const schema = signatureToSchema[signature];\n if (name && !(name in schemasObj) && schema && typeof schema === 'object') {\n schemasObj[name] = schema;\n }\n }\n\n // Replace inline enums with $ref to the new root enum\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n for (const { key, parent, signature } of inlineEnums) {\n const name = signatureToName[signature];\n if (name && key != null && parent && typeof parent === 'object') {\n (parent as Record<string, unknown>)[key] = {\n $ref: `${schemasPointerNamespace}${name}`,\n };\n }\n }\n};\n\n/**\n * Applies the enums transform according to the configured mode ('inline' or 'root').\n *\n * - In 'inline' mode, all root enums are inlined and removed.\n * - In 'root' mode, all inline enums are promoted to root components and deduplicated.\n *\n * @param config - The enums transform config\n * @param spec - The OpenAPI spec object to transform\n */\nexport const enumsTransform = ({ config, spec }: { config: EnumsConfig; spec: unknown }) => {\n if (config.mode === 'inline') {\n inlineMode({ spec });\n return;\n }\n\n if (config.mode === 'root') {\n rootMode({ config, spec });\n return;\n }\n};\n","import { childSchemaRelationships } from '../utils/schemaChildRelationships';\n\ntype NodeInfo = {\n key: string | number | null;\n node: unknown;\n parent: unknown;\n path: ReadonlyArray<string | number>;\n};\n\n/**\n * Recursively walk all schemas in the OpenAPI spec, visiting every object.\n * Calls the visitor with node info for each.\n *\n * @param key - The key of the current node\n * @param node - The current node\n * @param parent - The parent node\n * @param path - The path to the current node\n * @param visitor - Function to call for each visited node\n */\nconst walkSchemas = ({\n key,\n node,\n parent,\n path,\n visitor,\n}: NodeInfo & {\n visitor: (nodeInfo: NodeInfo) => void;\n}) => {\n if (!node || typeof node !== 'object' || node instanceof Array) return;\n\n const value = node as Record<string, unknown>;\n\n if ('type' in value || childSchemaRelationships.some(([keyword]) => keyword in value)) {\n visitor({ key, node, parent, path });\n }\n\n for (const [k, v] of Object.entries(value)) {\n if (typeof v === 'object' && v !== null) {\n if (v instanceof Array) {\n v.forEach((item, index) =>\n walkSchemas({\n key: index,\n node: item,\n parent: v,\n path: [...path, k, index],\n visitor,\n }),\n );\n } else {\n walkSchemas({\n key: k,\n node: v,\n parent: node,\n path: [...path, k],\n visitor,\n });\n }\n }\n }\n};\n\n/**\n * Applies the properties required by default transform\n *\n * @param spec - The OpenAPI spec object to transform\n */\nexport const propertiesRequiredByDefaultTransform = ({ spec }: { spec: unknown }) => {\n walkSchemas({\n key: null,\n node: spec,\n parent: null,\n path: [],\n visitor: (nodeInfo) => {\n if (\n nodeInfo.node &&\n typeof nodeInfo.node === 'object' &&\n 'type' in nodeInfo.node &&\n nodeInfo.node.type === 'object' &&\n 'properties' in nodeInfo.node &&\n nodeInfo.node.properties &&\n typeof nodeInfo.node.properties === 'object' &&\n !('required' in nodeInfo.node)\n ) {\n const propKeys = Object.keys(nodeInfo.node.properties as Record<string, unknown>);\n if (propKeys.length > 0) {\n (nodeInfo.node as Record<string, unknown>).required = propKeys;\n }\n }\n },\n });\n};\n","/**\n * Deep equality for JSON-compatible values (objects, arrays, primitives).\n * Used to determine whether read/write pruned variants actually differ.\n */\nconst deepEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n if (a === null || b === null) return a === b;\n const typeA = typeof a;\n const typeB = typeof b;\n if (typeA !== typeB) return false;\n if (typeA !== 'object') return false;\n\n // Arrays\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n\n // Plain objects\n const objA = a as Record<string, unknown>;\n const objB = b as Record<string, unknown>;\n const keysA = Object.keys(objA).sort();\n const keysB = Object.keys(objB).sort();\n if (keysA.length !== keysB.length) return false;\n for (let i = 0; i < keysA.length; i++) {\n if (keysA[i] !== keysB[i]) return false;\n }\n for (const key of keysA) {\n if (!deepEqual(objA[key], objB[key])) return false;\n }\n return true;\n};\n\nexport default deepEqual;\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Graph, NodeInfo } from '../../../graph';\nimport { normalizeJsonPointer, pathToJsonPointer } from '../../../utils/ref';\nimport { childSchemaRelationships } from './schemaChildRelationships';\n\n/**\n * Represents the possible access scopes for OpenAPI nodes.\n * - 'normal': Default scope for regular nodes.\n * - 'read': Node is read-only (e.g., readOnly: true).\n * - 'write': Node is write-only (e.g., writeOnly: true).\n */\nexport type Scope = 'normal' | 'read' | 'write';\n\n/**\n * Ensures every relevant child node (e.g., properties, items) in the graph has a `scopes` property.\n * If a node does not have its own scopes, it inherits from its parent if available.\n *\n * @param nodes - Map of JSON Pointer to NodeInfo.\n */\nexport const annotateChildScopes = (nodes: Graph['nodes']): void => {\n for (const [, nodeInfo] of nodes) {\n if (nodeInfo.scopes) continue;\n\n if (nodeInfo.parentPointer) {\n const parentInfo = nodes.get(nodeInfo.parentPointer);\n if (parentInfo?.scopes) {\n nodeInfo.scopes = new Set(parentInfo.scopes);\n }\n }\n }\n};\n\ninterface Cache {\n parentToChildren: Map<string, Array<string>>;\n subtreeDependencies: Map<string, Set<string>>;\n transitiveDependencies: Map<string, Set<string>>;\n}\n\ntype PointerDependenciesResult = {\n subtreeDependencies: Set<string>;\n transitiveDependencies: Set<string>;\n};\n\n/**\n * Recursively collects all $ref dependencies in the subtree rooted at `pointer`.\n */\nconst collectPointerDependencies = ({\n cache,\n graph,\n pointer,\n visited,\n}: {\n cache: Cache;\n graph: Graph;\n pointer: string;\n visited: Set<string>;\n}): PointerDependenciesResult => {\n const cached = cache.transitiveDependencies.get(pointer);\n if (cached) {\n return {\n subtreeDependencies: cache.subtreeDependencies.get(pointer)!,\n transitiveDependencies: cached,\n };\n }\n\n if (visited.has(pointer)) {\n return {\n subtreeDependencies: new Set(),\n transitiveDependencies: new Set(),\n };\n }\n visited.add(pointer);\n\n const nodeInfo = graph.nodes.get(pointer);\n if (!nodeInfo) {\n return {\n subtreeDependencies: new Set(),\n transitiveDependencies: new Set(),\n };\n }\n\n const transitiveDependencies = new Set<string>();\n const subtreeDependencies = new Set<string>();\n\n // Add direct $ref dependencies for this node\n // (from the dependencies map, or by checking nodeInfo.node directly)\n // We'll use the dependencies map for consistency:\n const nodeDependencies = graph.nodeDependencies.get(pointer);\n if (nodeDependencies) {\n for (const depPointer of nodeDependencies) {\n transitiveDependencies.add(depPointer);\n subtreeDependencies.add(depPointer);\n // Recursively collect dependencies of the referenced node\n const depResult = collectPointerDependencies({\n cache,\n graph,\n pointer: depPointer,\n visited,\n });\n for (const dependency of depResult.transitiveDependencies) {\n transitiveDependencies.add(dependency);\n }\n }\n }\n\n const children = cache.parentToChildren.get(pointer) ?? [];\n for (const childPointer of children) {\n let childResult: Partial<PointerDependenciesResult> = {\n subtreeDependencies: cache.subtreeDependencies.get(childPointer),\n transitiveDependencies: cache.transitiveDependencies.get(childPointer),\n };\n if (!childResult.subtreeDependencies || !childResult.transitiveDependencies) {\n childResult = collectPointerDependencies({\n cache,\n graph,\n pointer: childPointer,\n visited,\n });\n cache.transitiveDependencies.set(childPointer, childResult.transitiveDependencies!);\n cache.subtreeDependencies.set(childPointer, childResult.subtreeDependencies!);\n }\n for (const dependency of childResult.transitiveDependencies!) {\n transitiveDependencies.add(dependency);\n }\n for (const dependency of childResult.subtreeDependencies!) {\n subtreeDependencies.add(dependency);\n }\n }\n\n cache.transitiveDependencies.set(pointer, transitiveDependencies);\n cache.subtreeDependencies.set(pointer, subtreeDependencies);\n return {\n subtreeDependencies,\n transitiveDependencies,\n };\n};\n\n/**\n * Propagates scopes through the graph using a worklist algorithm.\n * Each node's scopes will be updated to include any scopes inherited via $ref dependencies, combinator/child relationships, and parent relationships.\n * Handles cycles and deep chains efficiently.\n *\n * Whenever a node's scopes change, all dependents are notified:\n * - Its parent (if any)\n * - All nodes that reference it via $ref (reverse dependencies)\n * - Combinator parents (allOf/anyOf/oneOf) if applicable\n *\n * @param graph - The Graph structure containing nodes, dependencies, and reverseNodeDependencies.\n */\nexport const propagateScopes = (graph: Graph): void => {\n const worklist: Set<string> = new Set(\n Array.from(graph.nodes.entries())\n .filter(([, nodeInfo]) => nodeInfo.scopes && nodeInfo.scopes.size > 0)\n .map(([pointer]) => pointer),\n );\n\n /**\n * Notifies all dependents of a node that its scopes may have changed.\n * Dependents include:\n * - The parent node (if any)\n * - All nodes that reference this node via $ref (reverse dependencies)\n * - Combinator parents (allOf/anyOf/oneOf) if this node is a combinator child\n *\n * @param pointer - The JSON pointer of the node whose dependents to notify\n * @param nodeInfo - The NodeInfo of the node\n * @param childPointer - (Optional) The pointer of the child, used to detect combinator parents\n */\n const notifyAllDependents = (pointer: string, nodeInfo: NodeInfo, childPointer?: string) => {\n if (nodeInfo.parentPointer) {\n worklist.add(nodeInfo.parentPointer);\n }\n const reverseNodeDependencies = graph.reverseNodeDependencies.get(pointer);\n if (reverseNodeDependencies) {\n for (const dependentPointer of reverseNodeDependencies) {\n worklist.add(dependentPointer);\n }\n }\n if (childPointer) {\n // If this is a combinator child, notify the combinator parent\n const combinatorChildMatch = childPointer.match(/(.*)\\/(allOf|anyOf|oneOf)\\/\\d+$/);\n if (combinatorChildMatch) {\n const combinatorParentPointer = combinatorChildMatch[1];\n if (combinatorParentPointer) {\n worklist.add(combinatorParentPointer);\n }\n }\n }\n };\n\n /**\n * Propagates scopes from a child node to its parent node.\n * If the parent's scopes change, notifies all dependents.\n *\n * @param pointer - The parent node's pointer\n * @param nodeInfo - The parent node's NodeInfo\n * @param childPointer - The child node's pointer\n */\n const propagateChildScopes = (\n pointer: string,\n nodeInfo: NodeInfo,\n childPointer: string,\n ): void => {\n if (!nodeInfo?.scopes) return;\n const childInfo = graph.nodes.get(childPointer);\n if (!childInfo?.scopes) return;\n const changed = propagateScopesToNode(childInfo, nodeInfo);\n if (changed) {\n notifyAllDependents(pointer, nodeInfo, childPointer);\n }\n };\n\n while (worklist.size > 0) {\n const pointer = worklist.values().next().value!;\n worklist.delete(pointer);\n\n const nodeInfo = graph.nodes.get(pointer);\n if (!nodeInfo) continue;\n\n if (!nodeInfo.scopes) {\n nodeInfo.scopes = new Set();\n }\n\n const node = nodeInfo.node as Record<string, unknown>;\n\n // Propagate scopes from all child schema relationships (combinators, properties, etc.)\n for (const [keyword, type] of childSchemaRelationships) {\n if (!node || typeof node !== 'object' || !(keyword in node)) continue;\n const value = node[keyword];\n if (type === 'array' && value instanceof Array) {\n for (let index = 0; index < value.length; index++) {\n const childPointer = `${pointer}/${keyword}/${index}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n } else if (\n type === 'objectMap' &&\n typeof value === 'object' &&\n value !== null &&\n !(value instanceof Array)\n ) {\n for (const key of Object.keys(value)) {\n const childPointer = `${pointer}/${keyword}/${key}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n } else if (type === 'single' && typeof value === 'object' && value !== null) {\n const childPointer = `${pointer}/${keyword}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n } else if (type === 'singleOrArray') {\n if (value instanceof Array) {\n for (let index = 0; index < value.length; index++) {\n const childPointer = `${pointer}/${keyword}/${index}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n } else if (typeof value === 'object' && value !== null) {\n const childPointer = `${pointer}/${keyword}`;\n propagateChildScopes(pointer, nodeInfo, childPointer);\n }\n }\n }\n\n // Propagate scopes from $ref dependencies\n const nodeDependencies = graph.nodeDependencies.get(pointer);\n if (nodeDependencies) {\n for (const depPointer of nodeDependencies) {\n const depNode = graph.nodes.get(depPointer);\n if (depNode?.scopes) {\n const changed = propagateScopesToNode(depNode, nodeInfo);\n if (changed) {\n notifyAllDependents(pointer, nodeInfo);\n }\n }\n }\n }\n\n // Propagate scopes up the parent chain\n if (nodeInfo.parentPointer) {\n const parentInfo = graph.nodes.get(nodeInfo.parentPointer);\n if (parentInfo) {\n const changed = propagateScopesToNode(nodeInfo, parentInfo);\n if (changed) {\n notifyAllDependents(nodeInfo.parentPointer, parentInfo);\n }\n }\n }\n }\n};\n\n/**\n * Propagates scopes from one node to another.\n * Adds any scopes from fromNodeInfo to toNodeInfo that are not already present.\n * Returns true if any scopes were added, false otherwise.\n *\n * @param fromNodeInfo - The node to propagate scopes from\n * @param toNodeInfo - The node to propagate scopes to\n * @returns boolean - Whether any scopes were added\n */\nconst propagateScopesToNode = (fromNodeInfo: NodeInfo, toNodeInfo: NodeInfo): boolean => {\n if (!fromNodeInfo.scopes) {\n return false;\n }\n\n if (!toNodeInfo.scopes) {\n toNodeInfo.scopes = new Set();\n }\n\n let changed = false;\n\n for (const scope of fromNodeInfo.scopes) {\n if (!toNodeInfo.scopes.has(scope)) {\n toNodeInfo.scopes.add(scope);\n changed = true;\n }\n }\n\n return changed;\n};\n\n/**\n * Seeds each node in the graph with its local access scope(s) based on its own properties.\n * - 'read' if readOnly: true\n * - 'write' if writeOnly: true\n * - 'normal' if node is an object property\n *\n * Only non-array objects are considered for scope seeding.\n *\n * @param nodes - Map of JSON Pointer to NodeInfo.\n */\nexport const seedLocalScopes = (nodes: Graph['nodes']): void => {\n for (const [pointer, nodeInfo] of nodes) {\n const { node } = nodeInfo;\n\n if (typeof node !== 'object' || node === null || node instanceof Array) {\n continue;\n }\n\n if ('readOnly' in node && node.readOnly === true) {\n nodeInfo.scopes = new Set(['read']);\n } else if ('writeOnly' in node && node.writeOnly === true) {\n nodeInfo.scopes = new Set(['write']);\n } else if (pointer.match(/\\/properties\\/[^/]+$/)) {\n nodeInfo.scopes = new Set(['normal']);\n }\n }\n};\n\n/**\n * Builds a graph of all nodes in an OpenAPI spec, indexed by normalized JSON Pointer,\n * and tracks all $ref dependencies and reverse dependencies between nodes.\n *\n * - All keys in the returned maps are normalized JSON Pointers (RFC 6901, always starting with '#').\n * - The `nodes` map allows fast lookup of any node and its parent/key context.\n * - The `dependencies` map records, for each node, the set of normalized pointers it references via $ref.\n * - The `reverseNodeDependencies` map records, for each node, the set of nodes that reference it via $ref.\n * - After construction, all nodes will have their local and propagated scopes annotated.\n *\n * @param root The root object (e.g., the OpenAPI spec)\n * @returns An object with:\n * - nodes: Map from normalized JSON Pointer string to NodeInfo\n * - dependencies: Map from normalized JSON Pointer string to Set of referenced normalized JSON Pointers\n * - reverseNodeDependencies: Map from normalized JSON Pointer string to Set of referencing normalized JSON Pointers\n */\nexport function buildGraph(\n root: unknown,\n logger: Logger,\n): {\n graph: Graph;\n} {\n const eventBuildGraph = logger.timeEvent('build-graph');\n const graph: Graph = {\n nodeDependencies: new Map(),\n nodes: new Map(),\n reverseNodeDependencies: new Map(),\n subtreeDependencies: new Map(),\n transitiveDependencies: new Map(),\n };\n\n const walk = ({\n key,\n node,\n parentPointer,\n path,\n }: NodeInfo & {\n path: ReadonlyArray<string | number>;\n }) => {\n if (typeof node !== 'object' || node === null) {\n return;\n }\n\n const pointer = pathToJsonPointer(path);\n\n let deprecated: boolean | undefined;\n let tags: Set<string> | undefined;\n\n if (typeof node === 'object' && node !== null) {\n // Check for deprecated property\n if ('deprecated' in node && typeof node.deprecated === 'boolean') {\n deprecated = Boolean(node.deprecated);\n }\n // If this node has a $ref, record the dependency\n if ('$ref' in node && typeof node.$ref === 'string') {\n const refPointer = normalizeJsonPointer(node.$ref);\n if (!graph.nodeDependencies.has(pointer)) {\n graph.nodeDependencies.set(pointer, new Set());\n }\n graph.nodeDependencies.get(pointer)!.add(refPointer);\n }\n // Check for tags property (should be an array of strings)\n if ('tags' in node && node.tags instanceof Array) {\n tags = new Set(node.tags.filter((tag) => typeof tag === 'string'));\n }\n }\n\n graph.nodes.set(pointer, { deprecated, key, node, parentPointer, tags });\n\n if (node instanceof Array) {\n node.forEach((item, index) =>\n walk({\n key: index,\n node: item,\n parentPointer: pointer,\n path: [...path, index],\n }),\n );\n } else {\n for (const [childKey, value] of Object.entries(node)) {\n walk({\n key: childKey,\n node: value,\n parentPointer: pointer,\n path: [...path, childKey],\n });\n }\n }\n };\n\n walk({\n key: null,\n node: root,\n parentPointer: null,\n path: [],\n });\n\n const cache: Cache = {\n parentToChildren: new Map(),\n subtreeDependencies: new Map(),\n transitiveDependencies: new Map(),\n };\n\n for (const [pointer, nodeInfo] of graph.nodes) {\n const parent = nodeInfo.parentPointer;\n if (!parent) continue;\n if (!cache.parentToChildren.has(parent)) {\n cache.parentToChildren.set(parent, []);\n }\n cache.parentToChildren.get(parent)!.push(pointer);\n }\n\n for (const [pointerFrom, pointers] of graph.nodeDependencies) {\n for (const pointerTo of pointers) {\n if (!graph.reverseNodeDependencies.has(pointerTo)) {\n graph.reverseNodeDependencies.set(pointerTo, new Set());\n }\n graph.reverseNodeDependencies.get(pointerTo)!.add(pointerFrom);\n }\n }\n\n seedLocalScopes(graph.nodes);\n propagateScopes(graph);\n annotateChildScopes(graph.nodes);\n\n for (const pointer of graph.nodes.keys()) {\n const result = collectPointerDependencies({\n cache,\n graph,\n pointer,\n visited: new Set(),\n });\n graph.transitiveDependencies.set(pointer, result.transitiveDependencies);\n graph.subtreeDependencies.set(pointer, result.subtreeDependencies);\n }\n\n eventBuildGraph.timeEnd();\n\n // functions creating data for debug scripts located in `dev/`\n // const { maxChildren, maxDepth, totalNodes } = debugTools.graph.analyzeStructure(graph);\n // const nodesForViz = debugTools.graph.exportForVisualization(graph);\n // fs.writeFileSync('dev/graph.json', JSON.stringify(nodesForViz, null, 2));\n\n return { graph };\n}\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport type { Parser } from '../../../config/parser/types';\nimport type { Graph } from '../../../graph';\nimport { applyNaming } from '../../../utils/naming/naming';\nimport { jsonPointerToPath } from '../../../utils/ref';\nimport deepEqual from '../utils/deepEqual';\nimport { buildGraph, type Scope } from '../utils/graph';\nimport { deepClone } from '../utils/schema';\nimport { childSchemaRelationships } from '../utils/schemaChildRelationships';\nimport {\n getSchemasObject,\n hasComponentsSchemasObject,\n hasDefinitionsObject,\n} from '../utils/transforms';\nimport { getUniqueComponentName, isPathRootSchema, specToSchemasPointerNamespace } from './utils';\n\ntype OriginalSchemas = Record<string, unknown>;\n\ntype SplitMapping = Record<\n string,\n {\n read?: string;\n write?: string;\n }\n>;\n\ntype SplitSchemas = {\n /** Key is the original schema pointer. */\n mapping: SplitMapping;\n /** splitPointer -> originalPointer */\n reverseMapping: Record<string, string>;\n /** name -> schema object */\n schemas: Record<string, unknown>;\n};\n\ntype ReadWriteConfig = Parser['transforms']['readWrite'];\n\nconst schemaKeys = new Set([\n 'additionalProperties',\n 'allOf',\n 'anyOf',\n 'items',\n 'not',\n 'oneOf',\n 'patternProperties',\n 'properties',\n 'schema',\n 'unevaluatedProperties',\n]);\n\nconst getComponentContext = (path: ReadonlyArray<string | number>): Scope | undefined => {\n // OpenAPI 3.x: #/components/{type}/{name}\n if (path.length === 3 && path[0] === 'components') {\n const type = path[1];\n if (type === 'parameters') return 'write';\n if (type === 'requestBodies') return 'write';\n if (type === 'responses') return 'read';\n if (type === 'headers') return 'read';\n }\n // OpenAPI 2.x: #/parameters/{name}, #/responses/{name}\n if (path.length === 2) {\n const type = path[0];\n if (type === 'parameters') return 'write';\n if (type === 'responses') return 'read';\n }\n return;\n};\n\n/**\n * Capture the original schema objects by pointer before splitting.\n * This is used to safely remove only the true originals after splitting,\n * even if names are swapped or overwritten by split variants.\n */\nconst captureOriginalSchemas = (spec: unknown, logger: Logger): OriginalSchemas => {\n const event = logger.timeEvent('capture-original-schemas');\n const originals: OriginalSchemas = {};\n if (hasComponentsSchemasObject(spec)) {\n for (const [name, obj] of Object.entries((spec as any).components.schemas)) {\n originals[`#/components/schemas/${name}`] = obj;\n }\n } else if (hasDefinitionsObject(spec)) {\n for (const [name, obj] of Object.entries((spec as any).definitions)) {\n originals[`#/definitions/${name}`] = obj;\n }\n }\n event.timeEnd();\n return originals;\n};\n\n/**\n * Inserts split schemas into the spec at the correct location (OpenAPI 3.x or 2.0).\n * This function is robust to spec version and will assign all split schemas\n * to either components.schemas (OAS3) or definitions (OAS2).\n *\n * @param spec - The OpenAPI spec object\n * @param split - The split schemas (from splitSchemas)\n */\nconst insertSplitSchemasIntoSpec = ({\n logger,\n spec,\n split,\n}: {\n logger: Logger;\n spec: unknown;\n split: Pick<SplitSchemas, 'schemas'>;\n}) => {\n const event = logger.timeEvent('insert-split-schemas-into-spec');\n if (hasComponentsSchemasObject(spec)) {\n Object.assign((spec as any).components.schemas, split.schemas);\n } else if (hasDefinitionsObject(spec)) {\n Object.assign((spec as any).definitions, split.schemas);\n }\n event.timeEnd();\n};\n\n/**\n * Prunes a schema by removing all child schemas (in any structural keyword)\n * that are marked with the given scope (readOnly/writeOnly), or that are $ref to a schema\n * that is exclusively the excluded scope (according to the graph).\n *\n * Uses childSchemaRelationships for parity with graph traversal.\n * Returns true if the schema itself should be removed from its parent.\n *\n * @param graph - The Graph containing all nodes and their scopes\n * @param schema - The schema object to prune\n * @param scope - The scope to exclude ('readOnly' or 'writeOnly')\n * @returns boolean - Whether the schema should be removed from its parent\n */\nconst pruneSchemaByScope = (\n graph: Graph,\n schema: unknown,\n scope: 'readOnly' | 'writeOnly',\n): boolean => {\n if (schema && typeof schema === 'object') {\n // Handle $ref schemas\n if ('$ref' in schema && typeof schema.$ref === 'string') {\n const nodeInfo = graph.nodes.get(schema.$ref);\n if (nodeInfo?.scopes) {\n // Only remove $ref if the referenced schema is *exclusively* the excluded scope.\n // This ensures 'normal' or multi-scope schemas are always kept.\n if (\n (scope === 'writeOnly' && nodeInfo.scopes.size === 1 && nodeInfo.scopes.has('write')) ||\n (scope === 'readOnly' && nodeInfo.scopes.size === 1 && nodeInfo.scopes.has('read'))\n ) {\n delete (schema as Record<string, unknown>)['$ref'];\n // If the schema is now empty, remove it\n if (!childSchemaRelationships.some(([keyword]) => keyword in schema)) {\n return true;\n }\n }\n }\n }\n // Recursively prune all child schemas according to childSchemaRelationships\n for (const [keyword, type] of childSchemaRelationships) {\n if (!(keyword in schema)) {\n continue;\n }\n const value = (schema as Record<string, unknown>)[keyword];\n if (type === 'array' && value instanceof Array) {\n for (let index = value.length - 1; index >= 0; index--) {\n const item = value[index];\n if (\n item &&\n typeof item === 'object' &&\n (item as Record<string, unknown>)[scope] === true\n ) {\n value.splice(index, 1);\n } else {\n const shouldRemove = pruneSchemaByScope(graph, item, scope);\n if (shouldRemove) value.splice(index, 1);\n }\n }\n if (!value.length) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n } else if (\n type === 'objectMap' &&\n typeof value === 'object' &&\n value !== null &&\n !(value instanceof Array)\n ) {\n const objMap = value as Record<string, unknown>;\n // Track removed properties for object schemas to update required array\n const removedProperties = new Set<string>();\n\n for (const key of Object.keys(objMap)) {\n const prop = objMap[key];\n if (\n prop &&\n typeof prop === 'object' &&\n (prop as Record<string, unknown>)[scope] === true\n ) {\n delete objMap[key];\n // Track removed properties for object schemas\n if (keyword === 'properties') {\n removedProperties.add(key);\n }\n } else {\n const shouldRemove = pruneSchemaByScope(graph, prop, scope);\n if (shouldRemove) {\n delete objMap[key];\n // Track removed properties for object schemas\n if (keyword === 'properties') {\n removedProperties.add(key);\n }\n }\n }\n }\n\n // Update required array if properties were removed\n if (\n removedProperties.size > 0 &&\n keyword === 'properties' &&\n 'required' in schema &&\n Array.isArray((schema as Record<string, unknown>).required)\n ) {\n const required = (schema as Record<string, unknown>).required as string[];\n const filteredRequired = required.filter((prop) => !removedProperties.has(prop));\n\n if (!filteredRequired.length) {\n delete (schema as Record<string, unknown>).required;\n } else {\n (schema as Record<string, unknown>).required = filteredRequired;\n }\n }\n\n if (!Object.keys(objMap).length) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n } else if (type === 'single' && typeof value === 'object' && value !== null) {\n if ((value as Record<string, unknown>)[scope] === true) {\n delete (schema as Record<string, unknown>)[keyword];\n } else {\n const shouldRemove = pruneSchemaByScope(graph, value, scope);\n if (shouldRemove) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n }\n } else if (type === 'singleOrArray') {\n if (value instanceof Array) {\n for (let index = value.length - 1; index >= 0; index--) {\n const item = value[index];\n if (\n item &&\n typeof item === 'object' &&\n (item as Record<string, unknown>)[scope] === true\n ) {\n value.splice(index, 1);\n } else {\n const shouldRemove = pruneSchemaByScope(graph, item, scope);\n if (shouldRemove) value.splice(index, 1);\n }\n }\n if (!value.length) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n } else if (typeof value === 'object' && value !== null) {\n if ((value as Record<string, unknown>)[scope] === true) {\n delete (schema as Record<string, unknown>)[keyword];\n } else {\n const shouldRemove = pruneSchemaByScope(graph, value, scope);\n if (shouldRemove) {\n delete (schema as Record<string, unknown>)[keyword];\n }\n }\n }\n }\n }\n // After all removals, if this is type: object and has no structural fields, remove it\n if (\n (schema as Record<string, unknown>).type === 'object' &&\n !childSchemaRelationships.some(([keyword]) => keyword in schema)\n ) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Remove only the true original schemas that were split, by object identity.\n * This is robust to swaps, overwrites, and name collisions.\n *\n * @param originalSchemas - Map of original pointers to their schema objects (captured before splitting)\n * @param spec - The OpenAPI spec object\n * @param split - The split mapping (from splitSchemas)\n */\nconst removeOriginalSplitSchemas = ({\n logger,\n originalSchemas,\n spec,\n split,\n}: {\n logger: Logger;\n originalSchemas: OriginalSchemas;\n spec: unknown;\n split: Pick<SplitSchemas, 'mapping'>;\n}) => {\n const event = logger.timeEvent('remove-original-split-schemas');\n const schemasObj = getSchemasObject(spec);\n\n for (const originalPointer of Object.keys(split.mapping)) {\n const path = jsonPointerToPath(originalPointer);\n const name = path[path.length - 1]!;\n if (\n typeof name === 'string' &&\n schemasObj &&\n Object.prototype.hasOwnProperty.call(schemasObj, name) &&\n schemasObj[name] === originalSchemas[originalPointer]\n ) {\n delete schemasObj[name];\n }\n }\n event.timeEnd();\n};\n\n/**\n * Create writable variants of parent schemas that have discriminators\n * and are referenced by split schemas.\n */\nfunction splitDiscriminatorSchemas({\n config,\n existingNames,\n schemasPointerNamespace,\n spec,\n split,\n}: {\n config: ReadWriteConfig;\n existingNames: Set<string>;\n schemasPointerNamespace: string;\n spec: unknown;\n split: SplitSchemas;\n}) {\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) return;\n\n const parentSchemasToSplit = new Map<string, Set<Scope>>();\n\n // First pass: identify parent schemas that need writable variants\n for (const [name, schema] of Object.entries(split.schemas)) {\n const pointer = `${schemasPointerNamespace}${name}`;\n const originalPointer = split.reverseMapping[pointer];\n\n if (originalPointer) {\n const mapping = split.mapping[originalPointer];\n if (mapping) {\n const contextVariant: Scope | null =\n mapping.read === pointer ? 'read' : mapping.write === pointer ? 'write' : null;\n\n // Check allOf for $refs to schemas with discriminators\n if (\n contextVariant &&\n schema &&\n typeof schema === 'object' &&\n 'allOf' in schema &&\n schema.allOf instanceof Array\n ) {\n for (const comp of schema.allOf) {\n if (\n comp &&\n typeof comp === 'object' &&\n '$ref' in comp &&\n typeof comp.$ref === 'string'\n ) {\n const refPath = jsonPointerToPath(comp.$ref);\n const schemaName = refPath[refPath.length - 1];\n\n if (typeof schemaName === 'string' && schemaName in schemasObj) {\n const resolvedSchema = schemasObj[schemaName];\n\n // Check if this schema has a discriminator with mapping\n if (\n resolvedSchema &&\n typeof resolvedSchema === 'object' &&\n 'discriminator' in resolvedSchema &&\n resolvedSchema.discriminator &&\n typeof resolvedSchema.discriminator === 'object' &&\n 'mapping' in resolvedSchema.discriminator &&\n resolvedSchema.discriminator.mapping &&\n typeof resolvedSchema.discriminator.mapping === 'object'\n ) {\n // This parent schema needs a variant for this context\n if (!parentSchemasToSplit.has(comp.$ref)) {\n parentSchemasToSplit.set(comp.$ref, new Set());\n }\n parentSchemasToSplit.get(comp.$ref)!.add(contextVariant);\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Second pass: create writable variants of parent schemas and update their discriminator mappings\n const parentSchemaVariants = new Map<string, SplitMapping[keyof SplitMapping]>();\n\n for (const [parentRef, contexts] of parentSchemasToSplit) {\n const refPath = jsonPointerToPath(parentRef);\n const parentName = refPath[refPath.length - 1];\n\n if (typeof parentName !== 'string' || !(parentName in schemasObj)) continue;\n\n const parentSchema = schemasObj[parentName];\n if (!parentSchema || typeof parentSchema !== 'object') continue;\n\n const variants: SplitMapping[keyof SplitMapping] = {};\n\n // Create variants for each context\n for (const context of contexts) {\n const variantSchema = deepClone(parentSchema);\n\n // Update discriminator mapping in the variant\n if (\n 'discriminator' in variantSchema &&\n variantSchema.discriminator &&\n typeof variantSchema.discriminator === 'object' &&\n 'mapping' in variantSchema.discriminator &&\n variantSchema.discriminator.mapping &&\n typeof variantSchema.discriminator.mapping === 'object'\n ) {\n const mapping = variantSchema.discriminator.mapping;\n const updatedMapping: Record<string, string> = {};\n\n for (const [discriminatorValue, originalRef] of Object.entries(mapping)) {\n const map = split.mapping[originalRef];\n if (map) {\n if (context === 'read' && map.read) {\n updatedMapping[discriminatorValue] = map.read;\n } else if (context === 'write' && map.write) {\n updatedMapping[discriminatorValue] = map.write;\n } else {\n updatedMapping[discriminatorValue] = originalRef;\n }\n } else {\n updatedMapping[discriminatorValue] = originalRef;\n }\n }\n\n variantSchema.discriminator.mapping = updatedMapping;\n }\n\n // Add the variant to split.schemas with an appropriate name\n if (context === 'write') {\n const writeBase = applyNaming(parentName, config.requests);\n const writeName = getUniqueComponentName({\n base: writeBase,\n components: existingNames,\n });\n existingNames.add(writeName);\n split.schemas[writeName] = variantSchema;\n variants.write = `${schemasPointerNamespace}${writeName}`;\n }\n // We could create read variants too, but typically they're not needed\n // since the original schema serves as the read variant\n }\n\n parentSchemaVariants.set(parentRef, variants);\n }\n\n // Third pass: update $refs in split schemas to point to the parent variants\n for (const [name, schema] of Object.entries(split.schemas)) {\n const pointer = `${schemasPointerNamespace}${name}`;\n const originalPointer = split.reverseMapping[pointer];\n if (!originalPointer) continue;\n\n const mapping = split.mapping[originalPointer];\n if (!mapping) continue;\n\n const contextVariant: Scope | null =\n mapping.read === pointer ? 'read' : mapping.write === pointer ? 'write' : null;\n\n if (contextVariant && schema && typeof schema === 'object') {\n // Update $refs in allOf\n if ('allOf' in schema && schema.allOf instanceof Array) {\n for (let i = 0; i < schema.allOf.length; i++) {\n const comp = schema.allOf[i];\n\n if (comp && typeof comp === 'object' && '$ref' in comp && typeof comp.$ref === 'string') {\n const variants = parentSchemaVariants.get(comp.$ref);\n\n if (variants) {\n if (contextVariant === 'write' && variants.write) {\n comp.$ref = variants.write;\n } else if (contextVariant === 'read' && variants.read) {\n comp.$ref = variants.read;\n }\n }\n }\n }\n }\n }\n }\n}\n\n/**\n * Splits schemas with both 'read' and 'write' scopes into read/write variants.\n * Returns the new schemas and a mapping from original pointer to new variant pointers.\n *\n * @param config - The readWrite transform config\n * @param graph - The Graph containing all nodes and their scopes\n * @param spec - The OpenAPI spec object\n * @returns SplitSchemas - The split schemas and pointer mappings\n */\nexport const splitSchemas = ({\n config,\n graph,\n logger,\n spec,\n}: {\n config: ReadWriteConfig;\n graph: Graph;\n logger: Logger;\n spec: unknown;\n}): SplitSchemas => {\n const event = logger.timeEvent('split-schemas');\n const existingNames = new Set<string>();\n const split: SplitSchemas = {\n mapping: {},\n reverseMapping: {},\n schemas: {},\n };\n\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n const schemasNamespaceSegments = schemasPointerNamespace.split('/').length - 1;\n\n /**\n * Extracts the schema name from pointer, but only if it's a top-level schema\n * pointer. Returns an empty string if it's a nested pointer.\n * @param pointer\n * @returns Schema's base name.\n */\n const pointerToSchema = (pointer: string): string => {\n if (pointer.startsWith(schemasPointerNamespace)) {\n const path = jsonPointerToPath(pointer);\n if (path.length === schemasNamespaceSegments) {\n return path[schemasNamespaceSegments - 1] || '';\n }\n }\n return '';\n };\n\n // Collect all existing schema names\n for (const pointer of graph.nodes.keys()) {\n const name = pointerToSchema(pointer);\n if (name) existingNames.add(name);\n }\n\n for (const [pointer, nodeInfo] of graph.nodes) {\n const name = pointerToSchema(pointer);\n // Only split top-level schemas, with either read-only or write-only scopes (or both).\n if (\n !name ||\n !(nodeInfo.scopes?.has('read') || nodeInfo.scopes?.has('write')) ||\n !nodeInfo.scopes?.has('normal')\n ) {\n continue;\n }\n\n // read variant\n const readSchema = deepClone<unknown>(nodeInfo.node);\n pruneSchemaByScope(graph, readSchema, 'writeOnly');\n const readBase = applyNaming(name, config.responses);\n const readName =\n readBase === name\n ? readBase\n : getUniqueComponentName({\n base: readBase,\n components: existingNames,\n });\n existingNames.add(readName);\n split.schemas[readName] = readSchema;\n const readPointer = `${schemasPointerNamespace}${readName}`;\n\n // write variant\n const writeSchema = deepClone<unknown>(nodeInfo.node);\n pruneSchemaByScope(graph, writeSchema, 'readOnly');\n\n // Check if this schema (or any of its descendants) references any schema that\n // will need read/write variants. This is determined by checking transitive\n // dependencies for schemas with both 'normal' and ('read' or 'write') scopes.\n const transitiveDeps = graph.transitiveDependencies.get(pointer) || new Set();\n const referencesReadWriteSchemas = Array.from(transitiveDeps).some((depPointer) => {\n const depNodeInfo = graph.nodes.get(depPointer);\n return (\n depNodeInfo?.scopes?.has('normal') &&\n (depNodeInfo.scopes.has('read') || depNodeInfo.scopes.has('write'))\n );\n });\n\n // If pruning did not change anything (both variants equal and equal to original),\n // and the schema doesn't reference any schemas that will have read/write variants,\n // skip splitting and keep the original single schema.\n if (\n !referencesReadWriteSchemas &&\n deepEqual(readSchema, writeSchema) &&\n deepEqual(readSchema, nodeInfo.node)\n ) {\n continue;\n }\n const writeBase = applyNaming(name, config.requests);\n const writeName =\n writeBase === name && writeBase !== readName\n ? writeBase\n : getUniqueComponentName({\n base: writeBase,\n components: existingNames,\n });\n existingNames.add(writeName);\n split.schemas[writeName] = writeSchema;\n const writePointer = `${schemasPointerNamespace}${writeName}`;\n\n split.mapping[pointer] = {\n read: readPointer,\n write: writePointer,\n };\n split.reverseMapping[readPointer] = pointer;\n split.reverseMapping[writePointer] = pointer;\n }\n\n splitDiscriminatorSchemas({\n config,\n existingNames,\n schemasPointerNamespace,\n spec,\n split,\n });\n\n event.timeEnd();\n return split;\n};\n\ntype WalkArgs = {\n context: Scope | null;\n currentPointer: string | null;\n inSchema: boolean;\n node: unknown;\n path: ReadonlyArray<string | number>;\n visited?: Set<string>;\n};\n\n/**\n * Recursively updates $ref fields in the spec to point to the correct read/write variant\n * according to the current context (read/write), using the split mapping.\n *\n * @param spec - The OpenAPI spec object\n * @param split - The split mapping (from splitSchemas)\n */\nexport const updateRefsInSpec = ({\n logger,\n spec,\n split,\n}: {\n logger: Logger;\n spec: unknown;\n split: Omit<SplitSchemas, 'schemas'>;\n}): void => {\n const event = logger.timeEvent('update-refs-in-spec');\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n\n const walk = ({\n context,\n currentPointer,\n inSchema,\n node,\n path,\n visited = new Set(),\n }: WalkArgs): void => {\n if (node instanceof Array) {\n node.forEach((item, index) =>\n walk({\n context,\n currentPointer,\n inSchema,\n node: item,\n path: [...path, index],\n visited,\n }),\n );\n } else if (node && typeof node === 'object') {\n // Detect if we're entering a split schema variant\n let nextPointer = currentPointer;\n let nextContext = context;\n if (isPathRootSchema(path)) {\n // Use the last path segment instead of a fixed index (path[2]) because\n // path depth varies across OAS2/OAS3 and contexts; fixed indexing is brittle.\n const nameSegment = path[path.length - 1] as string;\n nextPointer = `${schemasPointerNamespace}${nameSegment}`;\n const originalPointer = split.reverseMapping[nextPointer];\n if (originalPointer) {\n const mapping = split.mapping[originalPointer];\n if (mapping?.read === nextPointer) {\n nextContext = 'read';\n } else if (mapping?.write === nextPointer) {\n nextContext = 'write';\n }\n }\n // For schemas that are not split variants, keep the inherited context.\n // This ensures that $refs inside these schemas are resolved based on\n // where the schema is actually used (requestBody vs responses), not\n // based on the schema's own scopes which track readOnly/writeOnly fields.\n }\n\n const compContext = getComponentContext(path);\n if (compContext !== undefined) {\n // For each component, walk with the correct context\n for (const key in node) {\n if (!Object.prototype.hasOwnProperty.call(node, key)) {\n continue;\n }\n walk({\n context: compContext,\n currentPointer: nextPointer,\n inSchema: false,\n node: (node as Record<string, unknown>)[key],\n path: [...path, key],\n visited,\n });\n }\n return;\n }\n\n for (const key in node) {\n if (!Object.prototype.hasOwnProperty.call(node, key)) {\n continue;\n }\n const value = (node as Record<string, unknown>)[key];\n\n // Only treat context switches at the OpenAPI structure level (not inside schemas)\n if (!inSchema) {\n if (key === 'requestBody') {\n walk({\n context: 'write',\n currentPointer: nextPointer,\n inSchema: false,\n node: value,\n path: [...path, key],\n visited,\n });\n continue;\n }\n if (key === 'responses') {\n walk({\n context: 'read',\n currentPointer: nextPointer,\n inSchema: false,\n node: value,\n path: [...path, key],\n visited,\n });\n continue;\n }\n if (key === 'parameters' && Array.isArray(value)) {\n value.forEach((param, index) => {\n if (param && typeof param === 'object' && 'schema' in param) {\n walk({\n context: 'write',\n currentPointer: nextPointer,\n inSchema: true,\n node: param.schema,\n path: [...path, key, index, 'schema'],\n visited,\n });\n }\n // Also handle content (OpenAPI 3.x)\n if (param && typeof param === 'object' && 'content' in param) {\n walk({\n context: 'write',\n currentPointer: nextPointer,\n inSchema: false,\n node: param.content,\n path: [...path, key, index, 'content'],\n visited,\n });\n }\n });\n continue;\n }\n // OpenAPI 3.x: headers in responses\n if (key === 'headers' && typeof value === 'object' && value !== null) {\n for (const headerKey in value) {\n if (!Object.prototype.hasOwnProperty.call(value, headerKey)) {\n continue;\n }\n walk({\n context: 'read',\n currentPointer: nextPointer,\n inSchema: false,\n node: (value as Record<string, unknown>)[headerKey],\n path: [...path, key, headerKey],\n visited,\n });\n }\n continue;\n }\n }\n\n // Entering a schema context\n if (schemaKeys.has(key)) {\n walk({\n context: nextContext,\n currentPointer: nextPointer,\n inSchema: true,\n node: value,\n path: [...path, key],\n visited,\n });\n } else if (key === '$ref' && typeof value === 'string') {\n // Prefer exact match first\n const map = split.mapping[value];\n if (map) {\n if (nextContext === 'read' && map.read) {\n (node as Record<string, unknown>)[key] = map.read;\n } else if (nextContext === 'write' && map.write) {\n (node as Record<string, unknown>)[key] = map.write;\n } else if (!nextContext && map.read) {\n // For schemas with no context (unused in operations), default to read variant\n // This ensures $refs in unused schemas don't point to removed originals\n (node as Record<string, unknown>)[key] = map.read;\n }\n }\n } else if (key === 'discriminator' && typeof value === 'object' && value !== null) {\n // Update discriminator mappings to point to the correct read/write variants\n if ('mapping' in value && value.mapping && typeof value.mapping === 'object') {\n const updatedMapping: Record<string, string> = {};\n for (const [discriminatorValue, originalRef] of Object.entries(value.mapping)) {\n const map = split.mapping[originalRef];\n if (map) {\n if (nextContext === 'read' && map.read) {\n updatedMapping[discriminatorValue] = map.read;\n } else if (nextContext === 'write' && map.write) {\n updatedMapping[discriminatorValue] = map.write;\n } else {\n // For schemas with no context, don't update the mapping.\n // This preserves the original mapping for base schemas.\n updatedMapping[discriminatorValue] = originalRef;\n }\n } else {\n updatedMapping[discriminatorValue] = originalRef;\n }\n }\n value.mapping = updatedMapping;\n }\n // Continue walking the discriminator object for other properties\n walk({\n context: nextContext,\n currentPointer: nextPointer,\n inSchema,\n node: value,\n path: [...path, key],\n visited,\n });\n } else {\n walk({\n context: nextContext,\n currentPointer: nextPointer,\n inSchema,\n node: value,\n path: [...path, key],\n visited,\n });\n }\n }\n }\n };\n walk({\n context: null,\n currentPointer: null,\n inSchema: false,\n node: spec,\n path: [],\n });\n event.timeEnd();\n};\n\n/**\n * Orchestrates the full read/write transform:\n * - Captures original schemas\n * - Splits schemas into read/write variants\n * - Inserts split schemas into the spec\n * - Updates $refs throughout the spec\n * - Removes original schemas that were split\n *\n * @param config - The readWrite transform config\n * @param spec - The OpenAPI spec object\n */\nexport const readWriteTransform = ({\n config,\n logger,\n spec,\n}: {\n config: ReadWriteConfig;\n logger: Logger;\n spec: unknown;\n}) => {\n const { graph } = buildGraph(spec, logger);\n const originalSchemas = captureOriginalSchemas(spec, logger);\n const split = splitSchemas({ config, graph, logger, spec });\n insertSplitSchemasIntoSpec({ logger, spec, split });\n updateRefsInSpec({ logger, spec, split });\n removeOriginalSplitSchemas({ logger, originalSchemas, spec, split });\n};\n","import type { Parser } from '../../../config/parser/types';\nimport { applyNaming } from '../../../utils/naming/naming';\nimport { getSchemasObject } from '../utils/transforms';\nimport { specToSchemasPointerNamespace } from './utils';\n\ntype SchemaNameConfig = Parser['transforms']['schemaName'];\n\n/**\n * Recursively walks the entire spec object and replaces all $ref strings\n * according to the provided rename mapping.\n */\nconst rewriteRefs = (node: unknown, renameMap: Record<string, string>) => {\n if (node instanceof Array) {\n node.forEach((item) => rewriteRefs(item, renameMap));\n } else if (node && typeof node === 'object') {\n for (const [key, value] of Object.entries(node)) {\n if (key === '$ref' && typeof value === 'string' && value in renameMap) {\n (node as Record<string, unknown>)[key] = renameMap[value];\n } else {\n rewriteRefs(value, renameMap);\n }\n }\n }\n};\n\n/**\n * Renames schema component keys and updates all $ref pointers throughout\n * the spec. Handles collisions by skipping renames when the target name\n * already exists or conflicts with another rename.\n */\nexport const schemaNameTransform = ({\n config,\n spec,\n}: {\n config: SchemaNameConfig;\n spec: unknown;\n}) => {\n if (!config) {\n return;\n }\n\n const schemasObj = getSchemasObject(spec);\n if (!schemasObj) {\n return;\n }\n\n const schemasPointerNamespace = specToSchemasPointerNamespace(spec);\n if (!schemasPointerNamespace) {\n return;\n }\n\n const renameMap: Record<string, string> = {};\n const newNames = new Set<string>();\n const namingConfig = { name: config };\n\n for (const oldName of Object.keys(schemasObj)) {\n const newName = applyNaming(oldName, namingConfig);\n\n if (newName === oldName || newName in schemasObj || newNames.has(newName)) {\n continue;\n }\n\n renameMap[`${schemasPointerNamespace}${oldName}`] = `${schemasPointerNamespace}${newName}`;\n newNames.add(newName);\n }\n\n for (const [oldPointer, newPointer] of Object.entries(renameMap)) {\n const oldName = oldPointer.slice(schemasPointerNamespace.length);\n const newName = newPointer.slice(schemasPointerNamespace.length);\n const schema = schemasObj[oldName];\n\n delete schemasObj[oldName];\n schemasObj[newName] = schema;\n }\n\n if (Object.keys(renameMap).length > 0) {\n rewriteRefs(spec, renameMap);\n }\n};\n","import type { Context } from '../../../ir/context';\nimport { enumsTransform } from './enums';\nimport { propertiesRequiredByDefaultTransform } from './propertiesRequiredByDefault';\nimport { readWriteTransform } from './readWrite';\nimport { schemaNameTransform } from './schemas';\n\nexport const transformOpenApiSpec = ({ context }: { context: Context }) => {\n const { logger } = context;\n const eventTransformOpenApiSpec = logger.timeEvent('transform-openapi-spec');\n\n if (context.config.parser.transforms.schemaName) {\n schemaNameTransform({\n config: context.config.parser.transforms.schemaName,\n spec: context.spec,\n });\n }\n\n if (context.config.parser.transforms.enums.enabled) {\n enumsTransform({\n config: context.config.parser.transforms.enums,\n spec: context.spec,\n });\n }\n\n if (context.config.parser.transforms.propertiesRequiredByDefault) {\n propertiesRequiredByDefaultTransform({ spec: context.spec });\n }\n\n if (context.config.parser.transforms.readWrite.enabled) {\n readWriteTransform({\n config: context.config.parser.transforms.readWrite,\n logger,\n spec: context.spec,\n });\n }\n eventTransformOpenApiSpec.timeEnd();\n};\n","import type { IR } from '../../../ir/types';\n\nexport const mergeParametersObjects = ({\n source,\n target,\n}: {\n source: IR.ParametersObject | undefined;\n target: IR.ParametersObject | undefined;\n}): IR.ParametersObject | undefined => {\n const result = { ...target };\n\n if (source) {\n if (source.cookie) {\n if (result.cookie) {\n result.cookie = {\n ...result.cookie,\n ...source.cookie,\n };\n } else {\n result.cookie = source.cookie;\n }\n }\n\n if (source.header) {\n if (result.header) {\n result.header = {\n ...result.header,\n ...source.header,\n };\n } else {\n result.header = source.header;\n }\n }\n\n if (source.path) {\n if (result.path) {\n result.path = {\n ...result.path,\n ...source.path,\n };\n } else {\n result.path = source.path;\n }\n }\n\n if (source.query) {\n if (result.query) {\n result.query = {\n ...result.query,\n ...source.query,\n };\n } else {\n result.query = source.query;\n }\n }\n }\n\n if (!Object.keys(result).length) {\n return;\n }\n\n return result;\n};\n","import colors from 'ansi-colors';\n\nimport type { Context } from '../../../ir/context';\n\nexport interface ValidatorIssue {\n /**\n * Machine-readable issue code\n *\n * @example\n * 'invalid_type'\n */\n code: 'duplicate_key' | 'invalid_type' | 'missing_required_field';\n /**\n * Optional additional data.\n *\n * @example\n * 'expectedType'\n */\n context?: Record<string, any>;\n /**\n * Human-readable issue summary.\n */\n message: string;\n /**\n * JSONPath-like array to issue location.\n */\n path: ReadonlyArray<string | number>;\n /**\n * Error severity.\n */\n severity: 'error' | 'warning';\n}\n\nexport interface ValidatorResult {\n issues: ReadonlyArray<ValidatorIssue>;\n valid: boolean;\n}\n\nconst isSimpleKey = (key: string) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);\n\nconst formatPath = (path: ReadonlyArray<string | number>): string =>\n path\n .map((segment, i) => {\n if (typeof segment === 'number') {\n return `[${segment}]`;\n }\n\n if (i === 0) {\n // first segment no dot or brackets\n return segment;\n }\n\n return isSimpleKey(segment) ? `.${segment}` : `['${segment.replace(/\"/g, \"\\\\'\")}']`;\n })\n .join('');\n\nconst formatValidatorIssue = (issue: ValidatorIssue): string => {\n const pathStr = formatPath(issue.path);\n const level = issue.severity === 'error' ? colors.bold.red : colors.bold.yellow;\n\n const highlightedMessage = issue.message.replace(/`([^`]+)`/g, (_, code) =>\n colors.yellow(`\\`${code}\\``),\n );\n\n return `${level(`[${issue.severity.toUpperCase()}]`)} ${colors.cyan(pathStr)}: ${highlightedMessage}`;\n};\n\nconst shouldPrint = ({ context, issue }: { context: Context; issue: ValidatorIssue }) => {\n if (context.config.logs.level === 'silent') {\n return false;\n }\n\n if (issue.severity === 'error') {\n return context.config.logs.level !== 'warn';\n }\n\n return true;\n};\n\nexport const handleValidatorResult = ({\n context,\n result,\n}: {\n context: Context;\n result: ValidatorResult;\n}) => {\n for (const issue of result.issues) {\n if (shouldPrint({ context, issue })) {\n console.log(formatValidatorIssue(issue));\n }\n }\n\n if (!result.valid) {\n process.exit(1);\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { OpenApiV2_0_X, OperationObject, PathItemObject, PathsObject } from '../types/spec';\n\n/**\n * Replace source spec with filtered version.\n */\nexport const filterSpec = ({\n logger,\n operations,\n preserveOrder,\n schemas,\n spec,\n}: {\n logger: Logger;\n operations: Set<string>;\n parameters: Set<string>;\n preserveOrder: boolean;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n spec: OpenApiV2_0_X;\n}) => {\n const eventFilterSpec = logger.timeEvent('filter-spec');\n if (spec.definitions) {\n const filtered: typeof spec.definitions = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.definitions)) {\n if (schemas.has(addNamespace('schema', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of schemas) {\n const { name } = removeNamespace(key);\n const source = spec.definitions[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.definitions = filtered;\n }\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n\n for (const method of httpMethods) {\n // @ts-expect-error\n const operation = pathItem[method] as OperationObject;\n if (!operation) {\n continue;\n }\n\n const key = addNamespace('operation', createOperationKey({ method, path }));\n if (!operations.has(key)) {\n // @ts-expect-error\n delete pathItem[method];\n }\n }\n\n // remove paths that have no operations left\n if (!Object.keys(pathItem).length) {\n delete spec.paths[path];\n }\n }\n }\n eventFilterSpec.timeEnd();\n};\n","const fileLikeRegExp =\n /^(application\\/(pdf|rtf|msword|vnd\\.(ms-|openxmlformats-officedocument\\.)|zip|x-(7z|tar|rar|zip|iso)|octet-stream|gzip|x-msdownload|json\\+download|xml|x-yaml|x-7z-compressed|x-tar)|text\\/(yaml|css|javascript)|audio\\/(mpeg|wav)|video\\/(mp4|x-matroska)|image\\/(vnd\\.adobe\\.photoshop|svg\\+xml))(; ?charset=[^;]+)?$/i;\nconst jsonMimeRegExp = /^application\\/(.*\\+)?json(;.*)?$/i;\nconst multipartFormDataMimeRegExp = /^multipart\\/form-data(;.*)?$/i;\nconst textMimeRegExp = /^text\\/[a-z0-9.+-]+(;.*)?$/i;\nconst xWwwFormUrlEncodedMimeRegExp = /^application\\/x-www-form-urlencoded(;.*)?$/i;\nconst octetStreamMimeRegExp = /^application\\/octet-stream(;.*)?$/i;\n\nexport type IRMediaType = 'form-data' | 'json' | 'text' | 'url-search-params' | 'octet-stream';\n\nexport const isMediaTypeFileLike = ({ mediaType }: { mediaType: string }): boolean => {\n fileLikeRegExp.lastIndex = 0;\n return fileLikeRegExp.test(mediaType);\n};\n\nexport const mediaTypeToIrMediaType = ({\n mediaType,\n}: {\n mediaType: string;\n}): IRMediaType | undefined => {\n jsonMimeRegExp.lastIndex = 0;\n if (jsonMimeRegExp.test(mediaType)) {\n return 'json';\n }\n\n multipartFormDataMimeRegExp.lastIndex = 0;\n if (multipartFormDataMimeRegExp.test(mediaType)) {\n return 'form-data';\n }\n\n textMimeRegExp.lastIndex = 0;\n if (textMimeRegExp.test(mediaType)) {\n return 'text';\n }\n\n xWwwFormUrlEncodedMimeRegExp.lastIndex = 0;\n if (xWwwFormUrlEncodedMimeRegExp.test(mediaType)) {\n return 'url-search-params';\n }\n\n octetStreamMimeRegExp.lastIndex = 0;\n if (octetStreamMimeRegExp.test(mediaType)) {\n return 'octet-stream';\n }\n\n return;\n};\n","import type { IRMediaType } from '../../../ir/mediaType';\nimport { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType';\nimport type { ReferenceObject, ResponseObject, SchemaObject } from '../types/spec';\n\ninterface Content {\n mediaType: string;\n schema: SchemaObject | ReferenceObject | undefined;\n type: IRMediaType | undefined;\n}\n\nexport const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => {\n const { mediaType, schema } = content;\n\n if (schema && '$ref' in schema) {\n return {\n allOf: [{ ...schema }],\n };\n }\n\n if (!schema) {\n if (isMediaTypeFileLike({ mediaType })) {\n return {\n format: 'binary',\n type: 'string',\n };\n }\n return;\n }\n\n if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) {\n return {\n ...schema,\n format: 'binary',\n };\n }\n\n return schema;\n};\n\nexport const mediaTypeObjects = ({\n mimeTypes,\n response,\n}: {\n mimeTypes: ReadonlyArray<string> | undefined;\n response: Pick<ResponseObject, 'schema'>;\n}): ReadonlyArray<Content> => {\n const objects: Array<Content> = [];\n\n for (const mediaType of mimeTypes ?? []) {\n objects.push({\n mediaType,\n schema: response.schema,\n type: mediaTypeToIrMediaType({ mediaType }),\n });\n }\n\n return objects;\n};\n","import type { Parser } from '../config/parser/types';\nimport type { IR } from './types';\n\nexport function getPaginationKeywordsRegExp(pagination: Parser['pagination']): RegExp {\n const pattern = `^(${pagination.keywords.join('|')})$`;\n return new RegExp(pattern);\n}\n\nexport interface Pagination {\n in: 'body' | 'cookie' | 'header' | 'path' | 'query';\n name: string;\n schema: IR.SchemaObject;\n}\n","import type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\n\n/**\n * Supported types for discriminator properties.\n */\nexport type DiscriminatorPropertyType = 'boolean' | 'integer' | 'number' | 'string';\n\n/**\n * Converts a string discriminator mapping value to the appropriate type based on\n * the actual property type in the schema.\n *\n * OpenAPI discriminator mappings always use string keys, but the actual discriminator\n * property may be a boolean, number, or integer. This function converts the string\n * key to the correct runtime value and IR type.\n */\nexport const convertDiscriminatorValue = (\n value: string,\n propertyType: DiscriminatorPropertyType,\n): { const: IR.SchemaObject['const']; type: IR.SchemaObject['type'] } => {\n switch (propertyType) {\n case 'boolean': {\n const lowerValue = value.toLowerCase();\n if (lowerValue !== 'true' && lowerValue !== 'false') {\n console.warn(\n '๐Ÿšจ',\n `non-boolean discriminator mapping value \"${value}\" for boolean property, falling back to string`,\n );\n return {\n const: value,\n type: 'string',\n };\n }\n return {\n const: lowerValue === 'true',\n type: 'boolean',\n };\n }\n case 'integer': {\n const parsed = parseInt(value, 10);\n if (Number.isNaN(parsed)) {\n console.warn(\n '๐Ÿšจ',\n `non-numeric discriminator mapping value \"${value}\" for integer property, falling back to string`,\n );\n return {\n const: value,\n type: 'string',\n };\n }\n return {\n const: parsed,\n type: 'integer',\n };\n }\n case 'number': {\n const parsed = parseFloat(value);\n if (Number.isNaN(parsed)) {\n console.warn(\n '๐Ÿšจ',\n `non-numeric discriminator mapping value \"${value}\" for number property, falling back to string`,\n );\n return {\n const: value,\n type: 'string',\n };\n }\n return {\n const: parsed,\n type: 'number',\n };\n }\n default:\n return {\n const: value,\n type: 'string',\n };\n }\n};\n\nexport const discriminatorValues = (\n $ref: string,\n mapping?: Record<string, string>,\n shouldUseRefAsValue?: () => boolean,\n): ReadonlyArray<string> => {\n const values: Array<string> = [];\n\n for (const name in mapping) {\n if (mapping[name] === $ref) {\n values.push(name);\n }\n }\n\n if (!values.length && (!shouldUseRefAsValue || shouldUseRefAsValue())) {\n return [refToName($ref)];\n }\n\n return values;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { addItemsToSchema } from '../../../ir/utils';\nimport type {\n SchemaState,\n SchemaType,\n SchemaWithRequired,\n} from '../../../openApi/shared/types/schema';\nimport { discriminatorValues } from '../../../openApi/shared/utils/discriminator';\nimport { isTopLevelComponent, refToName } from '../../../utils/ref';\nimport type { SchemaObject } from '../types/spec';\n\nexport const getSchemaType = ({\n schema,\n}: {\n schema: SchemaObject;\n}): SchemaType<SchemaObject> | undefined => {\n if (schema.type) {\n return schema.type;\n }\n\n // infer object based on the presence of properties\n if (schema.properties) {\n return 'object';\n }\n\n return;\n};\n\nconst parseSchemaJsDoc = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.example) {\n irSchema.example = schema.example;\n }\n\n if (schema.description) {\n irSchema.description = schema.description;\n }\n\n if (schema.title) {\n irSchema.title = schema.title;\n }\n};\n\nconst parseSchemaMeta = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.default !== undefined) {\n irSchema.default = schema.default;\n }\n\n if (schema.exclusiveMaximum) {\n if (schema.maximum !== undefined) {\n irSchema.exclusiveMaximum = schema.maximum;\n }\n } else if (schema.maximum !== undefined) {\n irSchema.maximum = schema.maximum;\n }\n\n if (schema.exclusiveMinimum) {\n if (schema.minimum !== undefined) {\n irSchema.exclusiveMinimum = schema.minimum;\n }\n } else if (schema.minimum !== undefined) {\n irSchema.minimum = schema.minimum;\n }\n\n if (schema.format) {\n irSchema.format = schema.format;\n }\n\n if (schema.maxItems !== undefined) {\n irSchema.maxItems = schema.maxItems;\n }\n\n if (schema.maxLength !== undefined) {\n irSchema.maxLength = schema.maxLength;\n }\n\n if (schema.minItems !== undefined) {\n irSchema.minItems = schema.minItems;\n }\n\n if (schema.minLength !== undefined) {\n irSchema.minLength = schema.minLength;\n }\n\n if (schema.pattern) {\n irSchema.pattern = schema.pattern;\n }\n\n if (schema.readOnly) {\n irSchema.accessScope = 'read';\n }\n};\n\nconst parseArray = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (schema.maxItems && schema.maxItems === schema.minItems) {\n irSchema.type = 'tuple';\n } else {\n irSchema.type = 'array';\n }\n\n let schemaItems: Array<IR.SchemaObject> = [];\n\n if (schema.items) {\n const irItemsSchema = schemaToIrSchema({\n context,\n schema: schema.items,\n state,\n });\n\n if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {\n schemaItems = Array(schema.maxItems).fill(irItemsSchema);\n } else {\n if ('$ref' in schema.items) {\n schemaItems.push(irItemsSchema);\n } else {\n const ofArray = schema.items.allOf;\n if (ofArray && ofArray.length > 1 && !schema.items['x-nullable']) {\n // bring composition up to avoid incorrectly nested arrays\n irSchema = {\n ...irSchema,\n ...irItemsSchema,\n };\n } else {\n schemaItems.push(irItemsSchema);\n }\n }\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseBoolean = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'boolean';\n\n return irSchema;\n};\n\nconst parseNumber = ({\n irSchema = {},\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = schema.type;\n\n return irSchema;\n};\n\nconst parseObject = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'object';\n\n const schemaProperties: Record<string, IR.SchemaObject> = {};\n\n for (const name in schema.properties) {\n const property = schema.properties[name]!;\n if (typeof property === 'boolean') {\n // TODO: parser - handle boolean properties\n } else {\n const irPropertySchema = schemaToIrSchema({\n context,\n schema: property,\n state,\n });\n schemaProperties[name] = irPropertySchema;\n }\n }\n\n if (Object.keys(schemaProperties).length) {\n irSchema.properties = schemaProperties;\n }\n\n if (schema.additionalProperties === undefined) {\n if (!irSchema.properties) {\n irSchema.additionalProperties = {\n type: 'unknown',\n };\n }\n } else if (typeof schema.additionalProperties === 'boolean') {\n // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf\n // This would override inherited properties from other schemas in the composition\n const isEmptyObjectInAllOf =\n state.inAllOf &&\n schema.additionalProperties === false &&\n (!schema.properties || !Object.keys(schema.properties).length);\n\n if (!isEmptyObjectInAllOf) {\n irSchema.additionalProperties = {\n type: schema.additionalProperties ? 'unknown' : 'never',\n };\n }\n } else {\n const irAdditionalPropertiesSchema = schemaToIrSchema({\n context,\n schema: schema.additionalProperties,\n state,\n });\n irSchema.additionalProperties = irAdditionalPropertiesSchema;\n }\n\n if (schema.required) {\n irSchema.required = schema.required;\n }\n\n return irSchema;\n};\n\nconst parseString = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'string';\n\n return irSchema;\n};\n\nexport const parseExtensions = ({ source, target }: { source: object; target: object }) => {\n for (const key in source) {\n if (key.startsWith('x-')) {\n (target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];\n }\n }\n};\n\nconst initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n\n parseSchemaJsDoc({\n irSchema,\n schema,\n });\n\n parseExtensions({\n source: schema,\n target: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseAllOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'allOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.allOf;\n\n for (const compositionSchema of compositionSchemas) {\n const originalInAllOf = state.inAllOf;\n // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components\n if (!('$ref' in compositionSchema)) {\n state.inAllOf = true;\n }\n const irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n state.inAllOf = originalInAllOf;\n if (state.inAllOf === undefined) {\n delete state.inAllOf;\n }\n\n if (schema.required) {\n if (irCompositionSchema.required) {\n irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];\n } else {\n irCompositionSchema.required = schema.required;\n }\n }\n\n schemaItems.push(irCompositionSchema);\n\n if (compositionSchema.$ref) {\n const ref = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n // `$ref` should be passed from the root `parseSchema()` call\n if (ref.discriminator && state.$ref) {\n const values = discriminatorValues(state.$ref);\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) => ({\n const: value,\n type: 'string',\n }));\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [ref.discriminator]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n type: 'object',\n };\n if (ref.required?.includes(ref.discriminator)) {\n irDiscriminatorSchema.required = [ref.discriminator];\n }\n schemaItems.push(irDiscriminatorSchema);\n }\n }\n }\n\n if (schemaType === 'object') {\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n for (const requiredProperty of irObjectSchema.required ?? []) {\n if (!irObjectSchema.properties[requiredProperty]) {\n for (const compositionSchema of compositionSchemas) {\n // TODO: parser - this could be probably resolved more accurately\n const finalCompositionSchema = compositionSchema.$ref\n ? context.resolveRef<SchemaObject>(compositionSchema.$ref)\n : compositionSchema;\n\n if (getSchemaType({ schema: finalCompositionSchema }) === 'object') {\n const irCompositionSchema = parseOneType({\n context,\n schema: {\n ...finalCompositionSchema,\n type: 'object',\n },\n state,\n });\n\n if (irCompositionSchema.properties?.[requiredProperty]) {\n irObjectSchema.properties[requiredProperty] =\n irCompositionSchema.properties[requiredProperty];\n break;\n }\n }\n }\n }\n }\n schemaItems.push(irObjectSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n logicalOperator: 'and',\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schema['x-nullable']) {\n // nest composition to avoid producing an intersection with null\n const nestedItems: Array<IR.SchemaObject> = [\n {\n type: 'null',\n },\n ];\n\n if (schemaItems.length) {\n nestedItems.unshift(irSchema);\n }\n\n irSchema = {\n items: nestedItems,\n logicalOperator: 'or',\n };\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original deprecated\n if (nestedItems[0]!.deprecated) {\n irSchema.deprecated = nestedItems[0]!.deprecated;\n }\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original description\n if (nestedItems[0]!.description) {\n irSchema.description = nestedItems[0]!.description;\n }\n }\n\n return irSchema;\n};\n\nconst parseEnum = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'enum'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n irSchema.type = 'enum';\n\n const schemaItems: Array<IR.SchemaObject> = [];\n\n for (const [index, enumValue] of schema.enum.entries()) {\n const typeOfEnumValue = typeof enumValue;\n let enumType: SchemaType<SchemaObject> | 'null' | undefined;\n\n if (\n typeOfEnumValue === 'string' ||\n typeOfEnumValue === 'number' ||\n typeOfEnumValue === 'boolean'\n ) {\n enumType = typeOfEnumValue;\n } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {\n enumType = 'array';\n } else if (enumValue === null) {\n // nullable must be true\n if (schema['x-nullable']) {\n enumType = 'null';\n }\n } else {\n console.warn(\n '๐Ÿšจ',\n `unhandled \"${typeOfEnumValue}\" typeof value \"${enumValue}\" for enum`,\n schema.enum,\n );\n }\n\n if (!enumType) {\n continue;\n }\n\n const irTypeSchema = parseOneType({\n context,\n schema: {\n description: schema['x-enum-descriptions']?.[index],\n title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],\n // cast enum to string temporarily\n type: enumType === 'null' ? 'string' : enumType,\n },\n state,\n });\n\n irTypeSchema.const = enumValue;\n\n // cast enum back\n if (enumType === 'null') {\n irTypeSchema.type = enumType;\n }\n\n if (irTypeSchema.type === 'array') {\n irTypeSchema.type = 'tuple';\n }\n\n schemaItems.push(irTypeSchema);\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseRef = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, '$ref'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/definitions/Foo/properties/bar)\n // to avoid generating orphaned named types or referencing unregistered symbols\n const isComponentsRef = isTopLevelComponent(schema.$ref);\n if (!isComponentsRef) {\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n const irSchema = schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n return irSchema;\n }\n // Fallback to preserving the ref if circular\n }\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n irSchema.$ref = decodeURI(schema.$ref);\n\n // rewrite definitions refs as the internal schema follows OpenAPI 3.x syntax\n // and stores all definitions as reusable schemas\n irSchema.$ref = irSchema.$ref.replace(/#\\/definitions\\/([^/]+)/g, '#/components/schemas/$1');\n\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n }\n\n return irSchema;\n};\n\nconst parseNullableType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n const typeIrSchema: IR.SchemaObject = {};\n\n parseSchemaMeta({ irSchema: typeIrSchema, schema });\n\n if (typeIrSchema.default === null) {\n // clear to avoid duplicate default inside the non-null schema.\n // this would produce incorrect validator output\n delete typeIrSchema.default;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [\n parseOneType({\n context,\n irSchema: typeIrSchema,\n schema,\n state,\n }),\n {\n type: 'null',\n },\n ];\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseType = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n\n const type = getSchemaType({ schema });\n\n if (!type) {\n return irSchema;\n }\n\n if (schema['x-nullable']) {\n return parseNullableType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n }\n\n return parseOneType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n};\n\nconst parseOneType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n }\n\n switch (schema.type) {\n case 'array':\n return parseArray({\n context,\n irSchema,\n schema,\n state,\n });\n case 'boolean':\n return parseBoolean({\n context,\n irSchema,\n schema,\n state,\n });\n case 'integer':\n case 'number':\n return parseNumber({\n context,\n irSchema,\n schema,\n state,\n });\n case 'object':\n return parseObject({\n context,\n irSchema,\n schema,\n state,\n });\n case 'string':\n return parseString({\n context,\n irSchema,\n schema,\n state,\n });\n default:\n // gracefully handle invalid type\n return parseUnknown({\n context,\n irSchema,\n schema,\n });\n }\n};\n\nconst parseUnknown = ({\n irSchema,\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n irSchema.type = 'unknown';\n\n parseSchemaMeta({ irSchema, schema });\n\n return irSchema;\n};\n\nexport const schemaToIrSchema = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaObject;\n state: SchemaState | undefined;\n}): IR.SchemaObject => {\n if (!state) {\n state = {\n circularReferenceTracker: new Set(),\n };\n }\n\n if (state.$ref) {\n state.circularReferenceTracker.add(state.$ref);\n }\n\n if (schema.$ref) {\n return parseRef({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, '$ref'>,\n state,\n });\n }\n\n if (schema.enum) {\n return parseEnum({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'enum'>,\n state,\n });\n }\n\n if (schema.allOf) {\n return parseAllOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'allOf'>,\n state,\n });\n }\n\n // infer object based on the presence of properties\n if (schema.type || schema.properties) {\n return parseType({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n return parseUnknown({ context, schema });\n};\n\nexport const parseSchema = ({\n $ref,\n context,\n schema,\n}: {\n $ref: string;\n context: Context;\n schema: SchemaObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.schemas) {\n context.ir.components.schemas = {};\n }\n\n context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({\n context,\n schema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { getPaginationKeywordsRegExp } from '../../../ir/pagination';\nimport type { SchemaType } from '../../../openApi/shared/types/schema';\nimport type { ParameterObject, ReferenceObject } from '../types/spec';\nimport type { SchemaObject } from '../types/spec';\nimport { getSchemaType } from './schema';\n\nconst isPaginationType = (schemaType: SchemaType<SchemaObject> | undefined): boolean =>\n schemaType === 'boolean' ||\n schemaType === 'integer' ||\n schemaType === 'number' ||\n schemaType === 'string';\n\n// We handle only simple values for now, up to 1 nested field\nexport const paginationField = ({\n context,\n name,\n schema,\n}: {\n context: Context;\n name: string;\n schema:\n | ParameterObject\n | SchemaObject\n | ReferenceObject\n | {\n in: undefined;\n };\n}): boolean | string => {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n if (paginationRegExp.test(name)) {\n return true;\n }\n\n if ('$ref' in schema) {\n const ref = context.resolveRef<ParameterObject | SchemaObject>(schema.$ref ?? '');\n\n if ('in' in ref && ref.in) {\n const refSchema =\n 'schema' in ref\n ? ref.schema\n : {\n ...ref,\n in: undefined,\n };\n\n return paginationField({\n context,\n name,\n schema: refSchema,\n });\n }\n\n return paginationField({\n context,\n name,\n schema: ref,\n });\n }\n\n if ('in' in schema) {\n if (!schema.in) {\n return false;\n }\n\n const finalSchema =\n 'schema' in schema\n ? schema.schema\n : {\n ...schema,\n in: undefined,\n };\n\n return paginationField({\n context,\n name,\n schema: finalSchema,\n });\n }\n\n for (const name in schema.properties) {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n\n if (paginationRegExp.test(name)) {\n const property = schema.properties[name]!;\n\n if (typeof property !== 'boolean' && !('$ref' in property)) {\n const schemaType = getSchemaType({ schema: property });\n // TODO: resolve deeper references\n\n if (isPaginationType(schemaType)) {\n return name;\n }\n }\n }\n }\n\n for (const allOf of schema.allOf ?? []) {\n const pagination = paginationField({\n context,\n name,\n schema: allOf,\n });\n if (pagination) {\n return pagination;\n }\n }\n\n return false;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type { State } from '../../../openApi/shared/types/state';\nimport { operationToId } from '../../../openApi/shared/utils/operation';\nimport type {\n OperationObject,\n ParameterObject,\n PathItemObject,\n ResponseObject,\n SchemaObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { contentToSchema, mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ninterface Operation\n extends Omit<OperationObject, 'parameters'>, Pick<IR.OperationObject, 'parameters'> {\n requestBody?: OperationObject['parameters'];\n}\n\nconst parseOperationJsDoc = ({\n irOperation,\n operation,\n}: {\n irOperation: IR.OperationObject;\n operation: Operation;\n}) => {\n if (operation.deprecated !== undefined) {\n irOperation.deprecated = operation.deprecated;\n }\n\n if (operation.description) {\n irOperation.description = operation.description;\n }\n\n if (operation.summary) {\n irOperation.summary = operation.summary;\n }\n\n if (operation.tags?.length) {\n irOperation.tags = operation.tags;\n }\n};\n\nconst initIrOperation = ({\n context,\n method,\n operation,\n path,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n state: State;\n}): IR.OperationObject => {\n const irOperation: IR.OperationObject = {\n id: operationToId({\n context,\n id: operation.operationId,\n method,\n path,\n state,\n }),\n method,\n path,\n };\n\n if (operation.operationId) {\n irOperation.operationId = operation.operationId;\n }\n\n parseOperationJsDoc({\n irOperation,\n operation,\n });\n\n parseExtensions({\n source: operation,\n target: irOperation,\n });\n\n return irOperation;\n};\n\nconst operationToIrOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}): IR.OperationObject => {\n const irOperation = initIrOperation({\n context,\n method,\n operation,\n path,\n state,\n });\n\n if (operation.parameters) {\n irOperation.parameters = operation.parameters;\n }\n\n let isRequestBodyRequired = false;\n const requestBodyObject: IR.BodyObject = {\n mediaType: '',\n schema: {\n properties: {},\n required: [],\n type: 'object',\n },\n };\n const requestBodyObjectRequired: Array<string> = [];\n\n // Check if there are any body parameters (not formData) to determine default media type\n const hasBodyParameter = operation.requestBody?.some((param) => {\n const resolvedParam = '$ref' in param ? context.resolveRef<ParameterObject>(param.$ref) : param;\n return resolvedParam.in === 'body';\n });\n\n for (const requestBodyParameter of operation.requestBody ?? []) {\n const requestBody =\n '$ref' in requestBodyParameter\n ? context.resolveRef<ParameterObject>(requestBodyParameter.$ref)\n : requestBodyParameter;\n const schema: SchemaObject =\n requestBody.in === 'body'\n ? requestBody.schema\n : {\n ...requestBody,\n format: requestBody.type === 'file' ? 'binary' : requestBody.format,\n required: undefined,\n type: requestBody.type === 'file' ? 'string' : requestBody.type,\n };\n\n // Only default to JSON if we have body parameters and no consumes specified\n // FormData parameters without consumes should not get a default media type\n let mimeTypes = operation.consumes;\n if (!mimeTypes && hasBodyParameter && requestBody.in === 'body') {\n mimeTypes = ['application/json'];\n }\n\n const contents = mediaTypeObjects({\n mimeTypes,\n response: { schema },\n });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n const pagination = paginationField({\n context,\n name: '',\n schema:\n content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n });\n\n const irSchema = schemaToIrSchema({\n context,\n schema:\n '$ref' in requestBody\n ? {\n allOf: [\n {\n ...requestBody,\n $ref: requestBody.$ref as string,\n required: [],\n type: 'string',\n },\n ],\n description: requestBody.description,\n }\n : content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n state: undefined,\n });\n\n requestBodyObject.mediaType = content.mediaType;\n\n if (requestBody.in === 'body') {\n requestBodyObject.schema = irSchema;\n } else {\n requestBodyObject.schema.properties![requestBody.name] = irSchema;\n\n if (requestBody.required) {\n requestBodyObjectRequired.push(requestBody.name);\n }\n }\n\n if (pagination) {\n requestBodyObject.pagination = pagination;\n }\n\n if (content.type) {\n requestBodyObject.type = content.type;\n }\n }\n\n if (requestBody.required) {\n isRequestBodyRequired = true;\n }\n }\n\n if (requestBodyObject.mediaType) {\n if (requestBodyObjectRequired.length) {\n requestBodyObject.schema.required = requestBodyObjectRequired;\n }\n\n irOperation.body = requestBodyObject;\n\n if (isRequestBodyRequired) {\n irOperation.body.required = isRequestBodyRequired;\n }\n }\n\n for (const name in operation.responses) {\n if (!irOperation.responses) {\n irOperation.responses = {};\n }\n\n const response = operation.responses[name]!;\n const responseObject =\n '$ref' in response ? context.resolveRef<ResponseObject>(response.$ref) : response;\n const contents = mediaTypeObjects({\n // assume JSON by default\n mimeTypes: operation.produces ? operation.produces : ['application/json'],\n response: responseObject,\n });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n irOperation.responses[name] = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: responseObject.description,\n ...contentToSchema({ content }),\n },\n state: undefined,\n }),\n };\n } else {\n irOperation.responses[name] = {\n schema: {\n description: responseObject.description,\n // TODO: parser - cover all statues with empty response bodies\n // 1xx, 204, 205, 304\n type: name === '204' ? 'void' : 'unknown',\n },\n };\n }\n }\n\n if (operation.security) {\n const securitySchemeObjects: Map<string, IR.SecurityObject> = new Map();\n\n for (const securityRequirementObject of operation.security) {\n for (const name in securityRequirementObject) {\n const securitySchemeObject = securitySchemesMap.get(name);\n\n if (!securitySchemeObject) {\n continue;\n }\n\n let irSecuritySchemeObject: IR.SecurityObject | undefined;\n\n if (securitySchemeObject.type === 'apiKey') {\n irSecuritySchemeObject = securitySchemeObject;\n }\n\n if (securitySchemeObject.type === 'basic') {\n irSecuritySchemeObject = {\n description: securitySchemeObject.description,\n scheme: 'basic',\n type: 'http',\n };\n }\n\n if (securitySchemeObject.type === 'oauth2') {\n irSecuritySchemeObject = {\n description: securitySchemeObject.description,\n flows: {},\n type: 'oauth2',\n };\n\n switch (securitySchemeObject.flow) {\n case 'accessCode':\n irSecuritySchemeObject.flows.authorizationCode = {\n authorizationUrl: securitySchemeObject.authorizationUrl!,\n scopes: securitySchemeObject.scopes,\n tokenUrl: securitySchemeObject.tokenUrl!,\n };\n break;\n case 'application':\n irSecuritySchemeObject.flows.clientCredentials = {\n scopes: securitySchemeObject.scopes,\n tokenUrl: securitySchemeObject.tokenUrl!,\n };\n break;\n case 'implicit':\n irSecuritySchemeObject.flows.implicit = {\n authorizationUrl: securitySchemeObject.authorizationUrl!,\n scopes: securitySchemeObject.scopes,\n };\n break;\n case 'password':\n irSecuritySchemeObject.flows.password = {\n scopes: securitySchemeObject.scopes,\n tokenUrl: securitySchemeObject.tokenUrl!,\n };\n break;\n }\n }\n\n if (!irSecuritySchemeObject) {\n continue;\n }\n\n securitySchemeObjects.set(name, irSecuritySchemeObject);\n }\n }\n\n if (securitySchemeObjects.size) {\n irOperation.security = Array.from(securitySchemeObjects.values());\n }\n }\n\n // TODO: parser - handle servers\n // qux: operation.servers\n\n return irOperation;\n};\n\nexport const parsePathOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: {\n context: Context;\n method: Extract<\n keyof PathItemObject,\n 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'\n >;\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.paths) {\n context.ir.paths = {};\n }\n\n if (!context.ir.paths[path]) {\n context.ir.paths[path] = {};\n }\n\n context.ir.paths[path][method] = operationToIrOperation({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type {\n OperationObject,\n ParameterObject,\n ReferenceObject,\n SchemaObject,\n} from '../types/spec';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ntype Parameter = Exclude<ParameterObject, { in: 'body' }>;\n\n/**\n * Returns default parameter `explode` based on value of `collectionFormat`.\n */\nconst defaultExplode = (collectionFormat: Parameter['collectionFormat']): boolean => {\n switch (collectionFormat) {\n case 'multi':\n return true;\n case 'csv':\n case 'pipes':\n case 'ssv':\n case 'tsv':\n default:\n return false;\n }\n};\n\n/**\n * Returns default parameter `style` based on value of `in`.\n */\nconst defaultStyle = (_in: Parameter['in']): Required<IR.ParameterObject>['style'] => {\n switch (_in) {\n case 'header':\n case 'path':\n return 'simple';\n case 'query':\n default:\n return 'form';\n }\n};\n\nexport const parametersArrayToObject = ({\n context,\n operation,\n parameters,\n}: {\n context: Context;\n operation: OperationObject;\n parameters?: ReadonlyArray<ParameterObject | ReferenceObject>;\n}): IR.ParametersObject | undefined => {\n if (!parameters || !Object.keys(parameters).length) {\n return;\n }\n\n const parametersObject: IR.ParametersObject = {};\n\n for (const parameterOrReference of parameters) {\n const parameter =\n '$ref' in parameterOrReference\n ? context.dereference<ParameterObject>(parameterOrReference)\n : parameterOrReference;\n\n // push request body parameters into a separate field\n if (parameter.in === 'body' || parameter.in === 'formData') {\n // @ts-expect-error\n if (!operation.requestBody) {\n // @ts-expect-error\n operation.requestBody = [];\n }\n\n // @ts-expect-error\n operation.requestBody.push(parameter);\n continue;\n }\n\n if (!parametersObject[parameter.in]) {\n parametersObject[parameter.in] = {};\n }\n\n // lowercase keys for case insensitive access\n parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({\n $ref: `#/todo/real/path/to/parameter/${parameter.name}`,\n context,\n parameter,\n });\n }\n\n return parametersObject;\n};\n\nconst parameterToIrParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: Parameter;\n}): IR.ParameterObject => {\n const schema = parameter;\n\n const finalSchema: SchemaObject =\n schema && '$ref' in schema\n ? {\n allOf: [\n {\n ...schema,\n $ref: schema.$ref as string,\n required: Array.isArray(schema.required) ? schema.required : [],\n type: schema.type as SchemaObject['type'],\n },\n ],\n description: parameter.description,\n }\n : {\n description: parameter.description,\n ...schema,\n required: Array.isArray(schema.required) ? schema.required : [],\n type: schema.type as SchemaObject['type'],\n };\n\n const pagination = paginationField({\n context,\n name: parameter.name,\n schema: finalSchema,\n });\n\n const style = defaultStyle(parameter.in);\n const explode = defaultExplode(parameter.collectionFormat);\n const allowReserved = false;\n\n const irParameter: IR.ParameterObject = {\n allowReserved,\n explode,\n location: parameter.in as IR.ParameterObject['location'],\n name: parameter.name,\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n style,\n };\n\n if (parameter.description) {\n irParameter.description = parameter.description;\n }\n\n if (pagination) {\n irParameter.pagination = pagination;\n }\n\n if (parameter.required) {\n irParameter.required = parameter.required;\n }\n\n parseExtensions({\n source: parameter,\n target: irParameter,\n });\n\n return irParameter;\n};\n","const parseUrlRegExp =\n /^(([^:/?#]+):)?((\\/\\/)?([^:/?#]*)(:?([^/?#]*)))?([^?#]*)(\\?([^#]*))?(#(.*))?/;\n\ninterface Url {\n host: string;\n path: string;\n port: string;\n protocol: string;\n}\n\nexport function parseUrl(value: string): Url {\n const errorResponse: Url = {\n host: '',\n path: '',\n port: '',\n protocol: '',\n };\n\n parseUrlRegExp.lastIndex = 0;\n const match = value.match(parseUrlRegExp);\n\n if (!match) {\n return errorResponse;\n }\n\n const host = match[5] || '';\n\n // value is a relative file system path\n if (host === '.' || host === '..') {\n return errorResponse;\n }\n\n const path = match[8] || '';\n const protocol = match[2] || '';\n\n // value is probably a Windows file system path\n if (protocol.length === 1) {\n return errorResponse;\n }\n\n return {\n host,\n path: path === '/' ? '' : path,\n port: match[7] || '',\n protocol,\n };\n}\n","import type { Context } from '../../../ir/context';\nimport { parseUrl } from '../../../utils/url';\n\nexport const parseServers = ({ context }: { context: Context }) => {\n let schemes: ReadonlyArray<string> = context.spec.schemes ?? [];\n let host = context.spec.host ?? '';\n const path = context.spec.basePath ?? '';\n\n for (const input of context.config.input) {\n if (typeof input.path === 'string') {\n const url = parseUrl(input.path);\n\n if (!schemes.length) {\n if (url.protocol) {\n schemes = [url.protocol] as typeof schemes;\n }\n }\n\n if (!host) {\n host = `${url.host}${url.port ? `:${url.port}` : ''}`;\n }\n }\n }\n\n if (!schemes.length) {\n schemes = [''];\n }\n\n const servers = schemes\n .map((scheme) => `${scheme ? `${scheme}://` : ''}${host}${path}`)\n .filter(Boolean);\n\n if (servers.length) {\n context.ir.servers = servers.map((url) => ({\n url,\n }));\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type { OpenApiV2_0_X, PathItemObject, PathsObject } from '../types/spec';\n\nexport const validateOpenApiSpec = (spec: OpenApiV2_0_X, logger: Logger): ValidatorResult => {\n const eventValidate = logger.timeEvent('validate');\n const issues: Array<ValidatorIssue> = [];\n const operationIds = new Map();\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n if (method === 'trace') {\n continue;\n }\n\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const operationKey = createOperationKey({ method, path });\n\n if (operation.operationId) {\n if (!operationIds.has(operation.operationId)) {\n operationIds.set(operation.operationId, operationKey);\n } else {\n issues.push({\n code: 'duplicate_key',\n context: {\n key: 'operationId',\n value: operation.operationId,\n },\n message: 'Duplicate `operationId` found. Each `operationId` must be unique.',\n path: ['paths', path, method, 'operationId'],\n severity: 'error',\n });\n }\n }\n }\n }\n }\n\n eventValidate.timeEnd();\n return {\n issues,\n valid: !issues.some((issue) => issue.severity === 'error'),\n };\n};\n","import type { Context } from '../../../ir/context';\nimport { buildResourceMetadata } from '../../../openApi/shared/graph/meta';\nimport { transformOpenApiSpec } from '../../../openApi/shared/transforms';\nimport type { State } from '../../../openApi/shared/types/state';\nimport {\n createFilteredDependencies,\n createFilters,\n hasFilters,\n} from '../../../openApi/shared/utils/filter';\nimport { buildGraph } from '../../../openApi/shared/utils/graph';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport { handleValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type {\n OpenApiV2_0_X,\n OperationObject,\n PathItemObject,\n PathsObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { filterSpec } from './filter';\nimport { parsePathOperation } from './operation';\nimport { parametersArrayToObject } from './parameter';\nimport { parseSchema } from './schema';\nimport { parseServers } from './server';\nimport { validateOpenApiSpec } from './validate';\n\ntype PathKeys<T extends keyof PathsObject = keyof PathsObject> = keyof T extends infer K\n ? K extends `/${string}`\n ? K\n : never\n : never;\n\nexport const parseV2_0_X = (context: Context<OpenApiV2_0_X>) => {\n if (context.config.parser.validate_EXPERIMENTAL) {\n const result = validateOpenApiSpec(context.spec, context.logger);\n handleValidatorResult({ context, result });\n }\n\n const shouldFilterSpec = hasFilters(context.config.parser.filters);\n if (shouldFilterSpec) {\n const filters = createFilters(context.config.parser.filters, context.spec, context.logger);\n const { graph } = buildGraph(context.spec, context.logger);\n const { resourceMetadata } = buildResourceMetadata(graph, context.logger);\n const sets = createFilteredDependencies({\n filters,\n logger: context.logger,\n resourceMetadata,\n });\n filterSpec({\n ...sets,\n logger: context.logger,\n preserveOrder: filters.preserveOrder,\n spec: context.spec,\n });\n }\n\n transformOpenApiSpec({ context });\n\n const state: State = {\n ids: new Map(),\n };\n const securitySchemesMap = new Map<string, SecuritySchemeObject>();\n\n for (const name in context.spec.securityDefinitions) {\n const securitySchemeObject = context.spec.securityDefinitions[name]!;\n securitySchemesMap.set(name, securitySchemeObject);\n }\n\n if (context.spec.definitions) {\n for (const name in context.spec.definitions) {\n const $ref = `#/definitions/${name}`;\n const schema = context.spec.definitions[name]!;\n\n parseSchema({\n $ref,\n context,\n schema,\n });\n }\n }\n\n parseServers({ context });\n\n for (const path in context.spec.paths) {\n if (path.startsWith('x-')) continue;\n const pathItem = context.spec.paths[path as PathKeys]!;\n\n const finalPathItem = pathItem.$ref\n ? {\n ...context.resolveRef<PathItemObject>(pathItem.$ref),\n ...pathItem,\n }\n : pathItem;\n\n const commonOperation: OperationObject = {\n consumes: context.spec.consumes,\n produces: context.spec.produces,\n responses: {},\n security: context.spec.security,\n };\n const operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'> = {\n context,\n operation: {\n ...commonOperation,\n parameters: parametersArrayToObject({\n context,\n operation: commonOperation,\n parameters: finalPathItem.parameters,\n }),\n },\n path: path as PathKeys,\n securitySchemesMap,\n state,\n };\n\n if (finalPathItem.delete) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.delete,\n parameters: finalPathItem.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.delete,\n parameters,\n },\n });\n }\n\n if (finalPathItem.get) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.get,\n parameters: finalPathItem.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.get,\n parameters,\n },\n });\n }\n\n if (finalPathItem.head) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.head,\n parameters: finalPathItem.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.head,\n parameters,\n },\n });\n }\n\n if (finalPathItem.options) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.options,\n parameters: finalPathItem.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.options,\n parameters,\n },\n });\n }\n\n if (finalPathItem.patch) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.patch,\n parameters: finalPathItem.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.patch,\n parameters,\n },\n });\n }\n\n if (finalPathItem.post) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.post,\n parameters: finalPathItem.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.post,\n parameters,\n },\n });\n }\n\n if (finalPathItem.put) {\n const parameters = mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n operation: finalPathItem.put,\n parameters: finalPathItem.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n });\n parsePathOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.put,\n parameters,\n },\n });\n }\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { OpenApiV3_0_X, PathItemObject, PathsObject } from '../types/spec';\n\n/**\n * Replace source spec with filtered version.\n */\nexport const filterSpec = ({\n logger,\n operations,\n parameters,\n preserveOrder,\n requestBodies,\n responses,\n schemas,\n spec,\n}: {\n logger: Logger;\n operations: Set<string>;\n parameters: Set<string>;\n preserveOrder: boolean;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n spec: OpenApiV3_0_X;\n}) => {\n const eventFilterSpec = logger.timeEvent('filter-spec');\n if (spec.components) {\n if (spec.components.parameters) {\n const filtered: typeof spec.components.parameters = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.parameters)) {\n if (parameters.has(addNamespace('parameter', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of parameters) {\n const { name } = removeNamespace(key);\n const source = spec.components.parameters[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.parameters = filtered;\n }\n\n if (spec.components.requestBodies) {\n const filtered: typeof spec.components.requestBodies = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.requestBodies)) {\n if (requestBodies.has(addNamespace('body', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of requestBodies) {\n const { name } = removeNamespace(key);\n const source = spec.components.requestBodies[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.requestBodies = filtered;\n }\n\n if (spec.components.responses) {\n const filtered: typeof spec.components.responses = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.responses)) {\n if (responses.has(addNamespace('response', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of responses) {\n const { name } = removeNamespace(key);\n const source = spec.components.responses[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.responses = filtered;\n }\n\n if (spec.components.schemas) {\n const filtered: typeof spec.components.schemas = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.schemas)) {\n if (schemas.has(addNamespace('schema', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of schemas) {\n const { name } = removeNamespace(key);\n const source = spec.components.schemas[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.schemas = filtered;\n }\n }\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = addNamespace('operation', createOperationKey({ method, path }));\n if (!operations.has(key)) {\n delete pathItem[method];\n }\n }\n\n // remove paths that have no operations left\n if (!Object.keys(pathItem).length) {\n delete spec.paths[path];\n }\n }\n }\n eventFilterSpec.timeEnd();\n};\n","import type { IRMediaType } from '../../../ir/mediaType';\nimport { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType';\nimport type { MediaTypeObject, ReferenceObject, SchemaObject } from '../types/spec';\n\ninterface Content {\n mediaType: string;\n schema: SchemaObject | ReferenceObject | undefined;\n type: IRMediaType | undefined;\n}\n\nexport const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => {\n const { mediaType, schema } = content;\n\n if (schema && '$ref' in schema) {\n return {\n allOf: [{ ...schema }],\n };\n }\n\n if (!schema) {\n if (isMediaTypeFileLike({ mediaType })) {\n return {\n format: 'binary',\n type: 'string',\n };\n }\n return;\n }\n\n if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) {\n return {\n ...schema,\n format: 'binary',\n };\n }\n\n return schema;\n};\n\nexport const mediaTypeObjects = ({\n content,\n}: {\n content: Record<string, MediaTypeObject> | undefined;\n}): ReadonlyArray<Content> => {\n const objects: Array<Content> = [];\n\n for (const mediaType in content) {\n objects.push({\n mediaType,\n schema: content[mediaType]!.schema,\n type: mediaTypeToIrMediaType({ mediaType }),\n });\n }\n\n return objects;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { addItemsToSchema } from '../../../ir/utils';\nimport type {\n SchemaState,\n SchemaType,\n SchemaWithRequired,\n} from '../../../openApi/shared/types/schema';\nimport {\n convertDiscriminatorValue,\n type DiscriminatorPropertyType,\n discriminatorValues,\n} from '../../../openApi/shared/utils/discriminator';\nimport { isTopLevelComponent, refToName } from '../../../utils/ref';\nimport type { ReferenceObject, SchemaObject } from '../types/spec';\n\nexport const getSchemaType = ({\n schema,\n}: {\n schema: SchemaObject;\n}): SchemaType<SchemaObject> | undefined => {\n if (schema.type) {\n return schema.type;\n }\n\n // infer object based on the presence of properties\n if (schema.properties) {\n return 'object';\n }\n\n return;\n};\n\n/**\n * Finds the type of a discriminator property by looking it up in the provided schemas.\n * Searches through properties and allOf chains to find the property definition.\n */\nconst findDiscriminatorPropertyType = ({\n context,\n propertyName,\n schemas,\n}: {\n context: Context;\n propertyName: string;\n schemas: ReadonlyArray<SchemaObject | ReferenceObject>;\n}): DiscriminatorPropertyType => {\n for (const schema of schemas) {\n const resolved = '$ref' in schema ? context.resolveRef<SchemaObject>(schema.$ref) : schema;\n\n // Check direct properties\n const property = resolved.properties?.[propertyName];\n if (property) {\n const resolvedProperty =\n '$ref' in property ? context.resolveRef<SchemaObject>(property.$ref) : property;\n if (\n resolvedProperty.type === 'boolean' ||\n resolvedProperty.type === 'integer' ||\n resolvedProperty.type === 'number'\n ) {\n return resolvedProperty.type;\n }\n }\n\n // Check allOf chains\n if (resolved.allOf) {\n const foundType = findDiscriminatorPropertyType({\n context,\n propertyName,\n schemas: resolved.allOf,\n });\n if (foundType !== 'string') {\n return foundType;\n }\n }\n }\n\n return 'string';\n};\n\n/**\n * Recursively finds discriminators in a schema, including nested allOf compositions.\n * This is needed when a schema extends another schema via allOf, and that parent\n * schema is itself an allOf composition with discriminators in inline schemas.\n */\nconst findDiscriminatorsInSchema = ({\n context,\n discriminators = [],\n schema,\n}: {\n context: Context;\n discriminators?: Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n }>;\n schema: SchemaObject;\n}): Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n}> => {\n // Check if this schema has a discriminator\n if (schema.discriminator) {\n discriminators.push({\n discriminator: schema.discriminator,\n oneOf: schema.oneOf,\n });\n }\n\n // If this schema is an allOf composition, recursively search in its components\n if (schema.allOf) {\n for (const compositionSchema of schema.allOf) {\n let resolvedSchema: SchemaObject;\n if ('$ref' in compositionSchema) {\n resolvedSchema = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n } else {\n resolvedSchema = compositionSchema;\n }\n\n findDiscriminatorsInSchema({\n context,\n discriminators,\n schema: resolvedSchema,\n });\n }\n }\n\n return discriminators;\n};\n\n/**\n * Gets the discriminator value for a schema.\n * Returns only the schema's own discriminator value, not child values.\n */\nconst getAllDiscriminatorValues = ({\n discriminator,\n schemaRef,\n}: {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n schemaRef: string;\n}): Array<string> => {\n const values: Array<string> = [];\n\n // Check each entry in the discriminator mapping\n for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) {\n if (mappedSchemaRef === schemaRef) {\n // This is the current schema's own value\n values.push(value);\n }\n }\n\n return values;\n};\n\nconst parseSchemaJsDoc = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.deprecated !== undefined) {\n irSchema.deprecated = schema.deprecated;\n }\n\n if (schema.example) {\n irSchema.example = schema.example;\n }\n\n if (schema.description) {\n irSchema.description = schema.description;\n }\n\n if (schema.title) {\n irSchema.title = schema.title;\n }\n};\n\nconst parseSchemaMeta = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.default !== undefined) {\n irSchema.default = schema.default;\n }\n\n if (schema.exclusiveMaximum) {\n if (schema.maximum !== undefined) {\n irSchema.exclusiveMaximum = schema.maximum;\n }\n } else if (schema.maximum !== undefined) {\n irSchema.maximum = schema.maximum;\n }\n\n if (schema.exclusiveMinimum) {\n if (schema.minimum !== undefined) {\n irSchema.exclusiveMinimum = schema.minimum;\n }\n } else if (schema.minimum !== undefined) {\n irSchema.minimum = schema.minimum;\n }\n\n if (schema.format) {\n irSchema.format = schema.format;\n }\n\n if (schema.maxItems !== undefined) {\n irSchema.maxItems = schema.maxItems;\n }\n\n if (schema.maxLength !== undefined) {\n irSchema.maxLength = schema.maxLength;\n }\n\n if (schema.minItems !== undefined) {\n irSchema.minItems = schema.minItems;\n }\n\n if (schema.minLength !== undefined) {\n irSchema.minLength = schema.minLength;\n }\n\n if (schema.pattern) {\n irSchema.pattern = schema.pattern;\n }\n\n if (schema.readOnly) {\n irSchema.accessScope = 'read';\n } else if (schema.writeOnly) {\n irSchema.accessScope = 'write';\n }\n};\n\nconst parseArray = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (schema.maxItems && schema.maxItems === schema.minItems) {\n irSchema.type = 'tuple';\n } else {\n irSchema.type = 'array';\n }\n\n let schemaItems: Array<IR.SchemaObject> = [];\n\n if (schema.items) {\n const irItemsSchema = schemaToIrSchema({\n context,\n schema: schema.items,\n state,\n });\n\n if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {\n schemaItems = Array(schema.maxItems).fill(irItemsSchema);\n } else {\n if ('$ref' in schema.items) {\n schemaItems.push(irItemsSchema);\n } else {\n const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf;\n if (ofArray && ofArray.length > 1 && !schema.items.nullable) {\n // bring composition up to avoid incorrectly nested arrays\n irSchema = {\n ...irSchema,\n ...irItemsSchema,\n };\n } else {\n schemaItems.push(irItemsSchema);\n }\n }\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseBoolean = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'boolean';\n\n return irSchema;\n};\n\nconst parseNumber = ({\n irSchema = {},\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = schema.type;\n\n return irSchema;\n};\n\nconst parseObject = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'object';\n\n const schemaProperties: Record<string, IR.SchemaObject> = {};\n\n for (const name in schema.properties) {\n const property = schema.properties[name]!;\n if (typeof property === 'boolean') {\n // TODO: parser - handle boolean properties\n } else {\n schemaProperties[name] = schemaToIrSchema({\n context,\n schema: property,\n state,\n });\n }\n }\n\n if (Object.keys(schemaProperties).length) {\n irSchema.properties = schemaProperties;\n }\n\n if (schema.additionalProperties === undefined) {\n if (!irSchema.properties) {\n irSchema.additionalProperties = {\n type: 'unknown',\n };\n }\n } else if (typeof schema.additionalProperties === 'boolean') {\n // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf\n // This would override inherited properties from other schemas in the composition\n const isEmptyObjectInAllOf =\n state.inAllOf &&\n schema.additionalProperties === false &&\n (!schema.properties || !Object.keys(schema.properties).length);\n\n if (!isEmptyObjectInAllOf) {\n irSchema.additionalProperties = {\n type: schema.additionalProperties ? 'unknown' : 'never',\n };\n }\n } else {\n const irAdditionalPropertiesSchema = schemaToIrSchema({\n context,\n schema: schema.additionalProperties,\n state,\n });\n irSchema.additionalProperties = irAdditionalPropertiesSchema;\n }\n\n if (schema.required) {\n irSchema.required = schema.required;\n }\n\n return irSchema;\n};\n\nconst parseString = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'string';\n\n return irSchema;\n};\n\nexport const parseExtensions = ({ source, target }: { source: object; target: object }) => {\n for (const key in source) {\n if (key.startsWith('x-')) {\n (target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];\n }\n }\n};\n\nconst initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n\n parseSchemaJsDoc({\n irSchema,\n schema,\n });\n\n parseExtensions({\n source: schema,\n target: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseAllOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'allOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.allOf;\n\n // Collect discriminator information to add after all compositions are processed\n type DiscriminatorInfo = {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n isExplicitMapping: boolean;\n isRequired: boolean;\n values: ReadonlyArray<string>;\n };\n const discriminatorsToAdd: Array<DiscriminatorInfo> = [];\n\n for (const compositionSchema of compositionSchemas) {\n const originalInAllOf = state.inAllOf;\n // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components\n if (!('$ref' in compositionSchema)) {\n state.inAllOf = true;\n }\n const irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n state.inAllOf = originalInAllOf;\n if (state.inAllOf === undefined) {\n delete state.inAllOf;\n }\n\n if (schema.required) {\n if (irCompositionSchema.required) {\n irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];\n } else {\n irCompositionSchema.required = schema.required;\n }\n }\n\n schemaItems.push(irCompositionSchema);\n\n if ('$ref' in compositionSchema) {\n const ref = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n // `$ref` should be passed from the root `parseSchema()` call\n if (state.$ref) {\n // Find all discriminators in the referenced schema, including nested allOf compositions\n const discriminators = findDiscriminatorsInSchema({\n context,\n schema: ref,\n });\n\n for (const { discriminator, oneOf } of discriminators) {\n const values = discriminatorValues(\n state.$ref,\n discriminator.mapping,\n // If the ref has oneOf, we only use the schema name as the value\n // only if current schema is part of the oneOf. Else it is extending\n // the ref schema\n oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined,\n );\n\n if (values.length === 0) {\n continue;\n }\n\n // True when state.$ref appears directly in the mapping; false when the\n // value fell back to the schema name because no mapping entry matched.\n const isExplicitMapping =\n discriminator.mapping !== undefined &&\n Object.values(discriminator.mapping).includes(state.$ref);\n\n // An explicit mapping always beats a same-property fallback collected\n // earlier (e.g. from a grandparent discriminator that doesn't list this\n // schema). Replace it; otherwise skip the duplicate.\n const existingIndex = discriminatorsToAdd.findIndex(\n (d) => d.discriminator.propertyName === discriminator.propertyName,\n );\n if (existingIndex !== -1) {\n if (isExplicitMapping && !discriminatorsToAdd[existingIndex]!.isExplicitMapping) {\n discriminatorsToAdd.splice(existingIndex, 1);\n } else {\n continue;\n }\n }\n\n const isRequired = discriminators.some(\n (d) =>\n d.discriminator.propertyName === discriminator.propertyName &&\n (ref.required?.includes(d.discriminator.propertyName) ||\n (ref.allOf &&\n ref.allOf.some((item) => {\n const resolvedItem =\n '$ref' in item ? context.resolveRef<SchemaObject>(item.$ref) : item;\n return resolvedItem.required?.includes(d.discriminator.propertyName);\n }))),\n );\n\n discriminatorsToAdd.push({\n discriminator,\n isExplicitMapping,\n isRequired,\n values,\n });\n }\n }\n }\n }\n\n // Now add discriminators after all compositions have been processed\n for (const { discriminator, isRequired, values } of discriminatorsToAdd) {\n // Get all discriminator values including children for union types\n const allValues = getAllDiscriminatorValues({\n discriminator,\n schemaRef: state.$ref!,\n });\n\n // Use allValues if we found children, otherwise use the original values\n const finalValues = allValues.length > 0 ? allValues : values;\n\n // Detect the actual type of the discriminator property\n const propertyType = findDiscriminatorPropertyType({\n context,\n propertyName: discriminator.propertyName,\n schemas: compositionSchemas,\n });\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = finalValues.map((value) =>\n convertDiscriminatorValue(value, propertyType),\n );\n\n const discriminatorProperty: IR.SchemaObject =\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!;\n\n // Check if any $ref schemas in schemaItems have this discriminator property\n // If yes, mark them to omit it to avoid conflicts\n for (const item of schemaItems) {\n if (item.$ref || item.symbolRef) {\n // Check if the referenced schema has this property\n const hasProperty = (() => {\n if (!item.$ref) return false;\n try {\n const refSchema = context.resolveRef<SchemaObject>(item.$ref);\n // Check if the discriminator property exists in the ref schema\n return (\n refSchema.properties?.[discriminator.propertyName] !== undefined ||\n (refSchema.allOf &&\n refSchema.allOf.some((allOfItem) => {\n const resolved =\n '$ref' in allOfItem\n ? context.resolveRef<SchemaObject>(allOfItem.$ref)\n : allOfItem;\n return resolved.properties?.[discriminator.propertyName] !== undefined;\n }))\n );\n } catch {\n return false;\n }\n })();\n\n if (hasProperty) {\n // Mark this ref to omit the discriminator property\n if (!item.omit) {\n item.omit = [discriminator.propertyName];\n } else if (!item.omit.includes(discriminator.propertyName)) {\n item.omit = [...item.omit, discriminator.propertyName];\n }\n }\n }\n }\n\n // Find the inline schema (non-$ref) to merge the discriminator property into\n // The inline schema should be the last non-$ref item in schemaItems\n let inlineSchema: IR.SchemaObject | undefined;\n for (let i = schemaItems.length - 1; i >= 0; i--) {\n const item = schemaItems[i]!;\n // Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema\n if (item.type === 'object' || item.properties) {\n inlineSchema = item;\n break;\n }\n }\n\n // If we found an inline schema, add the discriminator property to it\n if (inlineSchema) {\n if (!inlineSchema.properties) {\n inlineSchema.properties = {};\n }\n inlineSchema.properties[discriminator.propertyName] = discriminatorProperty;\n\n if (isRequired) {\n if (!inlineSchema.required) {\n inlineSchema.required = [];\n }\n if (!inlineSchema.required.includes(discriminator.propertyName)) {\n inlineSchema.required = [...inlineSchema.required, discriminator.propertyName];\n }\n }\n } else {\n // Fallback: create a separate discriminator schema if no inline schema found\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [discriminator.propertyName]: discriminatorProperty,\n },\n type: 'object',\n };\n\n if (isRequired) {\n irDiscriminatorSchema.required = [discriminator.propertyName];\n }\n schemaItems.push(irDiscriminatorSchema);\n }\n }\n\n if (schemaType === 'object') {\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n for (const requiredProperty of irObjectSchema.required ?? []) {\n if (!irObjectSchema.properties[requiredProperty]) {\n for (const compositionSchema of compositionSchemas) {\n // TODO: parser - this could be probably resolved more accurately\n const finalCompositionSchema =\n '$ref' in compositionSchema\n ? context.resolveRef<SchemaObject>(compositionSchema.$ref)\n : compositionSchema;\n\n if (getSchemaType({ schema: finalCompositionSchema }) === 'object') {\n const irCompositionSchema = parseOneType({\n context,\n schema: {\n ...finalCompositionSchema,\n type: 'object',\n },\n state,\n });\n\n if (irCompositionSchema.properties?.[requiredProperty]) {\n irObjectSchema.properties[requiredProperty] =\n irCompositionSchema.properties[requiredProperty];\n break;\n }\n }\n }\n }\n }\n schemaItems.push(irObjectSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n logicalOperator: 'and',\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schema.nullable) {\n // nest composition to avoid producing an intersection with null\n const nestedItems: Array<IR.SchemaObject> = [\n {\n type: 'null',\n },\n ];\n\n if (schemaItems.length) {\n nestedItems.unshift(irSchema);\n }\n\n irSchema = {\n items: nestedItems,\n logicalOperator: 'or',\n };\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original deprecated\n if (nestedItems[0]!.deprecated) {\n irSchema.deprecated = nestedItems[0]!.deprecated;\n }\n\n // TODO: parser - this is a hack to bring back up meta fields\n // without it, some schemas were missing original description\n if (nestedItems[0]!.description) {\n irSchema.description = nestedItems[0]!.description;\n }\n }\n\n return irSchema;\n};\n\nconst parseAnyOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'anyOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.anyOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n schemaItems.push(irCompositionSchema);\n }\n\n if (schema.nullable) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaType === 'object') {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseEnum = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'enum'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n irSchema.type = 'enum';\n\n const schemaItems: Array<IR.SchemaObject> = [];\n\n for (const [index, enumValue] of schema.enum.entries()) {\n const typeOfEnumValue = typeof enumValue;\n let enumType: SchemaType<SchemaObject> | 'null' | undefined;\n\n if (\n typeOfEnumValue === 'string' ||\n typeOfEnumValue === 'number' ||\n typeOfEnumValue === 'boolean'\n ) {\n enumType = typeOfEnumValue;\n } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {\n enumType = 'array';\n } else if (enumValue === null) {\n // nullable must be true\n if (schema.nullable) {\n enumType = 'null';\n }\n } else {\n console.warn(\n '๐Ÿšจ',\n `unhandled \"${typeOfEnumValue}\" typeof value \"${enumValue}\" for enum`,\n schema.enum,\n );\n }\n\n if (!enumType) {\n continue;\n }\n\n const irTypeSchema = parseOneType({\n context,\n schema: {\n description: schema['x-enum-descriptions']?.[index],\n title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],\n // cast enum to string temporarily\n type: enumType === 'null' ? 'string' : enumType,\n },\n state,\n });\n\n irTypeSchema.const = enumValue;\n\n // cast enum back\n if (enumType === 'null') {\n irTypeSchema.type = enumType;\n }\n\n if (irTypeSchema.type === 'array') {\n irTypeSchema.type = 'tuple';\n }\n\n schemaItems.push(irTypeSchema);\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseOneOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'oneOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n let schemaItems: Array<IR.SchemaObject> = [];\n const schemaType = getSchemaType({ schema });\n\n const compositionSchemas = schema.oneOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n required: [schema.discriminator.propertyName],\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n // since we know oneOf will be using \"or\" logical operator, if the parsed\n // composition schema also has an \"or\" operator, we can bring it up\n // to avoid unnecessary brackets\n if (\n irCompositionSchema.logicalOperator === 'or' &&\n irCompositionSchema.type !== 'array' &&\n irCompositionSchema.items\n ) {\n schemaItems = schemaItems.concat(irCompositionSchema.items);\n } else {\n schemaItems.push(irCompositionSchema);\n }\n }\n\n if (schema.nullable) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaType === 'object') {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseRef = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: ReferenceObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/components/schemas/Foo/properties/bar)\n // to avoid generating orphaned named types or referencing unregistered symbols\n const isComponentsRef = isTopLevelComponent(schema.$ref);\n if (!isComponentsRef) {\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n const irSchema = schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n return irSchema;\n }\n // Fallback to preserving the ref if circular\n }\n\n const irSchema: IR.SchemaObject = {};\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n irSchema.$ref = decodeURI(schema.$ref);\n\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n }\n\n return irSchema;\n};\n\nconst parseNullableType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n const typeIrSchema: IR.SchemaObject = {};\n\n parseSchemaMeta({ irSchema: typeIrSchema, schema });\n\n if (typeIrSchema.default === null) {\n // clear to avoid duplicate default inside the non-null schema.\n // this would produce incorrect validator output\n delete typeIrSchema.default;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [\n parseOneType({\n context,\n irSchema: typeIrSchema,\n schema,\n state,\n }),\n {\n type: 'null',\n },\n ];\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseType = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n\n const type = getSchemaType({ schema });\n\n if (!type) {\n return irSchema;\n }\n\n if (!schema.nullable) {\n return parseOneType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n }\n\n return parseNullableType({\n context,\n irSchema,\n schema: {\n ...schema,\n type,\n },\n state,\n });\n};\n\nconst parseOneType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n }\n\n switch (schema.type) {\n case 'array':\n return parseArray({\n context,\n irSchema,\n schema,\n state,\n });\n case 'boolean':\n return parseBoolean({\n context,\n irSchema,\n schema,\n state,\n });\n case 'integer':\n case 'number':\n return parseNumber({\n context,\n irSchema,\n schema,\n state,\n });\n case 'object':\n return parseObject({\n context,\n irSchema,\n schema,\n state,\n });\n case 'string':\n return parseString({\n context,\n irSchema,\n schema,\n state,\n });\n default:\n // gracefully handle invalid type\n return parseUnknown({\n context,\n irSchema,\n schema,\n });\n }\n};\n\nconst parseUnknown = ({\n irSchema,\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n irSchema.type = 'unknown';\n\n parseSchemaMeta({ irSchema, schema });\n\n return irSchema;\n};\n\nexport const schemaToIrSchema = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaObject | ReferenceObject;\n state: SchemaState | undefined;\n}): IR.SchemaObject => {\n if (!state) {\n state = {\n circularReferenceTracker: new Set(),\n };\n }\n\n if (state.$ref) {\n state.circularReferenceTracker.add(state.$ref);\n }\n\n if ('$ref' in schema) {\n return parseRef({\n context,\n schema,\n state,\n });\n }\n\n if (schema.enum) {\n return parseEnum({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'enum'>,\n state,\n });\n }\n\n if (schema.allOf) {\n return parseAllOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'allOf'>,\n state,\n });\n }\n\n if (schema.anyOf) {\n return parseAnyOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'anyOf'>,\n state,\n });\n }\n\n if (schema.oneOf) {\n return parseOneOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'oneOf'>,\n state,\n });\n }\n\n // infer object based on the presence of properties\n if (schema.type || schema.properties) {\n return parseType({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n return parseUnknown({ context, schema });\n};\n\nexport const parseSchema = ({\n $ref,\n context,\n schema,\n}: {\n $ref: string;\n context: Context;\n schema: SchemaObject | ReferenceObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.schemas) {\n context.ir.components.schemas = {};\n }\n\n context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({\n context,\n schema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { getPaginationKeywordsRegExp } from '../../../ir/pagination';\nimport type { SchemaType } from '../../../openApi/shared/types/schema';\nimport type { ParameterObject, ReferenceObject, RequestBodyObject } from '../types/spec';\nimport type { SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { getSchemaType } from './schema';\n\nconst isPaginationType = (schemaType: SchemaType<SchemaObject> | undefined): boolean =>\n schemaType === 'boolean' ||\n schemaType === 'integer' ||\n schemaType === 'number' ||\n schemaType === 'string';\n\n// We handle only simple values for now, up to 1 nested field\nexport const paginationField = ({\n context,\n name,\n schema,\n}: {\n context: Context;\n name: string;\n schema: SchemaObject | ReferenceObject;\n}): boolean | string => {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n if (paginationRegExp.test(name)) {\n return true;\n }\n\n if ('$ref' in schema) {\n const ref = context.resolveRef<ParameterObject | RequestBodyObject | SchemaObject>(schema.$ref);\n\n if ('content' in ref || 'in' in ref) {\n let refSchema: SchemaObject | ReferenceObject | undefined;\n\n if ('in' in ref) {\n refSchema = ref.schema;\n }\n\n if (!refSchema) {\n // parameter or body\n const contents = mediaTypeObjects({ content: ref.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content?.schema) {\n refSchema = content.schema;\n }\n }\n\n if (!refSchema) {\n return false;\n }\n\n return paginationField({\n context,\n name,\n schema: refSchema,\n });\n }\n\n return paginationField({\n context,\n name,\n schema: ref,\n });\n }\n\n for (const name in schema.properties) {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n\n if (paginationRegExp.test(name)) {\n const property = schema.properties[name]!;\n\n if (typeof property !== 'boolean' && !('$ref' in property)) {\n const schemaType = getSchemaType({ schema: property });\n // TODO: resolve deeper references\n\n if (isPaginationType(schemaType)) {\n return name;\n }\n }\n }\n }\n\n for (const allOf of schema.allOf ?? []) {\n const pagination = paginationField({\n context,\n name,\n schema: allOf,\n });\n if (pagination) {\n return pagination;\n }\n }\n\n return false;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type { State } from '../../../openApi/shared/types/state';\nimport { operationToId } from '../../../openApi/shared/utils/operation';\nimport type {\n OperationObject,\n PathItemObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { contentToSchema, mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\ninterface Operation\n extends Omit<OperationObject, 'parameters'>, Pick<IR.OperationObject, 'parameters'> {}\n\nconst parseOperationJsDoc = ({\n irOperation,\n operation,\n}: {\n irOperation: IR.OperationObject;\n operation: Operation;\n}) => {\n if (operation.deprecated !== undefined) {\n irOperation.deprecated = operation.deprecated;\n }\n\n if (operation.description) {\n irOperation.description = operation.description;\n }\n\n if (operation.summary) {\n irOperation.summary = operation.summary;\n }\n\n if (operation.tags?.length) {\n irOperation.tags = operation.tags;\n }\n};\n\nconst initIrOperation = ({\n context,\n method,\n operation,\n path,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n state: State;\n}): IR.OperationObject => {\n const irOperation: IR.OperationObject = {\n id: operationToId({\n context,\n id: operation.operationId,\n method,\n path,\n state,\n }),\n method,\n path,\n };\n\n if (operation.operationId) {\n irOperation.operationId = operation.operationId;\n }\n\n parseOperationJsDoc({\n irOperation,\n operation,\n });\n\n parseExtensions({\n source: operation,\n target: irOperation,\n });\n\n return irOperation;\n};\n\nconst operationToIrOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}): IR.OperationObject => {\n const irOperation = initIrOperation({\n context,\n method,\n operation,\n path,\n state,\n });\n\n if (operation.parameters) {\n irOperation.parameters = operation.parameters;\n }\n\n if (operation.requestBody) {\n const requestBody =\n '$ref' in operation.requestBody\n ? context.resolveRef<RequestBodyObject>(operation.requestBody.$ref)\n : operation.requestBody;\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n const pagination = paginationField({\n context,\n name: '',\n schema:\n content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n });\n\n irOperation.body = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema:\n '$ref' in operation.requestBody\n ? {\n allOf: [{ ...operation.requestBody }],\n description: requestBody.description,\n }\n : content.schema && '$ref' in content.schema\n ? {\n allOf: [{ ...content.schema }],\n description: requestBody.description,\n }\n : {\n description: requestBody.description,\n ...content.schema,\n },\n state: undefined,\n }),\n };\n\n if (pagination) {\n irOperation.body.pagination = pagination;\n }\n\n if (requestBody.required) {\n irOperation.body.required = requestBody.required;\n }\n\n if (content.type) {\n irOperation.body.type = content.type;\n }\n }\n }\n\n for (const name in operation.responses) {\n if (name.startsWith('x-')) continue;\n\n if (!irOperation.responses) {\n irOperation.responses = {};\n }\n\n const response = operation.responses[name]! as ResponseObject | ReferenceObject;\n const responseObject =\n '$ref' in response ? context.resolveRef<ResponseObject>(response.$ref) : response;\n const contents = mediaTypeObjects({ content: responseObject.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n irOperation.responses[name] = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: responseObject.description,\n ...contentToSchema({ content }),\n },\n state: undefined,\n }),\n };\n } else {\n irOperation.responses[name] = {\n schema: {\n description: responseObject.description,\n // TODO: parser - cover all statues with empty response bodies\n // 1xx, 204, 205, 304\n type: name === '204' ? 'void' : 'unknown',\n },\n };\n }\n }\n\n if (operation.security) {\n const securitySchemeObjects: Map<string, IR.SecurityObject> = new Map();\n\n for (const securityRequirementObject of operation.security) {\n for (const name in securityRequirementObject) {\n const securitySchemeObject = securitySchemesMap.get(name);\n\n if (!securitySchemeObject) {\n continue;\n }\n\n securitySchemeObjects.set(name, securitySchemeObject);\n }\n }\n\n if (securitySchemeObjects.size) {\n irOperation.security = Array.from(securitySchemeObjects.values());\n }\n }\n\n // TODO: parser - handle servers\n // qux: operation.servers\n\n return irOperation;\n};\n\nexport const parsePathOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: {\n context: Context;\n method: Extract<\n keyof PathItemObject,\n 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace'\n >;\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.paths) {\n context.ir.paths = {};\n }\n\n if (!context.ir.paths[path]) {\n context.ir.paths[path] = {};\n }\n\n if (operation.servers) {\n context.ir.servers = [...(context.ir.servers ?? []), ...operation.servers];\n }\n\n context.ir.paths[path][method] = operationToIrOperation({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { ParameterObject, ReferenceObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\n/**\n * Returns default parameter `allowReserved` based on value of `in`.\n */\nconst defaultAllowReserved = (_in: ParameterObject['in']): boolean | undefined => {\n switch (_in) {\n // this keyword only applies to parameters with an `in` value of `query`\n case 'query':\n return false;\n default:\n return;\n }\n};\n\n/**\n * Returns default parameter `explode` based on value of `style`.\n */\nconst defaultExplode = (style: Required<ParameterObject>['style']): boolean => {\n switch (style) {\n // default value for `deepObject` is `false`, but that behavior is undefined\n // so we use `true` to make this work with the `client-fetch` package\n case 'deepObject':\n case 'form':\n return true;\n default:\n return false;\n }\n};\n\n/**\n * Returns default parameter `style` based on value of `in`.\n */\nconst defaultStyle = (_in: ParameterObject['in']): Required<IR.ParameterObject>['style'] => {\n switch (_in) {\n case 'header':\n case 'path':\n return 'simple';\n case 'cookie':\n case 'query':\n return 'form';\n }\n};\n\nexport const parametersArrayToObject = ({\n context,\n parameters,\n}: {\n context: Context;\n parameters?: ReadonlyArray<ParameterObject | ReferenceObject>;\n}): IR.ParametersObject | undefined => {\n if (!parameters || !Object.keys(parameters).length) {\n return;\n }\n\n const parametersObject: IR.ParametersObject = {};\n\n for (const parameterOrReference of parameters) {\n const parameter =\n '$ref' in parameterOrReference\n ? context.dereference<ParameterObject>(parameterOrReference)\n : parameterOrReference;\n\n if (!parametersObject[parameter.in]) {\n parametersObject[parameter.in] = {};\n }\n\n // lowercase keys for case insensitive access\n parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({\n $ref: `#/todo/real/path/to/parameter/${parameter.name}`,\n context,\n parameter,\n });\n }\n\n return parametersObject;\n};\n\nconst parameterToIrParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}): IR.ParameterObject => {\n // TODO: parser - fix\n let schema = parameter.schema;\n\n if (!schema) {\n const contents = mediaTypeObjects({ content: parameter.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content) {\n schema = content.schema;\n }\n }\n\n const finalSchema: SchemaObject =\n schema && '$ref' in schema\n ? {\n allOf: [{ ...schema }],\n deprecated: parameter.deprecated,\n description: parameter.description,\n }\n : {\n deprecated: parameter.deprecated,\n description: parameter.description,\n ...schema,\n };\n\n const pagination = paginationField({\n context,\n name: parameter.name,\n schema: finalSchema,\n });\n\n const style = parameter.style || defaultStyle(parameter.in);\n const explode = parameter.explode !== undefined ? parameter.explode : defaultExplode(style);\n const allowReserved =\n parameter.allowReserved !== undefined\n ? parameter.allowReserved\n : defaultAllowReserved(parameter.in);\n\n const irParameter: IR.ParameterObject = {\n allowReserved,\n explode,\n location: parameter.in,\n name: parameter.name,\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n style,\n };\n\n if (parameter.deprecated) {\n irParameter.deprecated = parameter.deprecated;\n }\n\n if (parameter.description) {\n irParameter.description = parameter.description;\n }\n\n if (pagination) {\n irParameter.pagination = pagination;\n }\n\n if (parameter.required) {\n irParameter.required = parameter.required;\n }\n\n parseExtensions({\n source: parameter,\n target: irParameter,\n });\n\n return irParameter;\n};\n\nexport const parseParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.parameters) {\n context.ir.components.parameters = {};\n }\n\n context.ir.components.parameters[refToName($ref)] = parameterToIrParameter({\n $ref,\n context,\n parameter,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { RequestBodyObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { schemaToIrSchema } from './schema';\n\nconst requestBodyToIrRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}): IR.RequestBodyObject => {\n // TODO: parser - fix\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n const schema = content ? content.schema : undefined;\n\n const finalSchema: SchemaObject = {\n description: requestBody.description,\n ...schema,\n };\n\n const irRequestBody: IR.RequestBodyObject = {\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n };\n\n if (requestBody.description) {\n irRequestBody.description = requestBody.description;\n }\n\n if (requestBody.required) {\n irRequestBody.required = requestBody.required;\n }\n\n return irRequestBody;\n};\n\nexport const parseRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.requestBodies) {\n context.ir.components.requestBodies = {};\n }\n\n context.ir.components.requestBodies[refToName($ref)] = requestBodyToIrRequestBody({\n $ref,\n context,\n requestBody,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { parseUrl } from '../../../utils/url';\n\nexport function parseServers({ context }: { context: Context }): void {\n if (context.spec.servers) {\n context.ir.servers = context.spec.servers;\n return;\n }\n\n for (const input of context.config.input) {\n if (typeof input.path === 'string') {\n const url = parseUrl(input.path);\n context.ir.servers = [\n {\n url: `${url.protocol ? `${url.protocol}://` : ''}${url.host}${url.port ? `:${url.port}` : ''}`,\n },\n ];\n }\n }\n\n if (!context.ir.servers) {\n context.ir.servers = [\n {\n url: '/',\n },\n ];\n }\n}\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type { OpenApiV3_0_X, PathItemObject, PathsObject } from '../types/spec';\n\nexport const validateOpenApiSpec = (spec: OpenApiV3_0_X, logger: Logger): ValidatorResult => {\n const eventValidate = logger.timeEvent('validate');\n const issues: Array<ValidatorIssue> = [];\n const operationIds = new Map();\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const operationKey = createOperationKey({ method, path });\n\n if (operation.operationId) {\n if (!operationIds.has(operation.operationId)) {\n operationIds.set(operation.operationId, operationKey);\n } else {\n issues.push({\n code: 'duplicate_key',\n context: {\n key: 'operationId',\n value: operation.operationId,\n },\n message: 'Duplicate `operationId` found. Each `operationId` must be unique.',\n path: ['paths', path, method, 'operationId'],\n severity: 'error',\n });\n }\n }\n }\n }\n }\n\n if (spec.servers) {\n if (typeof spec.servers !== 'object' || !Array.isArray(spec.servers)) {\n issues.push({\n code: 'invalid_type',\n message: '`servers` must be an array.',\n path: [],\n severity: 'error',\n });\n }\n\n for (let index = 0; index < spec.servers.length; index++) {\n const server = spec.servers[index];\n if (!server || typeof server !== 'object') {\n issues.push({\n code: 'invalid_type',\n context: {\n actual: typeof server,\n expected: 'object',\n },\n message: 'Each entry in `servers` must be an object.',\n path: ['servers', index],\n severity: 'error',\n });\n } else {\n if (!server.url) {\n issues.push({\n code: 'missing_required_field',\n context: {\n field: 'url',\n },\n message: 'Missing required field `url` in server object.',\n path: ['servers', index],\n severity: 'error',\n });\n }\n }\n }\n }\n\n eventValidate.timeEnd();\n return {\n issues,\n valid: !issues.some((issue) => issue.severity === 'error'),\n };\n};\n","import type { Context } from '../../../ir/context';\nimport { buildResourceMetadata } from '../../../openApi/shared/graph/meta';\nimport { transformOpenApiSpec } from '../../../openApi/shared/transforms';\nimport type { State } from '../../../openApi/shared/types/state';\nimport {\n createFilteredDependencies,\n createFilters,\n hasFilters,\n} from '../../../openApi/shared/utils/filter';\nimport { buildGraph } from '../../../openApi/shared/utils/graph';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport { handleValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type {\n OpenApiV3_0_X,\n ParameterObject,\n PathItemObject,\n PathsObject,\n RequestBodyObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { filterSpec } from './filter';\nimport { parsePathOperation } from './operation';\nimport { parametersArrayToObject, parseParameter } from './parameter';\nimport { parseRequestBody } from './requestBody';\nimport { parseSchema } from './schema';\nimport { parseServers } from './server';\nimport { validateOpenApiSpec } from './validate';\n\nexport const parseV3_0_X = (context: Context<OpenApiV3_0_X>) => {\n if (context.config.parser.validate_EXPERIMENTAL) {\n const result = validateOpenApiSpec(context.spec, context.logger);\n handleValidatorResult({ context, result });\n }\n\n const shouldFilterSpec = hasFilters(context.config.parser.filters);\n if (shouldFilterSpec) {\n const filters = createFilters(context.config.parser.filters, context.spec, context.logger);\n const { graph } = buildGraph(context.spec, context.logger);\n const { resourceMetadata } = buildResourceMetadata(graph, context.logger);\n const sets = createFilteredDependencies({\n filters,\n logger: context.logger,\n resourceMetadata,\n });\n filterSpec({\n ...sets,\n logger: context.logger,\n preserveOrder: filters.preserveOrder,\n spec: context.spec,\n });\n }\n\n transformOpenApiSpec({ context });\n\n const state: State = {\n ids: new Map(),\n };\n const securitySchemesMap = new Map<string, SecuritySchemeObject>();\n\n // TODO: parser - handle more component types, old parser handles only parameters and schemas\n if (context.spec.components) {\n for (const name in context.spec.components.securitySchemes) {\n const securityOrReference = context.spec.components.securitySchemes[name]!;\n const securitySchemeObject =\n '$ref' in securityOrReference\n ? context.resolveRef<SecuritySchemeObject>(securityOrReference.$ref)\n : securityOrReference;\n securitySchemesMap.set(name, securitySchemeObject);\n }\n\n for (const name in context.spec.components.parameters) {\n const $ref = `#/components/parameters/${name}`;\n const parameterOrReference = context.spec.components.parameters[name]!;\n const parameter =\n '$ref' in parameterOrReference\n ? context.resolveRef<ParameterObject>(parameterOrReference.$ref)\n : parameterOrReference;\n\n parseParameter({\n $ref,\n context,\n parameter,\n });\n }\n\n for (const name in context.spec.components.requestBodies) {\n const $ref = `#/components/requestBodies/${name}`;\n const requestBodyOrReference = context.spec.components.requestBodies[name]!;\n const requestBody =\n '$ref' in requestBodyOrReference\n ? context.resolveRef<RequestBodyObject>(requestBodyOrReference.$ref)\n : requestBodyOrReference;\n\n parseRequestBody({\n $ref,\n context,\n requestBody,\n });\n }\n\n for (const name in context.spec.components.schemas) {\n const $ref = `#/components/schemas/${name}`;\n const schema = context.spec.components.schemas[name]!;\n\n parseSchema({\n $ref,\n context,\n schema,\n });\n }\n }\n\n parseServers({ context });\n\n for (const path in context.spec.paths) {\n if (path.startsWith('x-')) continue;\n const pathItem = context.spec.paths[path as keyof PathsObject]! as PathItemObject;\n\n const finalPathItem = pathItem.$ref\n ? {\n ...context.resolveRef<PathItemObject>(pathItem.$ref),\n ...pathItem,\n }\n : pathItem;\n\n const operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method' | 'operation'> & {\n operation: Omit<Parameters<typeof parsePathOperation>[0]['operation'], 'responses'>;\n } = {\n context,\n operation: {\n description: finalPathItem.description,\n parameters: parametersArrayToObject({\n context,\n parameters: finalPathItem.parameters,\n }),\n security: context.spec.security,\n servers: finalPathItem.servers,\n summary: finalPathItem.summary,\n },\n path: path as `/${string}`,\n securitySchemesMap,\n state,\n };\n\n if (finalPathItem.delete) {\n parsePathOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.delete,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.get) {\n parsePathOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.get,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.head) {\n parsePathOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.head,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.options) {\n parsePathOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.options,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.patch) {\n parsePathOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.patch,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.post) {\n parsePathOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.post,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.put) {\n parsePathOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.put,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.trace) {\n parsePathOperation({\n ...operationArgs,\n method: 'trace',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.trace,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.trace.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { addNamespace, removeNamespace } from '../../../openApi/shared/utils/filter';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { OpenApiV3_1_X, PathItemObject, PathsObject } from '../types/spec';\n\n/**\n * Replace source spec with filtered version.\n */\nexport const filterSpec = ({\n logger,\n operations,\n parameters,\n preserveOrder,\n requestBodies,\n responses,\n schemas,\n spec,\n}: {\n logger: Logger;\n operations: Set<string>;\n parameters: Set<string>;\n preserveOrder: boolean;\n requestBodies: Set<string>;\n responses: Set<string>;\n schemas: Set<string>;\n spec: OpenApiV3_1_X;\n}) => {\n const eventFilterSpec = logger.timeEvent('filter-spec');\n if (spec.components) {\n if (spec.components.parameters) {\n const filtered: typeof spec.components.parameters = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.parameters)) {\n if (parameters.has(addNamespace('parameter', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of parameters) {\n const { name } = removeNamespace(key);\n const source = spec.components.parameters[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.parameters = filtered;\n }\n\n if (spec.components.requestBodies) {\n const filtered: typeof spec.components.requestBodies = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.requestBodies)) {\n if (requestBodies.has(addNamespace('body', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of requestBodies) {\n const { name } = removeNamespace(key);\n const source = spec.components.requestBodies[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.requestBodies = filtered;\n }\n\n if (spec.components.responses) {\n const filtered: typeof spec.components.responses = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.responses)) {\n if (responses.has(addNamespace('response', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of responses) {\n const { name } = removeNamespace(key);\n const source = spec.components.responses[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.responses = filtered;\n }\n\n if (spec.components.schemas) {\n const filtered: typeof spec.components.schemas = {};\n\n if (preserveOrder) {\n for (const [name, source] of Object.entries(spec.components.schemas)) {\n if (schemas.has(addNamespace('schema', name))) {\n filtered[name] = source;\n }\n }\n } else {\n for (const key of schemas) {\n const { name } = removeNamespace(key);\n const source = spec.components.schemas[name];\n if (source) {\n filtered[name] = source;\n }\n }\n }\n\n spec.components.schemas = filtered;\n }\n }\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const key = addNamespace('operation', createOperationKey({ method, path }));\n if (!operations.has(key)) {\n delete pathItem[method];\n }\n }\n\n // remove paths that have no operations left\n if (!Object.keys(pathItem).length) {\n delete spec.paths[path];\n }\n }\n }\n eventFilterSpec.timeEnd();\n};\n","import type { IRMediaType } from '../../../ir/mediaType';\nimport { isMediaTypeFileLike, mediaTypeToIrMediaType } from '../../../ir/mediaType';\nimport type { MediaTypeObject, SchemaObject } from '../types/spec';\n\ninterface Content {\n mediaType: string;\n schema: SchemaObject | undefined;\n type: IRMediaType | undefined;\n}\n\nexport const contentToSchema = ({ content }: { content: Content }): SchemaObject | undefined => {\n const { mediaType, schema } = content;\n\n if (!schema) {\n if (isMediaTypeFileLike({ mediaType })) {\n return {\n format: 'binary',\n type: 'string',\n };\n }\n return;\n }\n\n if (schema.type === 'string' && !schema.format && isMediaTypeFileLike({ mediaType })) {\n return {\n ...schema,\n format: 'binary',\n };\n }\n\n return schema;\n};\n\nexport const mediaTypeObjects = ({\n content,\n}: {\n content: Record<string, MediaTypeObject> | undefined;\n}): ReadonlyArray<Content> => {\n const objects: Array<Content> = [];\n\n for (const mediaType in content) {\n objects.push({\n mediaType,\n schema: content[mediaType]!.schema,\n type: mediaTypeToIrMediaType({ mediaType }),\n });\n }\n\n return objects;\n};\n","import type { Context } from '../../../ir/context';\nimport { isMediaTypeFileLike } from '../../../ir/mediaType';\nimport type { IR } from '../../../ir/types';\nimport { addItemsToSchema } from '../../../ir/utils';\nimport type {\n SchemaState,\n SchemaType,\n SchemaWithRequired,\n} from '../../../openApi/shared/types/schema';\nimport {\n convertDiscriminatorValue,\n type DiscriminatorPropertyType,\n discriminatorValues,\n} from '../../../openApi/shared/utils/discriminator';\nimport { isTopLevelComponent, refToName } from '../../../utils/ref';\nimport type { SchemaObject } from '../types/spec';\n\nexport const getSchemaTypes = ({\n schema,\n}: {\n schema: SchemaObject;\n}): ReadonlyArray<SchemaType<SchemaObject>> => {\n if (typeof schema.type === 'string') {\n return [schema.type];\n }\n\n if (schema.type) {\n return schema.type;\n }\n\n // infer object based on the presence of properties\n if (schema.properties) {\n return ['object'];\n }\n\n return [];\n};\n\n/**\n * Finds the type of a discriminator property by looking it up in the provided schemas.\n * Searches through properties and allOf chains to find the property definition.\n */\nconst findDiscriminatorPropertyType = ({\n context,\n propertyName,\n schemas,\n}: {\n context: Context;\n propertyName: string;\n schemas: ReadonlyArray<SchemaObject>;\n}): DiscriminatorPropertyType => {\n for (const schema of schemas) {\n const resolved = schema.$ref ? context.resolveRef<SchemaObject>(schema.$ref) : schema;\n\n // Check direct properties\n const property = resolved.properties?.[propertyName];\n if (property === true) {\n continue;\n }\n if (property) {\n const resolvedProperty = property.$ref\n ? context.resolveRef<SchemaObject>(property.$ref)\n : property;\n // Handle both single type and array of types (3.1.x supports type arrays)\n const propertyTypes = Array.isArray(resolvedProperty.type)\n ? resolvedProperty.type\n : resolvedProperty.type\n ? [resolvedProperty.type]\n : [];\n for (const propType of propertyTypes) {\n if (propType === 'boolean' || propType === 'integer' || propType === 'number') {\n return propType;\n }\n }\n }\n\n // Check allOf chains\n if (resolved.allOf) {\n const foundType = findDiscriminatorPropertyType({\n context,\n propertyName,\n schemas: resolved.allOf,\n });\n if (foundType !== 'string') {\n return foundType;\n }\n }\n }\n\n return 'string';\n};\n\n/**\n * Recursively finds discriminators in a schema, including nested allOf compositions.\n * This is needed when a schema extends another schema via allOf, and that parent\n * schema is itself an allOf composition with discriminators in inline schemas.\n */\nconst findDiscriminatorsInSchema = ({\n context,\n discriminators = [],\n schema,\n}: {\n context: Context;\n discriminators?: Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n }>;\n schema: SchemaObject;\n}): Array<{\n discriminator: NonNullable<SchemaObject['discriminator']>;\n oneOf?: SchemaObject['oneOf'];\n}> => {\n // Check if this schema has a discriminator\n if (schema.discriminator) {\n discriminators.push({\n discriminator: schema.discriminator,\n oneOf: schema.oneOf,\n });\n }\n\n // If this schema is an allOf composition, recursively search in its components\n if (schema.allOf) {\n for (const compositionSchema of schema.allOf) {\n let resolvedSchema: SchemaObject;\n if (compositionSchema.$ref) {\n resolvedSchema = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n } else {\n resolvedSchema = compositionSchema;\n }\n\n findDiscriminatorsInSchema({\n context,\n discriminators,\n schema: resolvedSchema,\n });\n }\n }\n\n return discriminators;\n};\n\n/**\n * Gets the discriminator value for a schema.\n * Returns only the schema's own discriminator value, not child values.\n */\nconst getAllDiscriminatorValues = ({\n discriminator,\n schemaRef,\n}: {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n schemaRef: string;\n}): Array<string> => {\n const values: Array<string> = [];\n\n // Check each entry in the discriminator mapping\n for (const [value, mappedSchemaRef] of Object.entries(discriminator.mapping || {})) {\n if (mappedSchemaRef === schemaRef) {\n // This is the current schema's own value\n values.push(value);\n }\n }\n\n return values;\n};\n\nconst parseSchemaJsDoc = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.deprecated !== undefined) {\n irSchema.deprecated = schema.deprecated;\n }\n\n if (schema.example) {\n irSchema.example = schema.example;\n }\n\n if (schema.description) {\n irSchema.description = schema.description;\n }\n\n if (schema.title) {\n irSchema.title = schema.title;\n }\n};\n\nconst parseSchemaMeta = ({\n irSchema,\n schema,\n}: {\n irSchema: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n if (schema.const !== undefined) {\n irSchema.const = schema.const;\n\n // try to infer schema type\n if (!schema.type) {\n if (schema.const === null) {\n irSchema.type = 'null';\n } else {\n switch (typeof schema.const) {\n case 'bigint':\n case 'number':\n irSchema.type = 'number';\n break;\n case 'boolean':\n irSchema.type = 'boolean';\n break;\n case 'string':\n irSchema.type = 'string';\n break;\n }\n }\n }\n }\n\n if (schema.default !== undefined) {\n irSchema.default = schema.default;\n }\n\n if (schema.exclusiveMaximum !== undefined) {\n irSchema.exclusiveMaximum = schema.exclusiveMaximum;\n }\n\n if (schema.exclusiveMinimum !== undefined) {\n irSchema.exclusiveMinimum = schema.exclusiveMinimum;\n }\n\n if (schema.format) {\n irSchema.format = schema.format;\n } else if (\n schema.contentMediaType &&\n isMediaTypeFileLike({ mediaType: schema.contentMediaType })\n ) {\n irSchema.format = 'binary';\n }\n\n if (schema.maximum !== undefined) {\n irSchema.maximum = schema.maximum;\n }\n\n if (schema.maxItems !== undefined) {\n irSchema.maxItems = schema.maxItems;\n }\n\n if (schema.maxLength !== undefined) {\n irSchema.maxLength = schema.maxLength;\n }\n\n if (schema.minimum !== undefined) {\n irSchema.minimum = schema.minimum;\n }\n\n if (schema.minItems !== undefined) {\n irSchema.minItems = schema.minItems;\n }\n\n if (schema.minLength !== undefined) {\n irSchema.minLength = schema.minLength;\n }\n\n if (schema.pattern) {\n irSchema.pattern = schema.pattern;\n }\n\n if (schema.readOnly) {\n irSchema.accessScope = 'read';\n } else if (schema.writeOnly) {\n irSchema.accessScope = 'write';\n }\n};\n\nconst parseArray = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n if (\n (schema.prefixItems && schema.prefixItems.length) ||\n (schema.maxItems && schema.maxItems === schema.minItems) ||\n schema.const !== undefined\n ) {\n irSchema.type = 'tuple';\n } else {\n irSchema.type = 'array';\n }\n\n let schemaItems: Array<IR.SchemaObject> = [];\n\n for (const item of schema.prefixItems ?? []) {\n const irItemSchema = schemaToIrSchema({\n context,\n schema: item,\n state,\n });\n schemaItems.push(irItemSchema);\n }\n\n if (schema.items) {\n const irItemsSchema = schemaToIrSchema({\n context,\n schema: schema.items,\n state,\n });\n\n if (!schemaItems.length && schema.maxItems && schema.maxItems === schema.minItems) {\n schemaItems = Array(schema.maxItems).fill(irItemsSchema);\n } else {\n const ofArray = schema.items.allOf || schema.items.anyOf || schema.items.oneOf;\n if (\n ofArray &&\n ofArray.length > 1 &&\n !getSchemaTypes({ schema: schema.items }).includes('null')\n ) {\n // bring composition up to avoid incorrectly nested arrays\n irSchema = {\n ...irSchema,\n ...irItemsSchema,\n };\n } else {\n schemaItems.push(irItemsSchema);\n }\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseBoolean = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n irSchema.type = 'boolean';\n\n return irSchema;\n};\n\nconst parseNull = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}) => {\n irSchema.type = 'null';\n\n return irSchema;\n};\n\nconst parseNumber = ({\n irSchema = {},\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: Omit<SchemaObject, 'type'> & {\n type: SchemaType<SchemaObject>;\n };\n}): IR.SchemaObject => {\n irSchema.type = schema.type;\n\n return irSchema;\n};\n\nconst parseObject = ({\n context,\n irSchema = {},\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n state: SchemaState;\n}): IR.SchemaObject => {\n irSchema.type = 'object';\n\n const schemaProperties: Record<string, IR.SchemaObject> = {};\n\n for (const name in schema.properties) {\n const property = schema.properties[name]!;\n if (typeof property === 'boolean') {\n // TODO: parser - handle boolean properties\n } else {\n const irPropertySchema = schemaToIrSchema({\n context,\n schema: property,\n state,\n });\n schemaProperties[name] = irPropertySchema;\n }\n }\n\n if (Object.keys(schemaProperties).length) {\n irSchema.properties = schemaProperties;\n }\n\n if (schema.additionalProperties === undefined) {\n if (!irSchema.properties) {\n irSchema.additionalProperties = {\n type: 'unknown',\n };\n }\n } else if (typeof schema.additionalProperties === 'boolean') {\n // Avoid [key: string]: never for empty objects with additionalProperties: false inside allOf\n // This would override inherited properties from other schemas in the composition\n const isEmptyObjectInAllOf =\n state.inAllOf &&\n schema.additionalProperties === false &&\n (!schema.properties || !Object.keys(schema.properties).length) &&\n (!schema.patternProperties || !Object.keys(schema.patternProperties).length);\n\n if (!isEmptyObjectInAllOf) {\n irSchema.additionalProperties = {\n type: schema.additionalProperties ? 'unknown' : 'never',\n };\n }\n } else {\n const irAdditionalPropertiesSchema = schemaToIrSchema({\n context,\n schema: schema.additionalProperties,\n state,\n });\n irSchema.additionalProperties = irAdditionalPropertiesSchema;\n }\n\n if (schema.patternProperties) {\n const patternProperties: Record<string, IR.SchemaObject> = {};\n\n for (const pattern in schema.patternProperties) {\n const patternSchema = schema.patternProperties[pattern]!;\n const irPatternSchema = schemaToIrSchema({\n context,\n schema: patternSchema,\n state,\n });\n patternProperties[pattern] = irPatternSchema;\n }\n\n if (Object.keys(patternProperties).length) {\n irSchema.patternProperties = patternProperties;\n }\n }\n\n if (schema.propertyNames) {\n irSchema.propertyNames = schemaToIrSchema({\n context,\n schema: schema.propertyNames,\n state,\n });\n }\n\n if (schema.required) {\n irSchema.required = schema.required;\n }\n\n return irSchema;\n};\n\nconst parseString = ({\n irSchema = {},\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n irSchema.type = 'string';\n\n return irSchema;\n};\n\nexport const parseExtensions = ({ source, target }: { source: object; target: object }) => {\n for (const key in source) {\n if (key.startsWith('x-')) {\n (target as Record<string, unknown>)[key] = (source as Record<string, unknown>)[key];\n }\n }\n};\n\nconst initIrSchema = ({ schema }: { schema: SchemaObject }): IR.SchemaObject => {\n const irSchema: IR.SchemaObject = {};\n\n parseSchemaJsDoc({\n irSchema,\n schema,\n });\n\n parseExtensions({\n source: schema,\n target: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseAllOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'allOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n const compositionSchemas = schema.allOf;\n\n // Collect discriminator information to add after all compositions are processed\n type DiscriminatorInfo = {\n discriminator: NonNullable<SchemaObject['discriminator']>;\n isExplicitMapping: boolean;\n isRequired: boolean;\n values: ReadonlyArray<string>;\n };\n const discriminatorsToAdd: Array<DiscriminatorInfo> = [];\n\n for (const compositionSchema of compositionSchemas) {\n const originalInAllOf = state.inAllOf;\n // Don't propagate inAllOf flag to $ref schemas to avoid issues with reusable components\n if (!('$ref' in compositionSchema)) {\n state.inAllOf = true;\n }\n const irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n state.inAllOf = originalInAllOf;\n if (state.inAllOf === undefined) {\n delete state.inAllOf;\n }\n\n if (schema.required) {\n if (irCompositionSchema.required) {\n irCompositionSchema.required = [...irCompositionSchema.required, ...schema.required];\n } else {\n irCompositionSchema.required = schema.required;\n }\n }\n\n schemaItems.push(irCompositionSchema);\n\n if (compositionSchema.$ref) {\n const ref = context.resolveRef<SchemaObject>(compositionSchema.$ref);\n // `$ref` should be passed from the root `parseSchema()` call\n if (state.$ref) {\n // Find all discriminators in the referenced schema, including nested allOf compositions\n const discriminators = findDiscriminatorsInSchema({\n context,\n schema: ref,\n });\n\n for (const { discriminator, oneOf } of discriminators) {\n const values = discriminatorValues(\n state.$ref,\n discriminator.mapping,\n // If the ref has oneOf, we only use the schema name as the value\n // only if current schema is part of the oneOf. Else it is extending\n // the ref schema\n oneOf ? () => oneOf.some((o) => '$ref' in o && o.$ref === state.$ref) : undefined,\n );\n\n if (values.length === 0) {\n continue;\n }\n\n // True when state.$ref appears directly in the mapping; false when the\n // value fell back to the schema name because no mapping entry matched.\n const isExplicitMapping =\n discriminator.mapping !== undefined &&\n Object.values(discriminator.mapping).includes(state.$ref);\n\n // An explicit mapping always beats a same-property fallback collected\n // earlier (e.g. from a grandparent discriminator that doesn't list this\n // schema). Replace it; otherwise skip the duplicate.\n const existingIndex = discriminatorsToAdd.findIndex(\n (d) => d.discriminator.propertyName === discriminator.propertyName,\n );\n if (existingIndex !== -1) {\n if (isExplicitMapping && !discriminatorsToAdd[existingIndex]!.isExplicitMapping) {\n discriminatorsToAdd.splice(existingIndex, 1);\n } else {\n continue;\n }\n }\n\n const isRequired = discriminators.some(\n (d) =>\n d.discriminator.propertyName === discriminator.propertyName &&\n (ref.required?.includes(d.discriminator.propertyName) ||\n (ref.allOf &&\n ref.allOf.some((item) => {\n const resolvedItem = item.$ref\n ? context.resolveRef<SchemaObject>(item.$ref)\n : item;\n return resolvedItem.required?.includes(d.discriminator.propertyName);\n }))),\n );\n\n discriminatorsToAdd.push({\n discriminator,\n isExplicitMapping,\n isRequired,\n values,\n });\n }\n }\n }\n }\n\n // Now add discriminators after all compositions have been processed\n for (const { discriminator, isRequired, values } of discriminatorsToAdd) {\n // Get all discriminator values including children for union types\n const allValues = getAllDiscriminatorValues({\n discriminator,\n schemaRef: state.$ref!,\n });\n\n // Use allValues if we found children, otherwise use the original values\n const finalValues = allValues.length > 0 ? allValues : values;\n\n // Detect the actual type of the discriminator property\n const propertyType = findDiscriminatorPropertyType({\n context,\n propertyName: discriminator.propertyName,\n schemas: compositionSchemas,\n });\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = finalValues.map((value) =>\n convertDiscriminatorValue(value, propertyType),\n );\n\n const discriminatorProperty: IR.SchemaObject =\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!;\n\n // Check if any $ref schemas in schemaItems have this discriminator property\n // If yes, mark them to omit it to avoid conflicts\n for (const item of schemaItems) {\n if (item.$ref || item.symbolRef) {\n // Check if the referenced schema has this property\n const hasProperty = (() => {\n if (!item.$ref) return false;\n try {\n const refSchema = context.resolveRef<SchemaObject>(item.$ref);\n // Check if the discriminator property exists in the ref schema\n return (\n refSchema.properties?.[discriminator.propertyName] !== undefined ||\n (refSchema.allOf &&\n refSchema.allOf.some((allOfItem) => {\n const resolved = allOfItem.$ref\n ? context.resolveRef<SchemaObject>(allOfItem.$ref)\n : allOfItem;\n return resolved.properties?.[discriminator.propertyName] !== undefined;\n }))\n );\n } catch {\n return false;\n }\n })();\n\n if (hasProperty) {\n // Mark this ref to omit the discriminator property\n if (!item.omit) {\n item.omit = [discriminator.propertyName];\n } else if (!item.omit.includes(discriminator.propertyName)) {\n item.omit = [...item.omit, discriminator.propertyName];\n }\n }\n }\n }\n\n // Find the inline schema (non-$ref) to merge the discriminator property into\n // The inline schema should be the last non-$ref item in schemaItems\n let inlineSchema: IR.SchemaObject | undefined;\n for (let i = schemaItems.length - 1; i >= 0; i--) {\n const item = schemaItems[i]!;\n // Check if this is not a $ref schema by looking for properties or checking if it came from an inline schema\n if (item.type === 'object' || item.properties) {\n inlineSchema = item;\n break;\n }\n }\n\n // If we found an inline schema, add the discriminator property to it\n if (inlineSchema) {\n if (!inlineSchema.properties) {\n inlineSchema.properties = {};\n }\n inlineSchema.properties[discriminator.propertyName] = discriminatorProperty;\n\n if (isRequired) {\n if (!inlineSchema.required) {\n inlineSchema.required = [];\n }\n if (!inlineSchema.required.includes(discriminator.propertyName)) {\n inlineSchema.required = [...inlineSchema.required, discriminator.propertyName];\n }\n }\n } else {\n // Fallback: create a separate discriminator schema if no inline schema found\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [discriminator.propertyName]: discriminatorProperty,\n },\n type: 'object',\n };\n\n if (isRequired) {\n irDiscriminatorSchema.required = [discriminator.propertyName];\n }\n schemaItems.push(irDiscriminatorSchema);\n }\n }\n\n if (schemaTypes.includes('object')) {\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n for (const requiredProperty of irObjectSchema.required ?? []) {\n if (!irObjectSchema.properties[requiredProperty]) {\n for (const compositionSchema of compositionSchemas) {\n // TODO: parser - this could be probably resolved more accurately\n const finalCompositionSchema = compositionSchema.$ref\n ? context.resolveRef<SchemaObject>(compositionSchema.$ref)\n : compositionSchema;\n\n if (getSchemaTypes({ schema: finalCompositionSchema }).includes('object')) {\n const irCompositionSchema = parseOneType({\n context,\n schema: {\n ...finalCompositionSchema,\n type: 'object',\n },\n state,\n });\n\n if (irCompositionSchema.properties?.[requiredProperty]) {\n irObjectSchema.properties[requiredProperty] =\n irCompositionSchema.properties[requiredProperty];\n break;\n }\n }\n }\n }\n }\n schemaItems.push(irObjectSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n logicalOperator: 'and',\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaTypes.includes('null')) {\n // nest composition to avoid producing an intersection with null\n const nestedItems: Array<IR.SchemaObject> = [\n {\n type: 'null',\n },\n ];\n\n if (schemaItems.length) {\n nestedItems.unshift(irSchema);\n }\n\n irSchema = {\n items: nestedItems,\n logicalOperator: 'or',\n };\n }\n\n return irSchema;\n};\n\nconst parseAnyOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'anyOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n const compositionSchemas = schema.anyOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n schemaItems.push(irCompositionSchema);\n }\n\n if (schemaTypes.includes('null')) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaTypes.includes('object')) {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseEnum = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'enum'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n\n irSchema.type = 'enum';\n\n const schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n for (const [index, enumValue] of schema.enum.entries()) {\n const typeOfEnumValue = typeof enumValue;\n let enumType: SchemaType<SchemaObject> | undefined;\n\n if (\n typeOfEnumValue === 'string' ||\n typeOfEnumValue === 'number' ||\n typeOfEnumValue === 'boolean'\n ) {\n enumType = typeOfEnumValue;\n } else if (typeOfEnumValue === 'object' && Array.isArray(enumValue)) {\n enumType = 'array';\n } else if (enumValue === null) {\n // type must contain null\n if (schemaTypes.includes('null')) {\n enumType = 'null';\n }\n } else {\n console.warn(\n '๐Ÿšจ',\n `unhandled \"${typeOfEnumValue}\" typeof value \"${enumValue}\" for enum`,\n schema.enum,\n );\n }\n\n if (!enumType) {\n continue;\n }\n\n const irTypeSchema = parseOneType({\n context,\n schema: {\n const: enumValue,\n description: schema['x-enum-descriptions']?.[index],\n title: schema['x-enum-varnames']?.[index] ?? schema['x-enumNames']?.[index],\n type: enumType,\n },\n state,\n });\n\n schemaItems.push(irTypeSchema);\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseOneOf = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'oneOf'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n let schemaItems: Array<IR.SchemaObject> = [];\n const schemaTypes = getSchemaTypes({ schema });\n\n const compositionSchemas = schema.oneOf;\n\n const discriminatorPropertyType = schema.discriminator\n ? findDiscriminatorPropertyType({\n context,\n propertyName: schema.discriminator.propertyName,\n schemas: compositionSchemas,\n })\n : undefined;\n\n for (const compositionSchema of compositionSchemas) {\n let irCompositionSchema = schemaToIrSchema({\n context,\n schema: compositionSchema,\n state,\n });\n\n // `$ref` should be defined with discriminators\n if (schema.discriminator && irCompositionSchema.$ref != null) {\n const values = discriminatorValues(irCompositionSchema.$ref, schema.discriminator.mapping);\n\n const valueSchemas: ReadonlyArray<IR.SchemaObject> = values.map((value) =>\n convertDiscriminatorValue(value, discriminatorPropertyType!),\n );\n const irDiscriminatorSchema: IR.SchemaObject = {\n properties: {\n [schema.discriminator.propertyName]:\n valueSchemas.length > 1\n ? {\n items: valueSchemas,\n logicalOperator: 'or',\n }\n : valueSchemas[0]!,\n },\n required: [schema.discriminator.propertyName],\n type: 'object',\n };\n irCompositionSchema = {\n items: [irDiscriminatorSchema, irCompositionSchema],\n logicalOperator: 'and',\n };\n }\n\n // since we know oneOf will be using \"or\" logical operator, if the parsed\n // composition schema also has an \"or\" operator, we can bring it up\n // to avoid unnecessary brackets\n if (\n irCompositionSchema.logicalOperator === 'or' &&\n irCompositionSchema.type !== 'array' &&\n irCompositionSchema.items\n ) {\n schemaItems = schemaItems.concat(irCompositionSchema.items);\n } else {\n schemaItems.push(irCompositionSchema);\n }\n }\n\n if (schemaTypes.includes('null')) {\n schemaItems.push({ type: 'null' });\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n if (schemaTypes.includes('object')) {\n // nest composition to avoid producing a union with object properties\n const irObjectSchema = parseOneType({\n context,\n schema: {\n ...schema,\n type: 'object',\n },\n state,\n });\n\n if (irObjectSchema.properties) {\n irSchema = {\n items: [irSchema, irObjectSchema],\n logicalOperator: 'and',\n };\n }\n }\n\n return irSchema;\n};\n\nconst parseRef = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, '$ref'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n // Inline non-component refs (e.g. #/paths/...) and deep path refs (e.g. #/components/schemas/Foo/properties/bar)\n // to avoid generating orphaned named types or referencing unregistered symbols\n const isComponentsRef = isTopLevelComponent(schema.$ref);\n if (!isComponentsRef) {\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n const irSchema = schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n return irSchema;\n }\n // Fallback to preserving the ref if circular\n }\n\n let irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n\n const irRefSchema: IR.SchemaObject = {};\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n irRefSchema.$ref = decodeURI(schema.$ref);\n\n if (!state.circularReferenceTracker.has(schema.$ref)) {\n const refSchema = context.resolveRef<SchemaObject>(schema.$ref);\n const originalRef = state.$ref;\n state.$ref = schema.$ref;\n schemaToIrSchema({\n context,\n schema: refSchema,\n state,\n });\n state.$ref = originalRef;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [];\n schemaItems.push(irRefSchema);\n\n if (schema.type && typeof schema.type !== 'string') {\n if (schema.type.includes('null')) {\n schemaItems.push({ type: 'null' });\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n mutateSchemaOneItem: true,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseOneType = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: Omit<SchemaObject, 'type'> & {\n type: SchemaType<SchemaObject>;\n };\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n parseSchemaMeta({ irSchema, schema });\n }\n\n switch (schema.type) {\n case 'array':\n return parseArray({\n context,\n irSchema,\n schema,\n state,\n });\n case 'boolean':\n return parseBoolean({\n context,\n irSchema,\n schema,\n });\n case 'integer':\n case 'number':\n return parseNumber({\n context,\n irSchema,\n schema,\n });\n case 'null':\n return parseNull({\n context,\n irSchema,\n schema,\n });\n case 'object':\n return parseObject({\n context,\n irSchema,\n schema,\n state,\n });\n case 'string':\n return parseString({\n context,\n irSchema,\n schema,\n });\n default:\n // gracefully handle invalid type\n return parseUnknown({ context, irSchema, schema });\n }\n};\n\nconst parseManyTypes = ({\n context,\n irSchema,\n schema,\n state,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: Omit<SchemaObject, 'type'> & {\n type: ReadonlyArray<SchemaType<SchemaObject>>;\n };\n state: SchemaState;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n const typeIrSchema: IR.SchemaObject = {};\n\n parseSchemaMeta({ irSchema: typeIrSchema, schema });\n\n if (schema.type.includes('null') && typeIrSchema.default === null) {\n // clear to avoid duplicate default inside the non-null schema.\n // this would produce incorrect validator output\n delete typeIrSchema.default;\n }\n\n const schemaItems: Array<IR.SchemaObject> = [];\n\n for (const type of schema.type) {\n if (type === 'null') {\n schemaItems.push({ type: 'null' });\n } else {\n const irTypeSchema = parseOneType({\n context,\n irSchema: { ...typeIrSchema },\n schema: {\n ...schema,\n type,\n },\n state,\n });\n\n schemaItems.push(irTypeSchema);\n }\n }\n\n irSchema = addItemsToSchema({\n items: schemaItems,\n schema: irSchema,\n });\n\n return irSchema;\n};\n\nconst parseType = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaWithRequired<SchemaObject, 'type'>;\n state: SchemaState;\n}): IR.SchemaObject => {\n const irSchema = initIrSchema({ schema });\n\n parseSchemaMeta({ irSchema, schema });\n\n const schemaTypes = getSchemaTypes({ schema });\n\n if (schemaTypes.length === 1) {\n return parseOneType({\n context,\n irSchema,\n schema: {\n ...schema,\n type: schemaTypes[0]!,\n },\n state,\n });\n }\n\n return parseManyTypes({\n context,\n irSchema,\n schema: {\n ...schema,\n type: schemaTypes,\n },\n state,\n });\n};\n\nconst parseUnknown = ({\n irSchema,\n schema,\n}: {\n context: Context;\n irSchema?: IR.SchemaObject;\n schema: SchemaObject;\n}): IR.SchemaObject => {\n if (!irSchema) {\n irSchema = initIrSchema({ schema });\n }\n\n irSchema.type = 'unknown';\n\n parseSchemaMeta({ irSchema, schema });\n\n return irSchema;\n};\n\nexport const schemaToIrSchema = ({\n context,\n schema,\n state,\n}: {\n context: Context;\n schema: SchemaObject;\n state: SchemaState | undefined;\n}): IR.SchemaObject => {\n if (!state) {\n state = {\n circularReferenceTracker: new Set(),\n };\n }\n\n if (state.$ref) {\n state.circularReferenceTracker.add(state.$ref);\n }\n\n if (schema.$ref) {\n return parseRef({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, '$ref'>,\n state,\n });\n }\n\n if (schema.enum) {\n return parseEnum({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'enum'>,\n state,\n });\n }\n\n if (schema.allOf) {\n return parseAllOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'allOf'>,\n state,\n });\n }\n\n if (schema.anyOf) {\n return parseAnyOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'anyOf'>,\n state,\n });\n }\n\n if (schema.oneOf) {\n return parseOneOf({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'oneOf'>,\n state,\n });\n }\n\n // infer object based on the presence of properties\n if (schema.type || schema.properties) {\n return parseType({\n context,\n schema: schema as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n // infer string with binary format based on contentMediaType\n if (schema.contentMediaType && isMediaTypeFileLike({ mediaType: schema.contentMediaType })) {\n return parseType({\n context,\n schema: { ...schema, type: 'string' } as SchemaWithRequired<SchemaObject, 'type'>,\n state,\n });\n }\n\n return parseUnknown({ context, schema });\n};\n\nexport const parseSchema = ({\n $ref,\n context,\n schema,\n}: {\n $ref: string;\n context: Context;\n schema: SchemaObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.schemas) {\n context.ir.components.schemas = {};\n }\n\n context.ir.components.schemas[refToName($ref)] = schemaToIrSchema({\n context,\n schema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { getPaginationKeywordsRegExp } from '../../../ir/pagination';\nimport type { SchemaType } from '../../../openApi/shared/types/schema';\nimport type { ParameterObject, RequestBodyObject } from '../types/spec';\nimport type { SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { getSchemaTypes } from './schema';\n\nconst isPaginationType = (schemaTypes: ReadonlyArray<SchemaType<SchemaObject>>): boolean =>\n schemaTypes.includes('boolean') ||\n schemaTypes.includes('integer') ||\n schemaTypes.includes('number') ||\n schemaTypes.includes('string');\n\n// We handle only simple values for now, up to 1 nested field\nexport const paginationField = ({\n context,\n name,\n schema,\n}: {\n context: Context;\n name: string;\n schema: SchemaObject;\n}): boolean | string => {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n if (paginationRegExp.test(name)) {\n return true;\n }\n\n if (schema.$ref) {\n const ref = context.resolveRef<ParameterObject | RequestBodyObject | SchemaObject>(schema.$ref);\n\n if ('content' in ref || 'in' in ref) {\n let refSchema: SchemaObject | undefined;\n\n if ('in' in ref) {\n refSchema = ref.schema;\n }\n\n if (!refSchema) {\n // parameter or body\n const contents = mediaTypeObjects({ content: ref.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content?.schema) {\n refSchema = content.schema;\n }\n }\n\n if (!refSchema) {\n return false;\n }\n\n return paginationField({\n context,\n name,\n schema: refSchema,\n });\n }\n\n return paginationField({\n context,\n name,\n schema: ref,\n });\n }\n\n for (const name in schema.properties) {\n const paginationRegExp = getPaginationKeywordsRegExp(context.config.parser.pagination);\n\n if (paginationRegExp.test(name)) {\n const property = schema.properties[name]!;\n\n if (typeof property !== 'boolean') {\n // TODO: resolve deeper references\n const schemaTypes = getSchemaTypes({ schema: property });\n\n if (!schemaTypes.length) {\n const compositionSchemas = property.anyOf ?? property.oneOf;\n const nonNullCompositionSchemas = (compositionSchemas ?? []).filter(\n (schema) => schema.type !== 'null',\n );\n if (nonNullCompositionSchemas.length === 1) {\n const schemaTypes = getSchemaTypes({\n schema: nonNullCompositionSchemas[0]!,\n });\n if (isPaginationType(schemaTypes)) {\n return name;\n }\n }\n }\n\n if (isPaginationType(schemaTypes)) {\n return name;\n }\n }\n }\n }\n\n for (const allOf of schema.allOf ?? []) {\n const pagination = paginationField({\n context,\n name,\n schema: allOf,\n });\n if (pagination) {\n return pagination;\n }\n }\n\n return false;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport type { State } from '../../../openApi/shared/types/state';\nimport type { httpMethods } from '../../../openApi/shared/utils/operation';\nimport { operationToId } from '../../../openApi/shared/utils/operation';\nimport type {\n OperationObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { contentToSchema, mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\nexport interface Operation\n extends Omit<OperationObject, 'parameters'>, Pick<IR.OperationObject, 'parameters'> {}\n\nconst parseOperationJsDoc = ({\n irOperation,\n operation,\n}: {\n irOperation: IR.OperationObject;\n operation: Operation;\n}) => {\n if (operation.deprecated !== undefined) {\n irOperation.deprecated = operation.deprecated;\n }\n\n if (operation.description) {\n irOperation.description = operation.description;\n }\n\n if (operation.summary) {\n irOperation.summary = operation.summary;\n }\n\n if (operation.tags?.length) {\n irOperation.tags = operation.tags;\n }\n};\n\nconst initIrOperation = ({\n context,\n method,\n operation,\n path,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n state: State;\n}): IR.OperationObject => {\n const irOperation: IR.OperationObject = {\n id: operationToId({\n context,\n id: operation.operationId,\n method,\n path,\n state,\n }),\n method,\n path,\n };\n\n if (operation.operationId) {\n irOperation.operationId = operation.operationId;\n }\n\n parseOperationJsDoc({\n irOperation,\n operation,\n });\n\n parseExtensions({\n source: operation,\n target: irOperation,\n });\n\n return irOperation;\n};\n\nconst operationToIrOperation = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: Pick<IR.OperationObject, 'method' | 'path'> & {\n context: Context;\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}): IR.OperationObject => {\n const irOperation = initIrOperation({\n context,\n method,\n operation,\n path,\n state,\n });\n\n if (operation.parameters) {\n irOperation.parameters = operation.parameters;\n }\n\n if (operation.requestBody) {\n const requestBody =\n '$ref' in operation.requestBody\n ? context.resolveRef<RequestBodyObject>(operation.requestBody.$ref)\n : operation.requestBody;\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n const pagination = paginationField({\n context,\n name: '',\n schema: {\n description: requestBody.description,\n ...content.schema,\n },\n });\n\n irOperation.body = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: requestBody.description,\n ...('$ref' in operation.requestBody ? operation.requestBody : content.schema),\n },\n state: undefined,\n }),\n };\n\n if (pagination) {\n irOperation.body.pagination = pagination;\n }\n\n if (requestBody.required) {\n irOperation.body.required = requestBody.required;\n }\n\n if (content.type) {\n irOperation.body.type = content.type;\n }\n }\n }\n\n for (const name in operation.responses) {\n if (name.startsWith('x-')) continue;\n\n if (!irOperation.responses) {\n irOperation.responses = {};\n }\n\n const response = operation.responses[name]! as ResponseObject | ReferenceObject;\n const responseObject =\n '$ref' in response ? context.resolveRef<ResponseObject>(response.$ref) : response;\n const contents = mediaTypeObjects({ content: responseObject.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n\n if (content) {\n irOperation.responses[name] = {\n mediaType: content.mediaType,\n schema: schemaToIrSchema({\n context,\n schema: {\n description: responseObject.description,\n ...contentToSchema({ content }),\n },\n state: undefined,\n }),\n };\n } else {\n irOperation.responses[name] = {\n schema: {\n description: responseObject.description,\n // TODO: parser - cover all statues with empty response bodies\n // 1xx, 204, 205, 304\n type: name === '204' ? 'void' : 'unknown',\n },\n };\n }\n }\n\n if (operation.security) {\n const securitySchemeObjects: Map<string, IR.SecurityObject> = new Map();\n\n for (const securityRequirementObject of operation.security) {\n for (const name in securityRequirementObject) {\n const securitySchemeObject = securitySchemesMap.get(name);\n\n if (!securitySchemeObject) {\n continue;\n }\n\n securitySchemeObjects.set(name, securitySchemeObject);\n }\n }\n\n if (securitySchemeObjects.size) {\n irOperation.security = Array.from(securitySchemeObjects.values());\n }\n }\n\n // TODO: parser - handle servers\n // qux: operation.servers\n\n return irOperation;\n};\n\nconst parseOperationObject = ({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n}: {\n context: Context;\n method: (typeof httpMethods)[number];\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (operation.servers) {\n context.ir.servers = [...(context.ir.servers ?? []), ...operation.servers];\n }\n\n const parsed = operationToIrOperation({\n context,\n method,\n operation,\n path,\n securitySchemesMap,\n state,\n });\n\n return { parsed };\n};\n\nexport const parsePathOperation = ({\n context,\n method,\n path,\n ...options\n}: {\n context: Context;\n method: (typeof httpMethods)[number];\n operation: Operation;\n path: keyof IR.PathsObject;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.paths) {\n context.ir.paths = {};\n }\n\n if (!context.ir.paths[path]) {\n context.ir.paths[path] = {};\n }\n\n const { parsed } = parseOperationObject({\n context,\n method,\n path,\n ...options,\n });\n\n context.ir.paths[path][method] = parsed;\n};\n\nexport const parseWebhookOperation = ({\n context,\n key,\n method,\n ...options\n}: {\n context: Context;\n key: string;\n method: (typeof httpMethods)[number];\n operation: Operation;\n securitySchemesMap: Map<string, SecuritySchemeObject>;\n state: State;\n}) => {\n if (!context.ir.webhooks) {\n context.ir.webhooks = {};\n }\n\n if (!context.ir.webhooks[key]) {\n context.ir.webhooks[key] = {};\n }\n\n const { parsed } = parseOperationObject({\n context,\n method,\n path: key as `/${string}`,\n ...options,\n });\n\n context.ir.webhooks[key][method] = parsed;\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { ParameterObject, ReferenceObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { paginationField } from './pagination';\nimport { parseExtensions, schemaToIrSchema } from './schema';\n\n/**\n * Returns default parameter `allowReserved` based on value of `in`.\n */\nconst defaultAllowReserved = (_in: ParameterObject['in']): boolean | undefined => {\n switch (_in) {\n // this keyword only applies to parameters with an `in` value of `query`\n case 'query':\n return false;\n default:\n return;\n }\n};\n\n/**\n * Returns default parameter `explode` based on value of `style`.\n */\nconst defaultExplode = (style: Required<ParameterObject>['style']): boolean => {\n switch (style) {\n // default value for `deepObject` is `false`, but that behavior is undefined\n // so we use `true` to make this work with the `client-fetch` package\n case 'deepObject':\n case 'form':\n return true;\n default:\n return false;\n }\n};\n\n/**\n * Returns default parameter `style` based on value of `in`.\n */\nconst defaultStyle = (_in: ParameterObject['in']): Required<ParameterObject>['style'] => {\n switch (_in) {\n case 'header':\n case 'path':\n return 'simple';\n case 'cookie':\n case 'query':\n return 'form';\n }\n};\n\nexport const parametersArrayToObject = ({\n context,\n parameters,\n}: {\n context: Context;\n parameters?: ReadonlyArray<ParameterObject | ReferenceObject>;\n}): IR.ParametersObject | undefined => {\n if (!parameters || !Object.keys(parameters).length) {\n return;\n }\n\n const parametersObject: IR.ParametersObject = {};\n\n for (const parameterOrReference of parameters) {\n const parameter =\n '$ref' in parameterOrReference\n ? context.dereference<ParameterObject>(parameterOrReference)\n : parameterOrReference;\n\n if (!parametersObject[parameter.in]) {\n parametersObject[parameter.in] = {};\n }\n\n // lowercase keys for case insensitive access\n parametersObject[parameter.in]![parameter.name.toLocaleLowerCase()] = parameterToIrParameter({\n $ref: `#/todo/real/path/to/parameter/${parameter.name}`,\n context,\n parameter,\n });\n }\n\n return parametersObject;\n};\n\nconst parameterToIrParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}): IR.ParameterObject => {\n // TODO: parser - fix\n let schema = parameter.schema;\n\n if (!schema) {\n const contents = mediaTypeObjects({ content: parameter.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n if (content) {\n schema = content.schema;\n }\n }\n\n const finalSchema: SchemaObject = {\n deprecated: parameter.deprecated,\n description: parameter.description,\n ...schema,\n };\n\n const pagination = paginationField({\n context,\n name: parameter.name,\n schema: finalSchema,\n });\n\n const style = parameter.style || defaultStyle(parameter.in);\n const explode = parameter.explode !== undefined ? parameter.explode : defaultExplode(style);\n const allowReserved =\n parameter.allowReserved !== undefined\n ? parameter.allowReserved\n : defaultAllowReserved(parameter.in);\n\n const irParameter: IR.ParameterObject = {\n allowReserved,\n explode,\n location: parameter.in,\n name: parameter.name,\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n style,\n };\n\n if (parameter.deprecated) {\n irParameter.deprecated = parameter.deprecated;\n }\n\n if (parameter.description) {\n irParameter.description = parameter.description;\n }\n\n if (pagination) {\n irParameter.pagination = pagination;\n }\n\n if (parameter.required) {\n irParameter.required = parameter.required;\n }\n\n parseExtensions({\n source: parameter,\n target: irParameter,\n });\n\n return irParameter;\n};\n\nexport const parseParameter = ({\n $ref,\n context,\n parameter,\n}: {\n $ref: string;\n context: Context;\n parameter: ParameterObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.parameters) {\n context.ir.components.parameters = {};\n }\n\n context.ir.components.parameters[refToName($ref)] = parameterToIrParameter({\n $ref,\n context,\n parameter,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport type { IR } from '../../../ir/types';\nimport { refToName } from '../../../utils/ref';\nimport type { RequestBodyObject, SchemaObject } from '../types/spec';\nimport { mediaTypeObjects } from './mediaType';\nimport { schemaToIrSchema } from './schema';\n\nconst requestBodyToIrRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}): IR.RequestBodyObject => {\n // TODO: parser - fix\n const contents = mediaTypeObjects({ content: requestBody.content });\n // TODO: add support for multiple content types, for now prefer JSON\n const content = contents.find((content) => content.type === 'json') || contents[0];\n const schema = content ? content.schema : undefined;\n\n const finalSchema: SchemaObject = {\n description: requestBody.description,\n ...schema,\n };\n\n const irRequestBody: IR.RequestBodyObject = {\n schema: schemaToIrSchema({\n context,\n schema: finalSchema,\n state: {\n $ref,\n circularReferenceTracker: new Set(),\n },\n }),\n };\n\n if (requestBody.description) {\n irRequestBody.description = requestBody.description;\n }\n\n if (requestBody.required) {\n irRequestBody.required = requestBody.required;\n }\n\n return irRequestBody;\n};\n\nexport const parseRequestBody = ({\n $ref,\n context,\n requestBody,\n}: {\n $ref: string;\n context: Context;\n requestBody: RequestBodyObject;\n}) => {\n if (!context.ir.components) {\n context.ir.components = {};\n }\n\n if (!context.ir.components.requestBodies) {\n context.ir.components.requestBodies = {};\n }\n\n context.ir.components.requestBodies[refToName($ref)] = requestBodyToIrRequestBody({\n $ref,\n context,\n requestBody,\n });\n};\n","import type { Context } from '../../../ir/context';\nimport { parseUrl } from '../../../utils/url';\n\nexport const parseServers = ({ context }: { context: Context }) => {\n if (context.spec.servers) {\n context.ir.servers = context.spec.servers;\n return;\n }\n\n for (const input of context.config.input) {\n if (typeof input.path === 'string') {\n const url = parseUrl(input.path);\n context.ir.servers = [\n {\n url: `${url.protocol ? `${url.protocol}://` : ''}${url.host}${url.port ? `:${url.port}` : ''}`,\n },\n ];\n }\n }\n\n if (!context.ir.servers) {\n context.ir.servers = [\n {\n url: '/',\n },\n ];\n }\n};\n","import type { Logger } from '@hey-api/codegen-core';\n\nimport { createOperationKey } from '../../../ir/operation';\nimport { httpMethods } from '../../../openApi/shared/utils/operation';\nimport type { ValidatorIssue, ValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type { OpenApiV3_1_X, PathItemObject, PathsObject } from '../types/spec';\n\nexport const validateOpenApiSpec = (spec: OpenApiV3_1_X, logger: Logger): ValidatorResult => {\n const eventValidate = logger.timeEvent('validate');\n const issues: Array<ValidatorIssue> = [];\n const operationIds = new Map();\n\n if (spec.paths) {\n for (const entry of Object.entries(spec.paths)) {\n const path = entry[0] as keyof PathsObject;\n const pathItem = entry[1] as PathItemObject;\n for (const method of httpMethods) {\n const operation = pathItem[method];\n if (!operation) {\n continue;\n }\n\n const operationKey = createOperationKey({ method, path });\n\n if (operation.operationId) {\n if (!operationIds.has(operation.operationId)) {\n operationIds.set(operation.operationId, operationKey);\n } else {\n issues.push({\n code: 'duplicate_key',\n context: {\n key: 'operationId',\n value: operation.operationId,\n },\n message: 'Duplicate `operationId` found. Each `operationId` must be unique.',\n path: ['paths', path, method, 'operationId'],\n severity: 'error',\n });\n }\n }\n }\n }\n }\n\n if (spec.servers) {\n if (typeof spec.servers !== 'object' || !Array.isArray(spec.servers)) {\n issues.push({\n code: 'invalid_type',\n message: '`servers` must be an array.',\n path: [],\n severity: 'error',\n });\n }\n\n for (let index = 0; index < spec.servers.length; index++) {\n const server = spec.servers[index];\n if (!server || typeof server !== 'object') {\n issues.push({\n code: 'invalid_type',\n context: {\n actual: typeof server,\n expected: 'object',\n },\n message: 'Each entry in `servers` must be an object.',\n path: ['servers', index],\n severity: 'error',\n });\n } else {\n if (!server.url) {\n issues.push({\n code: 'missing_required_field',\n context: {\n field: 'url',\n },\n message: 'Missing required field `url` in server object.',\n path: ['servers', index],\n severity: 'error',\n });\n }\n }\n }\n }\n\n eventValidate.timeEnd();\n return {\n issues,\n valid: !issues.some((issue) => issue.severity === 'error'),\n };\n};\n","import type { Context } from '../../../ir/context';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport type { OpenApiV3_1_X, PathItemObject } from '../types/spec';\nimport { parseWebhookOperation } from './operation';\nimport { parametersArrayToObject } from './parameter';\n\nexport const parseWebhooks = ({\n context,\n securitySchemesMap,\n}: Pick<Parameters<typeof parseWebhookOperation>[0], 'securitySchemesMap'> & {\n context: Context<OpenApiV3_1_X>;\n}) => {\n const state: Parameters<typeof parseWebhookOperation>[0]['state'] = {\n ids: new Map(),\n };\n\n for (const key in context.spec.webhooks) {\n const webhook = context.spec.webhooks[key]!;\n\n const finalWebhook =\n '$ref' in webhook\n ? {\n ...context.resolveRef<PathItemObject>(webhook.$ref!),\n ...webhook,\n }\n : webhook;\n\n const operationArgs: Omit<Parameters<typeof parseWebhookOperation>[0], 'method'> = {\n context,\n key,\n operation: {\n description: finalWebhook.description,\n parameters: parametersArrayToObject({\n context,\n parameters: finalWebhook.parameters,\n }),\n security: context.spec.security,\n servers: finalWebhook.servers,\n summary: finalWebhook.summary,\n },\n securitySchemesMap,\n state,\n };\n\n if (finalWebhook.delete) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.delete,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.get) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.get,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.head) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.head,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.options) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.options,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.patch) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.patch,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.post) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.post,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.put) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.put,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalWebhook.trace) {\n parseWebhookOperation({\n ...operationArgs,\n method: 'trace',\n operation: {\n ...operationArgs.operation,\n ...finalWebhook.trace,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalWebhook.trace.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n }\n};\n","import type { Context } from '../../../ir/context';\nimport { buildResourceMetadata } from '../../../openApi/shared/graph/meta';\nimport { transformOpenApiSpec } from '../../../openApi/shared/transforms';\nimport type { State } from '../../../openApi/shared/types/state';\nimport {\n createFilteredDependencies,\n createFilters,\n hasFilters,\n} from '../../../openApi/shared/utils/filter';\nimport { buildGraph } from '../../../openApi/shared/utils/graph';\nimport { mergeParametersObjects } from '../../../openApi/shared/utils/parameter';\nimport { handleValidatorResult } from '../../../openApi/shared/utils/validator';\nimport type {\n OpenApiV3_1_X,\n ParameterObject,\n PathItemObject,\n PathsObject,\n RequestBodyObject,\n SecuritySchemeObject,\n} from '../types/spec';\nimport { filterSpec } from './filter';\nimport { parsePathOperation } from './operation';\nimport { parametersArrayToObject, parseParameter } from './parameter';\nimport { parseRequestBody } from './requestBody';\nimport { parseSchema } from './schema';\nimport { parseServers } from './server';\nimport { validateOpenApiSpec } from './validate';\nimport { parseWebhooks } from './webhook';\n\nexport const parseV3_1_X = (context: Context<OpenApiV3_1_X>) => {\n if (context.config.parser.validate_EXPERIMENTAL) {\n const result = validateOpenApiSpec(context.spec, context.logger);\n handleValidatorResult({ context, result });\n }\n\n const shouldFilterSpec = hasFilters(context.config.parser.filters);\n if (shouldFilterSpec) {\n const filters = createFilters(context.config.parser.filters, context.spec, context.logger);\n const { graph } = buildGraph(context.spec, context.logger);\n const { resourceMetadata } = buildResourceMetadata(graph, context.logger);\n const sets = createFilteredDependencies({\n filters,\n logger: context.logger,\n resourceMetadata,\n });\n filterSpec({\n ...sets,\n logger: context.logger,\n preserveOrder: filters.preserveOrder,\n spec: context.spec,\n });\n }\n\n transformOpenApiSpec({ context });\n\n const state: State = {\n ids: new Map(),\n };\n const securitySchemesMap = new Map<string, SecuritySchemeObject>();\n\n // TODO: parser - handle more component types, old parser handles only parameters and schemas\n if (context.spec.components) {\n for (const name in context.spec.components.securitySchemes) {\n const securityOrReference = context.spec.components.securitySchemes[name]!;\n const securitySchemeObject =\n '$ref' in securityOrReference\n ? context.resolveRef<SecuritySchemeObject>(securityOrReference.$ref)\n : securityOrReference;\n securitySchemesMap.set(name, securitySchemeObject);\n }\n\n for (const name in context.spec.components.parameters) {\n const $ref = `#/components/parameters/${name}`;\n const parameterOrReference = context.spec.components.parameters[name]!;\n const parameter =\n '$ref' in parameterOrReference\n ? context.resolveRef<ParameterObject>(parameterOrReference.$ref)\n : parameterOrReference;\n\n parseParameter({\n $ref,\n context,\n parameter,\n });\n }\n\n for (const name in context.spec.components.requestBodies) {\n const $ref = `#/components/requestBodies/${name}`;\n const requestBodyOrReference = context.spec.components.requestBodies[name]!;\n const requestBody =\n '$ref' in requestBodyOrReference\n ? context.resolveRef<RequestBodyObject>(requestBodyOrReference.$ref)\n : requestBodyOrReference;\n\n parseRequestBody({\n $ref,\n context,\n requestBody,\n });\n }\n\n for (const name in context.spec.components.schemas) {\n const $ref = `#/components/schemas/${name}`;\n const schema = context.spec.components.schemas[name]!;\n\n parseSchema({\n $ref,\n context,\n schema,\n });\n }\n }\n\n parseServers({ context });\n\n for (const path in context.spec.paths) {\n if (path.startsWith('x-')) continue;\n const pathItem = context.spec.paths[path as keyof PathsObject]! as PathItemObject;\n\n const finalPathItem = pathItem.$ref\n ? {\n ...context.resolveRef<PathItemObject>(pathItem.$ref),\n ...pathItem,\n }\n : pathItem;\n\n const operationArgs: Omit<Parameters<typeof parsePathOperation>[0], 'method'> = {\n context,\n operation: {\n description: finalPathItem.description,\n parameters: parametersArrayToObject({\n context,\n parameters: finalPathItem.parameters,\n }),\n security: context.spec.security,\n servers: finalPathItem.servers,\n summary: finalPathItem.summary,\n },\n path: path as `/${string}`,\n securitySchemesMap,\n state,\n };\n\n if (finalPathItem.delete) {\n parsePathOperation({\n ...operationArgs,\n method: 'delete',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.delete,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.delete.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.get) {\n parsePathOperation({\n ...operationArgs,\n method: 'get',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.get,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.get.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.head) {\n parsePathOperation({\n ...operationArgs,\n method: 'head',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.head,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.head.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.options) {\n parsePathOperation({\n ...operationArgs,\n method: 'options',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.options,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.options.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.patch) {\n parsePathOperation({\n ...operationArgs,\n method: 'patch',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.patch,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.patch.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.post) {\n parsePathOperation({\n ...operationArgs,\n method: 'post',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.post,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.post.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.put) {\n parsePathOperation({\n ...operationArgs,\n method: 'put',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.put,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.put.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n\n if (finalPathItem.trace) {\n parsePathOperation({\n ...operationArgs,\n method: 'trace',\n operation: {\n ...operationArgs.operation,\n ...finalPathItem.trace,\n parameters: mergeParametersObjects({\n source: parametersArrayToObject({\n context,\n parameters: finalPathItem.trace.parameters,\n }),\n target: operationArgs.operation.parameters,\n }),\n },\n });\n }\n }\n\n parseWebhooks({ context, securitySchemesMap });\n};\n","import { satisfies } from '../config/utils/dependencies';\nimport type { Context } from '../ir/context';\nimport { parseV2_0_X } from './2.0.x';\nimport { parseV3_0_X } from './3.0.x';\nimport { parseV3_1_X } from './3.1.x';\nimport type { OpenApi } from './types';\n\n/**\n * @internal\n * Parse the resolved OpenAPI specification. This will populate and return\n * `context` with intermediate representation obtained from the parsed spec.\n */\nexport function parseOpenApiSpec(context: Context): Context {\n if ('swagger' in context.spec) {\n parseV2_0_X(context as Context<OpenApi.V2_0_X>);\n return context;\n }\n\n if (satisfies(context.spec.openapi, '>=3.0.0 <3.1.0')) {\n parseV3_0_X(context as Context<OpenApi.V3_0_X>);\n return context;\n }\n\n if (satisfies(context.spec.openapi, '>=3.1.0')) {\n parseV3_1_X(context as Context<OpenApi.V3_1_X>);\n return context;\n }\n\n throw new Error('Unsupported OpenAPI specification');\n}\n","import type { StructureLocation } from '@hey-api/codegen-core';\n\nimport type { IR } from '../../../ir/types';\n\n/**\n * A function that derives path segments from an operation.\n *\n * Used by location strategies to build paths within containers.\n */\nexport type OperationPathStrategy = (operation: IR.OperationObject) => ReadonlyArray<string>;\n\n/**\n * A function that determines where an operation appears in the structure.\n *\n * Returns one or more locations, each with a full path.\n */\nexport type OperationStructureStrategy = (\n operation: IR.OperationObject,\n) => ReadonlyArray<StructureLocation['path']>;\n\nexport type OperationsStrategy = 'byTags' | 'flat' | 'single' | OperationStructureStrategy;\n\n/**\n * Built-in strategies for operations.\n */\nexport const OperationStrategy = {\n /**\n * Creates one root container per operation tag.\n *\n * Operations with multiple tags appear in multiple root containers.\n * Operations without tags use the fallback root container.\n *\n * @example\n * // Operation with tags: ['users', 'admin']\n * // Path function returns: ['list']\n * // Result: [{ path: ['users', 'list'], shell }, { path: ['admin', 'list'], shell }]\n */\n byTags:\n (config: {\n /**\n * Root name for operations without tags.\n */\n fallback: string;\n /**\n * Derives path segments from the operation.\n *\n * @default OperationPath.id()\n */\n path?: OperationPathStrategy;\n }): OperationStructureStrategy =>\n (operation) => {\n const tags = operation.tags && operation.tags.length > 0 ? operation.tags : [config.fallback];\n const path = config.path ?? OperationPath.id();\n const pathSegments = path(operation);\n return tags.map((tag) => [tag, ...pathSegments]);\n },\n\n /**\n * Creates flat functions without any container.\n *\n * Each operation becomes a standalone function at the root level.\n * No shell is applied.\n *\n * @example\n * // Operation id: 'getUsers'\n * // Result: [{ path: ['getUsers'] }]\n */\n flat:\n (config?: {\n /**\n * Derives path segments within the root from the operation.\n *\n * @default OperationPath.id()\n */\n path?: OperationPathStrategy;\n }): OperationStructureStrategy =>\n (operation) => {\n const path = config?.path ?? OperationPath.id();\n const pathSegments = path(operation);\n return [[pathSegments[pathSegments.length - 1]!]];\n },\n\n /**\n * Places all operations under a single root container.\n *\n * @example\n * // Root: 'Sdk', path function returns: ['users', 'list']\n * // Result: [{ path: ['Sdk', 'users', 'list'], shell }]\n */\n single:\n (config: {\n /**\n * Derives path segments within the root from the operation.\n *\n * @default OperationPath.id()\n */\n path?: OperationPathStrategy;\n /**\n * Name of the container.\n */\n root: string;\n }): OperationStructureStrategy =>\n (operation) => {\n const path = config.path ?? OperationPath.id();\n const pathSegments = path(operation);\n return [[config.root, ...pathSegments]];\n },\n};\n\n/**\n * Built-in path derivation helpers for operations.\n */\nexport const OperationPath = {\n /**\n * Splits operationId by delimiters to create nested paths.\n *\n * @example\n * // operationId: 'users.accounts.list'\n * // Result: ['users', 'accounts', 'list']\n *\n * @example\n * // operationId: 'users/accounts/getAll'\n * // Result: ['users', 'accounts', 'getAll']\n */\n fromOperationId:\n (config?: {\n /**\n * Pattern to split operationId.\n *\n * @default /[./]/\n */\n delimiters?: RegExp;\n /**\n * Fallback strategy if operationId is missing.\n *\n * @default OperationPath.id()\n */\n fallback?: OperationPathStrategy;\n }): OperationPathStrategy =>\n (operation) => {\n const fallback = config?.fallback ?? OperationPath.id();\n if (!operation.operationId) return fallback(operation);\n const delimiters = config?.delimiters ?? /[./]/;\n const segments = operation.operationId.split(delimiters).filter(Boolean);\n return segments.length === 0 ? fallback(operation) : segments;\n },\n\n /**\n * Splits path by delimiters to create nested paths.\n *\n * Can include the method as a prefix or suffix segment.\n *\n * @example\n * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\\/{}]+/, methodPosition: 'none'\n * // Result: ['users', 'id', 'accounts']\n *\n * @example\n * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\\/{}]+/, methodPosition: 'prefix'\n * // Result: ['get', 'users', 'id', 'accounts']\n *\n * @example\n * // path: '/users/{id}/accounts', method: 'get', delimiters: /[\\/{}]+/, methodPosition: 'suffix'\n * // Result: ['users', 'id', 'accounts', 'get']\n */\n fromPath:\n (config?: {\n /**\n * Pattern to split the path.\n *\n * @default /[./]/\n */\n delimiters?: RegExp;\n /**\n * Position of the method segment.\n *\n * @default 'none'\n */\n methodPosition?: 'prefix' | 'suffix';\n }): OperationPathStrategy =>\n (operation) => {\n const delimiters = config?.delimiters ?? /[./]/;\n const segments = operation.path.split(delimiters).filter(Boolean);\n switch (config?.methodPosition) {\n case 'prefix':\n segments.unshift(operation.method.toLowerCase());\n break;\n case 'suffix':\n segments.push(operation.method.toLowerCase());\n break;\n default:\n break;\n }\n return segments;\n },\n\n /**\n * Uses operation.id as a single path segment.\n *\n * @example\n * // operation.id: 'getUserById'\n * // Result: ['getUserById']\n */\n id: (): OperationPathStrategy => (operation) => [operation.id],\n};\n","import type { Patch } from '../../../config/parser/patch';\nimport type { OpenApi } from '../../../openApi/types';\n\nexport async function patchOpenApiSpec({\n patchOptions,\n spec: _spec,\n}: {\n patchOptions: Patch | undefined;\n spec: unknown;\n}) {\n if (!patchOptions) {\n return;\n }\n\n const spec = _spec as OpenApi.V2_0_X | OpenApi.V3_0_X | OpenApi.V3_1_X;\n\n if (typeof patchOptions === 'function') {\n await patchOptions(spec);\n return;\n }\n\n if (patchOptions.input) {\n await patchOptions.input(spec);\n }\n\n if ('swagger' in spec) {\n if (patchOptions.version && spec.swagger) {\n spec.swagger = (\n typeof patchOptions.version === 'string'\n ? patchOptions.version\n : patchOptions.version(spec.swagger)\n ) as typeof spec.swagger;\n }\n\n if (patchOptions.meta && spec.info) {\n patchOptions.meta(spec.info);\n }\n\n if (patchOptions.schemas && spec.definitions) {\n if (typeof patchOptions.schemas === 'function') {\n for (const [key, schema] of Object.entries(spec.definitions)) {\n if (schema && typeof schema === 'object') {\n await patchOptions.schemas(key, schema);\n }\n }\n } else {\n for (const key in patchOptions.schemas) {\n const schema = spec.definitions[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.schemas[key]!;\n await patchFn(schema);\n }\n }\n }\n\n if (patchOptions.operations && spec.paths) {\n if (typeof patchOptions.operations === 'function') {\n // Bulk callback: iterate all operations\n for (const [path, pathItem] of Object.entries(spec.paths)) {\n if (!pathItem || typeof pathItem !== 'object') continue;\n for (const method of [\n 'get',\n 'put',\n 'post',\n 'delete',\n 'options',\n 'head',\n 'patch',\n 'trace',\n ]) {\n const operation = pathItem[method as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n await patchOptions.operations(method, path, operation as any);\n }\n }\n } else {\n // Record-based: iterate named operations\n for (const key in patchOptions.operations) {\n const [method, path] = key.split(' ');\n if (!method || !path) continue;\n\n const pathItem = spec.paths[path as keyof typeof spec.paths];\n if (!pathItem) continue;\n\n const operation =\n pathItem[method.toLocaleLowerCase() as keyof typeof pathItem] ||\n pathItem[method.toLocaleUpperCase() as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n\n const patchFn = patchOptions.operations[key]!;\n await patchFn(operation as any);\n }\n }\n }\n return;\n }\n\n if (patchOptions.version && spec.openapi) {\n spec.openapi = (\n typeof patchOptions.version === 'string'\n ? patchOptions.version\n : patchOptions.version(spec.openapi)\n ) as typeof spec.openapi;\n }\n\n if (patchOptions.meta && spec.info) {\n patchOptions.meta(spec.info);\n }\n\n if (spec.components) {\n if (patchOptions.schemas && spec.components.schemas) {\n if (typeof patchOptions.schemas === 'function') {\n for (const [key, schema] of Object.entries(spec.components.schemas)) {\n if (schema && typeof schema === 'object') {\n await patchOptions.schemas(key, schema as Parameters<typeof patchOptions.schemas>[1]);\n }\n }\n } else {\n for (const key in patchOptions.schemas) {\n const schema = spec.components.schemas[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.schemas[key]!;\n await patchFn(schema as Parameters<typeof patchFn>[0]);\n }\n }\n }\n\n if (patchOptions.parameters && spec.components.parameters) {\n for (const key in patchOptions.parameters) {\n const schema = spec.components.parameters[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.parameters[key]!;\n patchFn(schema);\n }\n }\n\n if (patchOptions.requestBodies && spec.components.requestBodies) {\n for (const key in patchOptions.requestBodies) {\n const schema = spec.components.requestBodies[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.requestBodies[key]!;\n patchFn(schema);\n }\n }\n\n if (patchOptions.responses && spec.components.responses) {\n for (const key in patchOptions.responses) {\n const schema = spec.components.responses[key];\n if (!schema || typeof schema !== 'object') continue;\n\n const patchFn = patchOptions.responses[key]!;\n patchFn(schema);\n }\n }\n }\n\n if (patchOptions.operations && spec.paths) {\n if (typeof patchOptions.operations === 'function') {\n // Bulk callback: iterate all operations\n for (const [path, pathItem] of Object.entries(spec.paths)) {\n if (!pathItem || typeof pathItem !== 'object') continue;\n for (const method of [\n 'get',\n 'put',\n 'post',\n 'delete',\n 'options',\n 'head',\n 'patch',\n 'trace',\n ]) {\n const operation = pathItem[method as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n await patchOptions.operations(method, path, operation as any);\n }\n }\n } else {\n // Record-based: iterate named operations\n for (const key in patchOptions.operations) {\n const [method, path] = key.split(' ');\n if (!method || !path) continue;\n\n const pathItem = spec.paths[path as keyof typeof spec.paths];\n if (!pathItem) continue;\n\n const operation =\n pathItem[method.toLocaleLowerCase() as keyof typeof pathItem] ||\n pathItem[method.toLocaleUpperCase() as keyof typeof pathItem];\n if (!operation || typeof operation !== 'object') continue;\n\n const patchFn = patchOptions.operations[key]!;\n await patchFn(operation as any);\n }\n }\n }\n}\n","import type { Plugin } from '../../../plugins/types';\n\nexport const definePluginConfig =\n <T extends Plugin.Types>(defaultConfig: Plugin.Config<T>) =>\n (\n userConfig?: Omit<T['config'], 'name'>,\n ): Omit<Plugin.Config<T>, 'name'> & {\n /**\n * Cast name to `any` so it doesn't throw type error in `plugins` array.\n * We could allow any `string` as plugin `name` in the object syntax, but\n * that TypeScript trick would cause all string methods to appear as\n * suggested auto completions, which is undesirable.\n */\n name: any;\n } => ({\n ...defaultConfig,\n config: {\n ...defaultConfig.config,\n ...userConfig,\n },\n });\n\n/**\n * Reusable mappers for `enabled` and `name` fields.\n */\nexport const mappers = {\n boolean: (enabled: boolean) => ({ enabled }),\n function: (name: (...args: Array<any>) => any) => ({ name }),\n string: (name: string) => ({ name }),\n} as const;\n","import type { SymbolIn } from '@hey-api/codegen-core';\n\nimport type { GetNameContext } from '../parser/hooks';\nimport { applyNaming } from '../utils/naming/naming';\nimport type { PluginInstance } from './shared/utils/instance';\n\n/**\n * Helper function to build the input for symbol registration, applying naming hooks if provided.\n */\nexport function buildSymbolIn({\n plugin,\n ...ctx\n}: GetNameContext & {\n plugin: {\n config: Pick<PluginInstance['config'], '~hooks'>;\n context: {\n config: {\n parser: Pick<PluginInstance['context']['config']['parser'], 'hooks'>;\n };\n };\n };\n}): SymbolIn {\n const hooks = [\n plugin.config['~hooks']?.symbols?.getName,\n plugin.context.config.parser.hooks.symbols?.getName,\n ];\n for (const hook of hooks) {\n if (!hook) continue;\n\n const result = hook(ctx);\n if (typeof result === 'function') {\n const name = result(ctx);\n if (name) {\n return {\n meta: ctx.meta,\n name,\n };\n }\n } else if (typeof result === 'string') {\n return {\n meta: ctx.meta,\n name: ctx.naming ? applyNaming(result, ctx.naming) : result,\n };\n }\n }\n\n return {\n meta: ctx.meta,\n name: ctx.naming ? applyNaming(ctx.name, ctx.naming) : ctx.name,\n };\n}\n","import { EOL } from 'node:os';\n\nexport function escapeComment(value: string) {\n return value\n .replace(/\\*\\//g, '*')\n .replace(/\\/\\*/g, '*')\n .replace(/\\r?\\n(.*)/g, (_l, w) => EOL + w.trim());\n}\n","import { toCase } from './naming/naming';\nimport type { Casing } from './naming/types';\n\n/**\n * Utilities shared across the package.\n */\nexport const utils = {\n /**\n * @deprecated use `toCase` instead\n */\n stringCase({\n case: casing,\n stripLeadingSeparators,\n value,\n }: {\n readonly case: Casing | undefined;\n /**\n * If leading separators have a semantic meaning, we might not want to\n * remove them.\n */\n stripLeadingSeparators?: boolean;\n value: string;\n }) {\n return toCase(value, casing, { stripLeadingSeparators });\n },\n /**\n * Converts the given string to the specified casing.\n */\n toCase,\n};\n","import type { IProject } from '@hey-api/codegen-core';\n\nimport type { OutputHeader } from '../config/output/types';\n\n/**\n * Converts an {@link OutputHeader} value to a string prefix for file content.\n */\nexport function outputHeaderToPrefix(header: OutputHeader, project: IProject): string {\n let lines = typeof header === 'function' ? header({ project }) : header;\n if (lines === null || lines === undefined) return '';\n lines =\n typeof lines === 'string' ? lines.split(/\\r?\\n/) : lines.flatMap((line) => line.split(/\\r?\\n/));\n const content = lines.join('\\n');\n return content ? `${content}\\n\\n` : '';\n}\n","/**\n * After these structural segments, the next segment has a known role.\n * This is what makes a property literally named \"properties\" safe โ€”\n * it occupies the name position, never the structural position.\n */\nconst STRUCTURAL_ROLE: Record<string, 'name' | 'index'> = {\n items: 'index',\n patternProperties: 'name',\n properties: 'name',\n};\n\n/**\n * These structural segments have no following name/index โ€”\n * they are the terminal structural node. Append a suffix\n * to disambiguate from the parent.\n */\nconst STRUCTURAL_SUFFIX: Record<string, string> = {\n additionalProperties: 'Value',\n};\n\ntype RootContextConfig = {\n /** How many consecutive semantic segments follow before structural walking begins */\n names: number;\n /** How many leading segments to skip (the root keyword + any category segment) */\n skip: number;\n};\n\n/**\n * Root context configuration.\n */\nconst ROOT_CONTEXT: Record<string | number, RootContextConfig> = {\n components: { names: 1, skip: 2 }, // components/schemas/{name}\n definitions: { names: 1, skip: 1 }, // definitions/{name}\n paths: { names: 2, skip: 1 }, // paths/{path}/{method}\n webhooks: { names: 2, skip: 1 }, // webhooks/{name}/{method}\n};\n\n/**\n * Sanitizes a path segment for use in a derived name.\n *\n * Handles API path segments like `/api/v1/users/{id}` โ†’ `ApiV1UsersId`.\n */\nfunction sanitizeSegment(segment: string | number): string {\n const str = String(segment);\n if (str.startsWith('/')) {\n return str\n .split('/')\n .filter(Boolean)\n .map((part) => {\n const clean = part.replace(/[{}]/g, '');\n return clean.charAt(0).toUpperCase() + clean.slice(1);\n })\n .join('');\n }\n return str;\n}\n\nexport interface PathToNameOptions {\n /**\n * When provided, replaces the root semantic segments with this anchor.\n * Structural suffixes are still derived from path.\n */\n anchor?: string;\n}\n\n/**\n * Derives a composite name from a path.\n *\n * Examples:\n * .../User โ†’ 'User'\n * .../User/properties/address โ†’ 'UserAddress'\n * .../User/properties/properties โ†’ 'UserProperties'\n * .../User/properties/address/properties/city โ†’ 'UserAddressCity'\n * .../Pet/additionalProperties โ†’ 'PetValue'\n * .../Order/properties/items/items/0 โ†’ 'OrderItems'\n * paths//event/get/properties/query โ†’ 'EventGetQuery'\n *\n * With anchor:\n * paths//event/get/properties/query, { anchor: 'event.subscribe' }\n * โ†’ 'event.subscribe-Query'\n */\nexport function pathToName(\n path: ReadonlyArray<string | number>,\n options?: PathToNameOptions,\n): string {\n const names: Array<string> = [];\n let index = 0;\n\n const rootContext = ROOT_CONTEXT[path[0]!];\n if (rootContext) {\n index = rootContext.skip;\n\n if (options?.anchor) {\n // Use anchor as base name, skip past root semantic segments\n names.push(options.anchor);\n index += rootContext.names;\n } else {\n // Collect consecutive semantic name segments\n for (let n = 0; n < rootContext.names && index < path.length; n++) {\n names.push(sanitizeSegment(path[index]!));\n index++;\n }\n }\n } else {\n // Unknown root\n if (options?.anchor) {\n names.push(options.anchor);\n index++;\n } else if (index < path.length) {\n names.push(sanitizeSegment(path[index]!));\n index++;\n }\n }\n\n while (index < path.length) {\n const segment = String(path[index]);\n\n const role = STRUCTURAL_ROLE[segment];\n if (role === 'name') {\n // Next segment is a semantic name โ€” collect it\n index++;\n if (index < path.length) {\n names.push(sanitizeSegment(path[index]!));\n }\n } else if (role === 'index') {\n // Next segment is a numeric index โ€” skip it\n index++;\n if (index < path.length && typeof path[index] === 'number') {\n index++;\n }\n continue;\n } else if (STRUCTURAL_SUFFIX[segment]) {\n names.push(STRUCTURAL_SUFFIX[segment]);\n }\n\n index++;\n }\n\n // refs using unicode characters become encoded, didn't investigate why\n // but the suspicion is this comes from `@hey-api/json-schema-ref-parser`\n return decodeURI(names.join('-'));\n}\n"],"mappings":";;;;;;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