@abapify/openai-codegen 0.4.31 → 0.4.36

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 +0,0 @@
1
- {"version":3,"file":"generate-DgXsowgP.mjs","names":["isRecord","isRecord","componentNameFromRef","isRecord","pluckType","isNullable","findPlannedEntryBySchema","buildStructureFields","isRecord","pluckType","componentNameFromRef","pickRequestBodySchema","exhaustive"],"sources":["../src/oas/types.ts","../src/oas/load.ts","../src/types/naming.ts","../src/types/errors.ts","../src/types/plan.ts","../src/types/map.ts","../src/emit/naming.ts","../src/emit/types-interface.ts","../src/emit/operations-interface.ts","../src/emit/exception-class.ts","../src/emit/templates/locals-def.abap.ts","../src/emit/templates/locals-imp.abap.ts","../src/emit/local-classes.ts","../src/emit/response-mapper.ts","../src/format/validate.ts","../src/format/abapgit.ts","../src/format/gcts.ts","../src/format/index.ts","../src/emit/implementation-class.ts","../src/generate.ts"],"sourcesContent":["/**\n * Narrowed OpenAPI 3.1-compatible types used by the code generator.\n *\n * These are deliberately decoupled from `openapi-types` to keep the surface\n * small, stable, and friendly to ABAP emitters. `JsonSchema` is kept as an\n * open record for now — later waves will refine it into a discriminated union\n * when we need richer structural reasoning.\n */\n\nexport type JsonSchema = Record<string, unknown>;\n\nexport interface JsonSchemaRef {\n $ref: string;\n}\n\nexport function isRef(x: unknown): x is JsonSchemaRef {\n return (\n typeof x === 'object' &&\n x !== null &&\n typeof (x as { $ref?: unknown }).$ref === 'string'\n );\n}\n\nexport type HttpMethod =\n | 'get'\n | 'post'\n | 'put'\n | 'patch'\n | 'delete'\n | 'head'\n | 'options'\n | 'trace';\n\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie';\n\nexport interface SpecInfo {\n title: string;\n version: string;\n description?: string;\n termsOfService?: string;\n contact?: { name?: string; url?: string; email?: string };\n license?: { name: string; url?: string; identifier?: string };\n}\n\nexport interface NormalizedServerVariable {\n default: string;\n enum?: string[];\n description?: string;\n}\n\nexport interface NormalizedServer {\n url: string;\n description?: string;\n variables: Record<string, NormalizedServerVariable>;\n}\n\nexport interface NormalizedParameter {\n name: string;\n in: ParameterLocation;\n required: boolean;\n schema: JsonSchema;\n style?: string;\n explode?: boolean;\n description?: string;\n deprecated: boolean;\n}\n\nexport interface NormalizedMediaType {\n schema: JsonSchema;\n}\n\nexport interface NormalizedRequestBody {\n required: boolean;\n description?: string;\n content: Record<string, NormalizedMediaType>;\n}\n\nexport interface NormalizedHeader {\n schema: JsonSchema;\n description?: string;\n required?: boolean;\n deprecated?: boolean;\n}\n\nexport interface NormalizedResponse {\n statusCode: string;\n isSuccess: boolean;\n isError: boolean;\n description?: string;\n content: Record<string, NormalizedMediaType>;\n headers: Record<string, NormalizedHeader>;\n}\n\nexport interface NormalizedOperation {\n operationId: string;\n method: HttpMethod;\n path: string;\n tags: string[];\n summary?: string;\n description?: string;\n deprecated: boolean;\n parameters: NormalizedParameter[];\n requestBody?: NormalizedRequestBody;\n responses: NormalizedResponse[];\n security: SecurityRequirement[];\n}\n\nexport interface SecuritySchemeApiKey {\n type: 'apiKey';\n name: string;\n in: 'header' | 'query' | 'cookie';\n description?: string;\n}\n\nexport interface SecuritySchemeHttp {\n type: 'http';\n scheme: 'bearer' | 'basic' | string;\n bearerFormat?: string;\n description?: string;\n}\n\nexport interface OAuthFlow {\n authorizationUrl?: string;\n tokenUrl?: string;\n refreshUrl?: string;\n scopes: Record<string, string>;\n}\n\nexport interface SecuritySchemeOAuth2 {\n type: 'oauth2';\n flows: {\n implicit?: OAuthFlow;\n password?: OAuthFlow;\n clientCredentials?: OAuthFlow;\n authorizationCode?: OAuthFlow;\n };\n description?: string;\n}\n\nexport interface SecuritySchemeOpenIdConnect {\n type: 'openIdConnect';\n openIdConnectUrl: string;\n description?: string;\n}\n\nexport type SecurityScheme =\n | SecuritySchemeApiKey\n | SecuritySchemeHttp\n | SecuritySchemeOAuth2\n | SecuritySchemeOpenIdConnect;\n\n/** Map of scheme-name → required scopes. */\nexport type SecurityRequirement = Record<string, string[]>;\n\nexport interface NormalizedSpec {\n openapiVersion: string;\n info: SpecInfo;\n servers: NormalizedServer[];\n operations: NormalizedOperation[];\n schemas: Record<string, JsonSchema>;\n securitySchemes: Record<string, SecurityScheme>;\n}\n","import { readFile } from 'node:fs/promises';\nimport SwaggerParser from '@apidevtools/swagger-parser';\nimport YAML from 'yaml';\nimport type {\n HttpMethod,\n JsonSchema,\n NormalizedOperation,\n NormalizedParameter,\n NormalizedRequestBody,\n NormalizedResponse,\n NormalizedServer,\n NormalizedSpec,\n SecurityRequirement,\n SecurityScheme,\n SpecInfo,\n} from './types.js';\n\ntype UnknownRecord = Record<string, unknown>;\n\nconst HTTP_METHODS: readonly HttpMethod[] = [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'delete',\n 'head',\n 'options',\n 'trace',\n] as const;\n\nfunction isRecord(x: unknown): x is UnknownRecord {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\nfunction asString(x: unknown): string | undefined {\n return typeof x === 'string' ? x : undefined;\n}\n\nfunction asBool(x: unknown, fallback: boolean): boolean {\n return typeof x === 'boolean' ? x : fallback;\n}\n\nfunction asArray(x: unknown): unknown[] {\n return Array.isArray(x) ? x : [];\n}\n\nfunction asStringArray(x: unknown): string[] {\n return asArray(x).filter((v): v is string => typeof v === 'string');\n}\n\n/**\n * Load and normalize an OpenAPI 3.x spec from a file path, URL, or in-memory\n * object. YAML files (`.yaml` / `.yml`) are read manually with the `yaml`\n * library first so we always hand SwaggerParser a parsed object — this keeps\n * our behaviour identical for local files and in-memory inputs.\n */\nexport async function loadSpec(\n input: string | URL | object,\n): Promise<NormalizedSpec> {\n let raw: unknown;\n\n if (typeof input === 'string' && /\\.ya?ml$/i.test(input)) {\n const text = await readFile(input, 'utf8');\n raw = YAML.parse(text);\n } else if (input instanceof URL) {\n raw = input.toString();\n } else {\n raw = input;\n }\n\n // Pre-capture component schema names before dereferencing (which would\n // inline them and lose the named handles).\n const namedSchemas = extractComponentSchemas(raw);\n\n let validated: unknown;\n try {\n // SwaggerParser mutates the input; pass a clone when it's an object so\n // we don't pollute the caller's reference.\n const parserInput = typeof raw === 'string' ? raw : structuredClone(raw);\n validated = await (\n SwaggerParser.validate as (api: unknown) => Promise<unknown>\n )(parserInput);\n } catch (err) {\n throw formatValidationError(err);\n }\n\n const dereferenced = (await (\n SwaggerParser.dereference as (api: unknown) => Promise<unknown>\n )(validated)) as UnknownRecord;\n\n return normalizeSpec(dereferenced, namedSchemas);\n}\n\nfunction formatValidationError(err: unknown): Error {\n if (err instanceof Error) {\n const details = (err as Error & { details?: unknown }).details;\n if (Array.isArray(details) && details.length > 0) {\n const top = details\n .slice(0, 3)\n .map((d, i) => {\n const msg =\n isRecord(d) && typeof d.message === 'string'\n ? d.message\n : String(d);\n return ` ${i + 1}. ${msg}`;\n })\n .join('\\n');\n return new Error(`OpenAPI spec validation failed:\\n${top}`);\n }\n return new Error(`OpenAPI spec validation failed: ${err.message}`);\n }\n return new Error(`OpenAPI spec validation failed: ${String(err)}`);\n}\n\nfunction extractComponentSchemas(raw: unknown): Record<string, JsonSchema> {\n const out: Record<string, JsonSchema> = {};\n if (!isRecord(raw)) return out;\n const components = raw.components;\n if (!isRecord(components)) return out;\n const schemas = components.schemas;\n if (!isRecord(schemas)) return out;\n for (const [name, schema] of Object.entries(schemas)) {\n if (isRecord(schema)) {\n out[name] = schema as JsonSchema;\n }\n }\n return out;\n}\n\n/**\n * Normalize a (presumed-dereferenced) OpenAPI document into our internal\n * shape. Callers who already have a dereferenced spec may invoke this\n * directly.\n */\nexport function normalizeSpec(\n dereferenced: unknown,\n namedSchemas: Record<string, JsonSchema> = {},\n): NormalizedSpec {\n if (!isRecord(dereferenced)) {\n throw new Error('normalizeSpec: input must be an object');\n }\n\n const openapiVersion = asString(dereferenced.openapi) ?? '';\n const info = normalizeInfo(dereferenced.info);\n const servers = normalizeServers(dereferenced.servers);\n const securitySchemes = normalizeSecuritySchemes(\n isRecord(dereferenced.components)\n ? (dereferenced.components as UnknownRecord).securitySchemes\n : undefined,\n );\n const topLevelSecurity = normalizeSecurityRequirements(dereferenced.security);\n const operations = normalizeOperations(dereferenced.paths, topLevelSecurity);\n\n // Prefer the pre-captured named schemas (from before dereferencing) so the\n // original handles survive. Fall back to `components.schemas` from the\n // dereferenced tree when the caller didn't supply them.\n const schemas =\n Object.keys(namedSchemas).length > 0\n ? namedSchemas\n : extractComponentSchemas(dereferenced);\n\n return Object.freeze<NormalizedSpec>({\n openapiVersion,\n info,\n servers,\n operations,\n schemas,\n securitySchemes,\n });\n}\n\nfunction normalizeInfo(raw: unknown): SpecInfo {\n if (!isRecord(raw)) {\n return { title: '', version: '' };\n }\n const info: SpecInfo = {\n title: asString(raw.title) ?? '',\n version: asString(raw.version) ?? '',\n };\n const description = asString(raw.description);\n if (description !== undefined) info.description = description;\n const tos = asString(raw.termsOfService);\n if (tos !== undefined) info.termsOfService = tos;\n if (isRecord(raw.contact)) {\n const contact: SpecInfo['contact'] = {};\n const name = asString(raw.contact.name);\n if (name !== undefined) contact.name = name;\n const url = asString(raw.contact.url);\n if (url !== undefined) contact.url = url;\n const email = asString(raw.contact.email);\n if (email !== undefined) contact.email = email;\n info.contact = contact;\n }\n if (isRecord(raw.license)) {\n const license: NonNullable<SpecInfo['license']> = {\n name: asString(raw.license.name) ?? '',\n };\n const url = asString(raw.license.url);\n if (url !== undefined) license.url = url;\n const id = asString(raw.license.identifier);\n if (id !== undefined) license.identifier = id;\n info.license = license;\n }\n return info;\n}\n\nfunction normalizeServers(raw: unknown): NormalizedServer[] {\n return asArray(raw)\n .filter(isRecord)\n .map((s) => {\n const url = asString(s.url) ?? '';\n const variables: NormalizedServer['variables'] = {};\n if (isRecord(s.variables)) {\n for (const [k, v] of Object.entries(s.variables)) {\n if (!isRecord(v)) continue;\n const variable: NormalizedServer['variables'][string] = {\n default: asString(v.default) ?? '',\n };\n const enums = asStringArray(v.enum);\n if (enums.length > 0) variable.enum = enums;\n const desc = asString(v.description);\n if (desc !== undefined) variable.description = desc;\n variables[k] = variable;\n }\n }\n const server: NormalizedServer = { url, variables };\n const desc = asString(s.description);\n if (desc !== undefined) server.description = desc;\n return server;\n });\n}\n\nfunction normalizeSecuritySchemes(\n raw: unknown,\n): Record<string, SecurityScheme> {\n const out: Record<string, SecurityScheme> = {};\n if (!isRecord(raw)) return out;\n for (const [name, schemeRaw] of Object.entries(raw)) {\n if (!isRecord(schemeRaw)) continue;\n const type = asString(schemeRaw.type);\n const description = asString(schemeRaw.description);\n switch (type) {\n case 'apiKey': {\n const inLoc = asString(schemeRaw.in);\n if (inLoc !== 'header' && inLoc !== 'query' && inLoc !== 'cookie')\n continue;\n const scheme: SecurityScheme = {\n type: 'apiKey',\n name: asString(schemeRaw.name) ?? name,\n in: inLoc,\n };\n if (description !== undefined) scheme.description = description;\n out[name] = scheme;\n break;\n }\n case 'http': {\n const scheme: SecurityScheme = {\n type: 'http',\n scheme: asString(schemeRaw.scheme) ?? 'bearer',\n };\n const bf = asString(schemeRaw.bearerFormat);\n if (bf !== undefined) scheme.bearerFormat = bf;\n if (description !== undefined) scheme.description = description;\n out[name] = scheme;\n break;\n }\n case 'oauth2': {\n const flowsRaw = isRecord(schemeRaw.flows) ? schemeRaw.flows : {};\n const scheme: SecurityScheme = {\n type: 'oauth2',\n flows: {},\n };\n for (const flowName of [\n 'implicit',\n 'password',\n 'clientCredentials',\n 'authorizationCode',\n ] as const) {\n const f = flowsRaw[flowName];\n if (!isRecord(f)) continue;\n const flow: {\n authorizationUrl?: string;\n tokenUrl?: string;\n refreshUrl?: string;\n scopes: Record<string, string>;\n } = {\n scopes: {},\n };\n if (isRecord(f.scopes)) {\n for (const [k, v] of Object.entries(f.scopes)) {\n if (typeof v === 'string') flow.scopes[k] = v;\n }\n }\n const au = asString(f.authorizationUrl);\n if (au !== undefined) flow.authorizationUrl = au;\n const tu = asString(f.tokenUrl);\n if (tu !== undefined) flow.tokenUrl = tu;\n const ru = asString(f.refreshUrl);\n if (ru !== undefined) flow.refreshUrl = ru;\n scheme.flows[flowName] = flow;\n }\n if (description !== undefined) scheme.description = description;\n out[name] = scheme;\n break;\n }\n case 'openIdConnect': {\n const url = asString(schemeRaw.openIdConnectUrl);\n if (url === undefined) continue;\n const scheme: SecurityScheme = {\n type: 'openIdConnect',\n openIdConnectUrl: url,\n };\n if (description !== undefined) scheme.description = description;\n out[name] = scheme;\n break;\n }\n default:\n // Unsupported security scheme type — skip.\n break;\n }\n }\n return out;\n}\n\nfunction normalizeSecurityRequirements(raw: unknown): SecurityRequirement[] {\n return asArray(raw)\n .filter(isRecord)\n .map((req) => {\n const out: SecurityRequirement = {};\n for (const [k, v] of Object.entries(req)) {\n out[k] = asStringArray(v);\n }\n return out;\n });\n}\n\nfunction normalizeOperations(\n pathsRaw: unknown,\n topLevelSecurity: SecurityRequirement[],\n): NormalizedOperation[] {\n const ops: NormalizedOperation[] = [];\n if (!isRecord(pathsRaw)) return ops;\n\n // Iterate paths in insertion order for determinism.\n for (const [path, pathItemRaw] of Object.entries(pathsRaw)) {\n if (!isRecord(pathItemRaw)) continue;\n const pathLevelParams = normalizeParameters(pathItemRaw.parameters);\n\n for (const method of HTTP_METHODS) {\n const opRaw = pathItemRaw[method];\n if (!isRecord(opRaw)) continue;\n\n const opParams = normalizeParameters(opRaw.parameters);\n const parameters = mergeParameters(pathLevelParams, opParams);\n\n const operationId =\n asString(opRaw.operationId) ?? synthesizeOperationId(method, path);\n\n const op: NormalizedOperation = {\n operationId,\n method,\n path,\n tags: asStringArray(opRaw.tags),\n deprecated: asBool(opRaw.deprecated, false),\n parameters,\n responses: normalizeResponses(opRaw.responses),\n security:\n opRaw.security === undefined\n ? topLevelSecurity\n : normalizeSecurityRequirements(opRaw.security),\n };\n\n const summary = asString(opRaw.summary);\n if (summary !== undefined) op.summary = summary;\n const description = asString(opRaw.description);\n if (description !== undefined) op.description = description;\n\n const requestBody = normalizeRequestBody(opRaw.requestBody);\n if (requestBody !== undefined) op.requestBody = requestBody;\n\n ops.push(op);\n }\n }\n return ops;\n}\n\nfunction normalizeParameters(raw: unknown): NormalizedParameter[] {\n return asArray(raw)\n .filter(isRecord)\n .map((p) => {\n const inLoc = asString(p.in);\n if (\n inLoc !== 'path' &&\n inLoc !== 'query' &&\n inLoc !== 'header' &&\n inLoc !== 'cookie'\n ) {\n return undefined;\n }\n const name = asString(p.name);\n if (name === undefined) return undefined;\n\n const param: NormalizedParameter = {\n name,\n in: inLoc,\n required: inLoc === 'path' ? true : asBool(p.required, false),\n schema: isRecord(p.schema) ? (p.schema as JsonSchema) : {},\n deprecated: asBool(p.deprecated, false),\n };\n const style = asString(p.style);\n if (style !== undefined) param.style = style;\n if (typeof p.explode === 'boolean') param.explode = p.explode;\n const desc = asString(p.description);\n if (desc !== undefined) param.description = desc;\n return param;\n })\n .filter((p): p is NormalizedParameter => p !== undefined);\n}\n\nfunction mergeParameters(\n pathLevel: NormalizedParameter[],\n opLevel: NormalizedParameter[],\n): NormalizedParameter[] {\n const key = (p: NormalizedParameter) => `${p.in}:${p.name}`;\n const merged = new Map<string, NormalizedParameter>();\n for (const p of pathLevel) merged.set(key(p), p);\n for (const p of opLevel) merged.set(key(p), p); // op-level wins\n return [...merged.values()];\n}\n\nfunction normalizeRequestBody(raw: unknown): NormalizedRequestBody | undefined {\n if (!isRecord(raw)) return undefined;\n const content: NormalizedRequestBody['content'] = {};\n if (isRecord(raw.content)) {\n for (const [mt, mtRaw] of Object.entries(raw.content)) {\n if (!isRecord(mtRaw)) continue;\n content[mt] = {\n schema: isRecord(mtRaw.schema) ? (mtRaw.schema as JsonSchema) : {},\n };\n }\n }\n const body: NormalizedRequestBody = {\n required: asBool(raw.required, false),\n content,\n };\n const desc = asString(raw.description);\n if (desc !== undefined) body.description = desc;\n return body;\n}\n\nfunction normalizeResponses(raw: unknown): NormalizedResponse[] {\n if (!isRecord(raw)) return [];\n const entries = Object.entries(raw).filter(\n (entry): entry is [string, UnknownRecord] => isRecord(entry[1]),\n );\n const has2xx = entries.some(([code]) => /^2\\d\\d$/.test(code));\n return entries.map(([statusCode, respRaw]) => {\n const isSuccess =\n /^2\\d\\d$/.test(statusCode) || (statusCode === 'default' && !has2xx);\n const isError =\n /^(4|5)\\d\\d$/.test(statusCode) || (statusCode === 'default' && has2xx);\n\n const content: NormalizedResponse['content'] = {};\n if (isRecord(respRaw.content)) {\n for (const [mt, mtRaw] of Object.entries(respRaw.content)) {\n if (!isRecord(mtRaw)) continue;\n content[mt] = {\n schema: isRecord(mtRaw.schema) ? (mtRaw.schema as JsonSchema) : {},\n };\n }\n }\n\n const headers: NormalizedResponse['headers'] = {};\n if (isRecord(respRaw.headers)) {\n for (const [hn, hRaw] of Object.entries(respRaw.headers)) {\n if (!isRecord(hRaw)) continue;\n const header: NormalizedResponse['headers'][string] = {\n schema: isRecord(hRaw.schema) ? (hRaw.schema as JsonSchema) : {},\n };\n const desc = asString(hRaw.description);\n if (desc !== undefined) header.description = desc;\n if (typeof hRaw.required === 'boolean') header.required = hRaw.required;\n if (typeof hRaw.deprecated === 'boolean')\n header.deprecated = hRaw.deprecated;\n headers[hn] = header;\n }\n }\n\n const resp: NormalizedResponse = {\n statusCode,\n isSuccess,\n isError,\n content,\n headers,\n };\n const desc = asString(respRaw.description);\n if (desc !== undefined) resp.description = desc;\n return resp;\n });\n}\n\nfunction synthesizeOperationId(method: HttpMethod, path: string): string {\n // Explicit character-by-character sanitization avoids super-linear regex\n // backtracking risks (Sonar `typescript:S5852`).\n const out: string[] = [];\n let underscore = false;\n let braceDepth = 0;\n for (const ch of path) {\n if (ch === '{') {\n braceDepth += 1;\n continue;\n }\n if (ch === '}') {\n if (braceDepth > 0) braceDepth -= 1;\n continue;\n }\n const isAlnum =\n (ch >= 'A' && ch <= 'Z') ||\n (ch >= 'a' && ch <= 'z') ||\n (ch >= '0' && ch <= '9');\n if (isAlnum) {\n out.push(ch);\n underscore = false;\n } else if (!underscore) {\n out.push('_');\n underscore = true;\n }\n }\n // Trim leading/trailing underscores.\n let start = 0;\n let end = out.length;\n while (start < end && out[start] === '_') start += 1;\n while (end > start && out[end - 1] === '_') end -= 1;\n return `${method}_${out.slice(start, end).join('')}`;\n}\n","import { createHash } from 'node:crypto';\n\nexport type IdentKind = 'type' | 'method' | 'param' | 'class';\n\nexport interface SanitizeOpts {\n prefix?: string;\n maxLen?: number;\n}\n\nconst DEFAULT_MAX_LEN = 30;\n\n/** Split an identifier on camelCase boundaries, non-alnum runs, and digits-prev-letter. */\nfunction splitWords(raw: string): string[] {\n if (!raw) return [];\n const cleaned = raw.replaceAll(/[^A-Za-z0-9]+/g, ' ').trim();\n if (!cleaned) return [];\n // Split on spaces, then further split on camelCase within each token.\n const tokens = cleaned.split(/\\s+/);\n const out: string[] = [];\n for (const tok of tokens) {\n // Insert spaces before uppercase runs: \"HTTPServer\" -> \"HTTP Server\", \"camelCase\" -> \"camel Case\".\n // Using lookahead-only patterns (no overlapping quantifiers) keeps regex\n // evaluation linear-time (CodeQL `js/polynomial-redos`).\n const spaced = tok\n .replaceAll(/([A-Z])(?=[A-Z][a-z])/g, '$1 ')\n .replaceAll(/([a-z0-9])(?=[A-Z])/g, '$1 ');\n for (const part of spaced.split(/\\s+/)) {\n if (part) out.push(part);\n }\n }\n return out;\n}\n\nfunction shortHash(raw: string, len = 4): string {\n return createHash('sha256').update(raw).digest('hex').slice(0, len);\n}\n\n/** Sanitize a raw identifier into an ABAP-safe name. */\nexport function sanitizeIdent(\n raw: string,\n kind: IdentKind,\n opts: SanitizeOpts = {},\n): string {\n const maxLen = opts.maxLen ?? DEFAULT_MAX_LEN;\n const prefix = opts.prefix ?? '';\n const words = splitWords(raw);\n const joiner = '_';\n let base: string;\n if (kind === 'class') {\n base = words.map((w) => w.toUpperCase()).join(joiner);\n } else {\n base = words.map((w) => w.toLowerCase()).join(joiner);\n }\n if (!base) {\n base = kind === 'class' ? 'X' : 'x';\n }\n // Identifiers cannot start with a digit.\n if (/^[0-9]/.test(base)) {\n base = (kind === 'class' ? 'N_' : 'n_') + base;\n }\n let full = prefix + base;\n if (full.length > maxLen) {\n const hash = shortHash(raw, 4);\n const suffix = '_' + hash;\n full = full.slice(0, Math.max(0, maxLen - suffix.length)) + suffix;\n }\n return full;\n}\n\nexport type NameAllocator = (\n raw: string,\n kind: IdentKind,\n opts?: SanitizeOpts,\n) => string;\n\n/** Create a collision-resolving allocator bound to a mutable name set. */\nexport function makeNameAllocator(usedNames: Set<string>): NameAllocator {\n return (raw, kind, opts = {}) => {\n const maxLen = opts.maxLen ?? DEFAULT_MAX_LEN;\n const base = sanitizeIdent(raw, kind, opts);\n if (!usedNames.has(base)) {\n usedNames.add(base);\n return base;\n }\n for (let i = 2; i < 10_000; i++) {\n const suffix = '_' + i;\n const head = base.slice(0, Math.max(0, maxLen - suffix.length));\n const candidate = head + suffix;\n if (!usedNames.has(candidate)) {\n usedNames.add(candidate);\n return candidate;\n }\n }\n throw new Error(\n `makeNameAllocator: unable to resolve collision for \"${raw}\"`,\n );\n };\n}\n","export class CyclicTypeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CyclicTypeError';\n }\n}\n\nexport class CollisionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CollisionError';\n }\n}\n\nexport class UnsupportedSchemaError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UnsupportedSchemaError';\n }\n}\n","import type { JsonSchema, NormalizedSpec } from '../oas/index';\nimport { isRef } from '../oas/index';\nimport { makeNameAllocator } from './naming';\nimport { CyclicTypeError } from './errors';\n\nexport interface TypePlanEntry {\n /** Stable logical id, e.g. \"components.schemas.Pet\" or \"components.schemas.Pet.properties.x\". */\n readonly id: string;\n /** ABAP type name (ty_foo). */\n readonly abapName: string;\n /** Original JSON schema object. */\n readonly schema: JsonSchema;\n /** Logical ids of other plan entries this one depends on. */\n readonly dependencies: readonly string[];\n /** Where the entry comes from. */\n readonly source: 'component' | 'inline' | 'auxiliary';\n /** True when the entry participates in a self-reference (directly or indirectly via itself). */\n readonly selfReferential?: boolean;\n}\n\nexport interface TypePlan {\n readonly entries: readonly TypePlanEntry[];\n readonly byId: ReadonlyMap<string, TypePlanEntry>;\n}\n\nexport interface PlanTypesOptions {\n /** ABAP prefix applied to every emitted type name, e.g. \"zps3_\" → ty names become ty_zps3_pet. We use it as-is, joined with snake name. */\n typePrefix: string;\n}\n\ninterface MutableEntry {\n id: string;\n abapName: string;\n schema: JsonSchema;\n dependencies: string[];\n source: 'component' | 'inline' | 'auxiliary';\n selfReferential?: boolean;\n}\n\nfunction isRecord(x: unknown): x is Record<string, unknown> {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\n/** Extract component schema name from a $ref like \"#/components/schemas/Pet\". */\nfunction componentNameFromRef(ref: string): string | undefined {\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n return m ? m[1] : undefined;\n}\n\n/** Decide if a (non-ref) schema should get its own plan entry when encountered inline. */\nfunction isNonTrivialInline(schema: JsonSchema): boolean {\n if (isRef(schema)) return false;\n const type = (schema as { type?: unknown }).type;\n const props = (schema as { properties?: unknown }).properties;\n if (type === 'object' || isRecord(props)) return isRecord(props);\n for (const c of ['allOf', 'oneOf', 'anyOf'] as const) {\n if (Array.isArray((schema as Record<string, unknown>)[c])) return true;\n }\n return false;\n}\n\n/** Walk a single schema (rooted at `rootId`) to collect:\n * - direct dependencies on other entries (by id)\n * - inline entries that must be allocated.\n *\n * Descends into properties / items / combinators / additionalProperties.\n */\nfunction collectFromSchema(\n rootId: string,\n rootSchema: JsonSchema,\n plannedIds: Set<string>,\n enqueueInline: (id: string, schema: JsonSchema) => void,\n schemaToId: Map<object, string>,\n): string[] {\n const deps = new Set<string>();\n\n const visit = (schema: unknown, path: string[], atRoot: boolean): void => {\n if (!isRecord(schema)) return;\n if (isRef(schema)) {\n const name = componentNameFromRef(schema.$ref);\n if (name) {\n const depId = `components.schemas.${name}`;\n deps.add(depId);\n }\n return;\n }\n // Non-root: if this schema object IS one of the planned component schemas\n // (same reference — common after $ref dereferencing), treat as a dep and\n // stop descent.\n if (!atRoot) {\n const hitId = schemaToId.get(schema);\n if (hitId && hitId !== rootId) {\n deps.add(hitId);\n return;\n }\n if (hitId === rootId) {\n // Self-reference via identity.\n deps.add(rootId);\n return;\n }\n }\n // Non-root, non-ref, non-trivial object → allocate a dedicated inline entry.\n if (!atRoot && isNonTrivialInline(schema as JsonSchema)) {\n const id = `${rootId}.${path.join('.')}`;\n if (!plannedIds.has(id)) {\n enqueueInline(id, schema as JsonSchema);\n schemaToId.set(schema, id);\n }\n deps.add(id);\n return;\n }\n\n // Otherwise, keep descending to find refs / nested inline types.\n const rec = schema;\n if (isRecord(rec.properties)) {\n for (const [name, sub] of Object.entries(rec.properties)) {\n visit(sub, [...path, 'properties', name], false);\n }\n }\n if (rec.items !== undefined) {\n visit(rec.items, [...path, 'items'], false);\n }\n if (isRecord(rec.additionalProperties)) {\n visit(rec.additionalProperties, [...path, 'additionalProperties'], false);\n }\n for (const c of ['allOf', 'anyOf', 'oneOf'] as const) {\n const arr = rec[c];\n if (Array.isArray(arr)) {\n arr.forEach((sub, idx) => {\n visit(sub, [...path, c, String(idx)], false);\n });\n }\n }\n };\n\n visit(rootSchema, [], true);\n return [...deps];\n}\n\n/** Plan the ABAP type universe for a normalized spec. */\nexport function planTypes(\n spec: NormalizedSpec,\n opts: PlanTypesOptions,\n): TypePlan {\n const used = new Set<string>();\n const alloc = makeNameAllocator(used);\n const entries: MutableEntry[] = [];\n const byId = new Map<string, MutableEntry>();\n const plannedIds = new Set<string>();\n const schemaToId = new Map<object, string>();\n const queue: Array<{\n id: string;\n schema: JsonSchema;\n source: MutableEntry['source'];\n }> = [];\n\n const enqueue = (\n id: string,\n schema: JsonSchema,\n source: MutableEntry['source'],\n ) => {\n if (plannedIds.has(id)) return;\n plannedIds.add(id);\n schemaToId.set(schema, id);\n queue.push({ id, schema, source });\n };\n\n // 1) Seed queue with named component schemas.\n for (const [name, schema] of Object.entries(spec.schemas)) {\n enqueue(`components.schemas.${name}`, schema, 'component');\n }\n\n // 2) Process queue; inline children discovered during collection will be\n // appended here and processed in order.\n while (queue.length > 0) {\n const item = queue.shift()!;\n const rawName = inferRawName(item.id, item.source);\n const abapName = alloc(rawName, 'type', {\n prefix: 'ty_' + (opts.typePrefix ?? ''),\n });\n const entry: MutableEntry = {\n id: item.id,\n abapName,\n schema: item.schema,\n dependencies: [],\n source: item.source,\n };\n entries.push(entry);\n byId.set(item.id, entry);\n\n const deps = collectFromSchema(\n item.id,\n item.schema,\n plannedIds,\n (id, schema) => {\n enqueue(id, schema, 'inline');\n },\n schemaToId,\n );\n entry.dependencies = deps;\n }\n\n // 3) additionalProperties auxiliary: if any entry uses additionalProperties,\n // register a shared ty_kv entry exactly once.\n const needsKv = entries.some((e) => hasOpenAdditional(e.schema));\n if (needsKv) {\n const kvId = 'aux.kv';\n const kvName = alloc('kv', 'type', {\n prefix: 'ty_' + (opts.typePrefix ?? ''),\n });\n const kvEntry: MutableEntry = {\n id: kvId,\n abapName: kvName,\n schema: {\n type: 'object',\n properties: {\n key: { type: 'string' },\n value: { type: 'string' },\n },\n },\n dependencies: [],\n source: 'auxiliary',\n };\n entries.push(kvEntry);\n byId.set(kvId, kvEntry);\n }\n\n // 4) Topological sort with self-reference tolerance.\n const sorted = topoSort(entries);\n\n return {\n entries: Object.freeze(\n sorted.map((e) =>\n Object.freeze({\n ...e,\n dependencies: Object.freeze([...e.dependencies]),\n }),\n ),\n ),\n byId: new Map(\n sorted.map((e) => [\n e.id,\n {\n ...e,\n dependencies: Object.freeze([...e.dependencies]) as readonly string[],\n } as TypePlanEntry,\n ]),\n ),\n };\n}\n\nfunction hasOpenAdditional(schema: JsonSchema): boolean {\n const ap = (schema as Record<string, unknown>).additionalProperties;\n if (ap === true) return true;\n if (isRecord(ap)) return true;\n return false;\n}\n\nfunction inferRawName(id: string, source: MutableEntry['source']): string {\n if (source === 'component') {\n const m = /^components\\.schemas\\.(.+)$/.exec(id);\n return m ? m[1] : id;\n }\n if (source === 'auxiliary') {\n const m = /^aux\\.(.+)$/.exec(id);\n return m ? m[1] : id;\n }\n // Inline: use last two path segments joined.\n const parts = id\n .split('.')\n .filter((p) => p && p !== 'properties' && p !== 'items');\n return parts.slice(-2).join('_') || id;\n}\n\nfunction topoSort(entries: MutableEntry[]): MutableEntry[] {\n const byId = new Map(entries.map((e) => [e.id, e]));\n const out: MutableEntry[] = [];\n const state = new Map<string, 'white' | 'gray' | 'black'>();\n for (const e of entries) state.set(e.id, 'white');\n\n const visit = (id: string, stack: string[]): void => {\n const s = state.get(id);\n if (s === 'black') return;\n const entry = byId.get(id);\n if (!entry) return; // dependency points outside the plan (shouldn't happen)\n if (s === 'gray') {\n // Mark participants as self-referential.\n const cycleStart = stack.indexOf(id);\n const cycle = cycleStart >= 0 ? stack.slice(cycleStart) : [id];\n if (cycle.length === 1) {\n // simple self-reference — allow.\n entry.selfReferential = true;\n return;\n }\n // Mark all participants as self-referential (indirect cycle) and allow\n // — the emitter will insert a TYPE REF TO indirection for the back edge.\n for (const pid of cycle) {\n const ent = byId.get(pid);\n if (ent) ent.selfReferential = true;\n }\n return;\n }\n state.set(id, 'gray');\n stack.push(id);\n for (const dep of entry.dependencies) {\n if (dep === id) {\n entry.selfReferential = true;\n continue;\n }\n if (!byId.has(dep)) continue;\n const depState = state.get(dep);\n if (depState === 'gray') {\n // back-edge → mark cycle participants.\n const cycleStart = stack.indexOf(dep);\n const cycle = cycleStart >= 0 ? stack.slice(cycleStart) : [dep];\n for (const pid of [...cycle, id]) {\n const ent = byId.get(pid);\n if (ent) ent.selfReferential = true;\n }\n continue;\n }\n visit(dep, stack);\n }\n stack.pop();\n state.set(id, 'black');\n out.push(entry);\n };\n\n for (const e of entries) visit(e.id, []);\n // Sanity: every entry must be in `out`.\n if (out.length !== entries.length) {\n throw new CyclicTypeError(\n `planTypes: unable to topologically sort ${entries.length} entries (got ${out.length}).`,\n );\n }\n return out;\n}\n","import {\n builtinType,\n comment,\n enumType,\n namedTypeRef,\n structureType,\n tableType,\n typeDef,\n type BuiltinTypeName,\n type Comment,\n type EnumMember,\n type StructureField,\n type TypeDef,\n type TypeRef,\n} from '@abapify/abap-ast';\nimport type { JsonSchema } from '../oas/index';\nimport { isRef } from '../oas/index';\nimport type { TypePlan, TypePlanEntry } from './plan';\nimport { CollisionError, UnsupportedSchemaError } from './errors';\nimport { sanitizeIdent } from './naming';\n\nfunction isRecord(x: unknown): x is Record<string, unknown> {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\n/** Map a JSON Schema primitive (type+format) to an ABAP builtin type name. */\nexport function mapPrimitive(schema: JsonSchema): BuiltinTypeName {\n const type = (schema as { type?: unknown }).type;\n const format = (schema as { format?: unknown }).format;\n if (type === 'boolean') return 'abap_bool';\n if (type === 'integer') {\n return format === 'int64' ? 'int8' : 'i';\n }\n if (type === 'number') {\n return format === 'float' || format === 'double' ? 'f' : 'decfloat34';\n }\n if (type === 'string') {\n switch (format) {\n case 'date':\n return 'd';\n case 'date-time':\n return 'timestampl';\n case 'uuid':\n return 'sysuuid_x16';\n case 'byte':\n case 'binary':\n return 'xstring';\n default:\n return 'string';\n }\n }\n // Unknown: fallback to string.\n return 'string';\n}\n\nfunction refToEntry(ref: string, plan: TypePlan): TypePlanEntry | undefined {\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n if (!m) return undefined;\n return plan.byId.get(`components.schemas.${m[1]}`);\n}\n\nfunction pluckType(schema: JsonSchema): string | undefined {\n const t = (schema as { type?: unknown }).type;\n if (typeof t === 'string') return t;\n if (Array.isArray(t)) {\n const nonNull = t.filter((x): x is string => x !== 'null');\n if (nonNull.length >= 1) return nonNull[0];\n }\n return undefined;\n}\n\nfunction isNullable(schema: JsonSchema): boolean {\n const rec = schema as Record<string, unknown>;\n if (rec.nullable === true) return true;\n const t = rec.type;\n if (Array.isArray(t) && t.includes('null')) return true;\n return false;\n}\n\n/** Resolve a schema to an ABAP TypeRef. */\nexport function mapSchemaToTypeRef(\n schema: JsonSchema,\n plan: TypePlan,\n ctx: { entryId?: string } = {},\n): TypeRef {\n if (isRef(schema)) {\n const entry = refToEntry(schema.$ref, plan);\n if (!entry) {\n throw new UnsupportedSchemaError(\n `mapSchemaToTypeRef: unresolved $ref \"${schema.$ref}\"`,\n );\n }\n return namedTypeRef({ name: entry.abapName });\n }\n const type = pluckType(schema);\n // enum on string-like scalar → points to named entry when one exists; otherwise base string.\n if (type === 'array') {\n const items = (schema as { items?: unknown }).items;\n const rowSchema: JsonSchema = isRecord(items) ? (items as JsonSchema) : {};\n return tableType({\n rowType: mapSchemaToTypeRef(rowSchema, plan, ctx),\n tableKind: 'standard',\n });\n }\n if (\n type === 'object' ||\n isRecord((schema as { properties?: unknown }).properties)\n ) {\n // Prefer a planned entry for this exact schema if one exists.\n const matched = findPlannedEntryBySchema(schema, plan, ctx.entryId);\n if (matched) return namedTypeRef({ name: matched.abapName });\n // Inline structure as fallback.\n const fields = buildStructureFields(schema, plan, ctx);\n if (fields.length === 0) {\n return builtinType({ name: 'string' });\n }\n return structureType({ fields });\n }\n if (type === undefined) {\n // Untyped schema — unless combinator present.\n for (const c of ['allOf', 'oneOf', 'anyOf'] as const) {\n if (Array.isArray((schema as Record<string, unknown>)[c])) {\n // Treat as object; let typedef emission handle full shape.\n const matched = findPlannedEntryBySchema(schema, plan, ctx.entryId);\n if (matched) return namedTypeRef({ name: matched.abapName });\n return builtinType({ name: 'string' });\n }\n }\n return builtinType({ name: 'string' });\n }\n return builtinType({ name: mapPrimitive(schema) });\n}\n\n/** If a schema is identical-by-reference to a planned entry, return it. */\nfunction findPlannedEntryBySchema(\n schema: JsonSchema,\n plan: TypePlan,\n excludeId: string | undefined,\n): TypePlanEntry | undefined {\n for (const entry of plan.entries) {\n if (entry.id === excludeId) continue;\n if (entry.schema === schema) return entry;\n }\n return undefined;\n}\n\nfunction buildEnumMembers(values: readonly unknown[]): EnumMember[] {\n const out: EnumMember[] = [];\n for (const v of values) {\n if (typeof v === 'string') {\n const name = sanitizeIdent(v, 'type');\n out.push({ name, value: v });\n } else if (typeof v === 'number') {\n out.push({ name: sanitizeIdent(`v_${v}`, 'type'), value: v });\n }\n }\n return out;\n}\n\n/** Build the list of structure fields for an object-like schema, including\n * combinators, nullable flags, and additionalProperties escape hatch. */\nfunction buildStructureFields(\n schema: JsonSchema,\n plan: TypePlan,\n ctx: { entryId?: string },\n): StructureField[] {\n const fields: StructureField[] = [];\n const seen = new Map<string, TypeRef>();\n\n const addField = (name: string, type: TypeRef, src: JsonSchema) => {\n const sanitized = sanitizeIdent(name, 'param');\n const prev = seen.get(sanitized);\n if (prev) {\n // Only allow dedupe if structurally identical (by reference or same kind+name).\n if (prev === type || shallowTypeRefEqual(prev, type)) return;\n throw new CollisionError(\n `buildStructureFields: duplicate field \"${sanitized}\" with conflicting types`,\n );\n }\n seen.set(sanitized, type);\n fields.push({ name: sanitized, type });\n if (isNullable(src)) {\n const flagName = sanitizeIdent(`${name}_is_null`, 'param');\n if (!seen.has(flagName)) {\n const flagType = builtinType({ name: 'abap_bool' });\n seen.set(flagName, flagType);\n fields.push({ name: flagName, type: flagType });\n }\n }\n };\n\n // 1) allOf merging.\n const allOf = (schema as { allOf?: unknown }).allOf;\n if (Array.isArray(allOf)) {\n for (const sub of allOf) {\n if (!isRecord(sub)) continue;\n const subSchema = sub as JsonSchema;\n const subProps = isRef(subSchema)\n ? ((): Record<string, unknown> | undefined => {\n const entry = refToEntry(subSchema.$ref, plan);\n if (!entry) return undefined;\n return (entry.schema as { properties?: Record<string, unknown> })\n .properties;\n })()\n : (subSchema as { properties?: Record<string, unknown> }).properties;\n if (isRecord(subProps)) {\n for (const [name, propSchema] of Object.entries(subProps)) {\n if (!isRecord(propSchema)) continue;\n addField(\n name,\n mapSchemaToTypeRef(propSchema as JsonSchema, plan, ctx),\n propSchema as JsonSchema,\n );\n }\n }\n }\n }\n\n // 2) Own properties.\n const props = (schema as { properties?: unknown }).properties;\n if (isRecord(props)) {\n for (const [name, propSchema] of Object.entries(props)) {\n if (!isRecord(propSchema)) continue;\n addField(\n name,\n mapSchemaToTypeRef(propSchema as JsonSchema, plan, ctx),\n propSchema as JsonSchema,\n );\n }\n }\n\n // 3) oneOf / anyOf.\n for (const combinator of ['oneOf', 'anyOf'] as const) {\n const arr = (schema as Record<string, unknown>)[combinator];\n if (!Array.isArray(arr)) continue;\n const discriminator = (schema as { discriminator?: unknown }).discriminator;\n if (\n isRecord(discriminator) &&\n typeof discriminator.propertyName === 'string'\n ) {\n // Tagged shape: kind TYPE string + one field per variant.\n addFieldRaw(fields, seen, 'kind', builtinType({ name: 'string' }));\n arr.forEach((sub, idx) => {\n if (!isRecord(sub)) return;\n const variantName = variantFieldName(sub as JsonSchema, idx);\n addFieldRaw(\n fields,\n seen,\n variantName,\n mapSchemaToTypeRef(sub as JsonSchema, plan, ctx),\n );\n });\n } else {\n // Fallback: variant_kind string + one field per candidate + _is_set flag.\n addFieldRaw(\n fields,\n seen,\n 'variant_kind',\n builtinType({ name: 'string' }),\n );\n arr.forEach((sub, idx) => {\n if (!isRecord(sub)) return;\n const variantName = variantFieldName(sub as JsonSchema, idx);\n addFieldRaw(\n fields,\n seen,\n variantName,\n mapSchemaToTypeRef(sub as JsonSchema, plan, ctx),\n );\n addFieldRaw(\n fields,\n seen,\n `${variantName}_is_set`,\n builtinType({ name: 'abap_bool' }),\n );\n });\n }\n }\n\n // 4) additionalProperties escape hatch.\n const ap = (schema as { additionalProperties?: unknown })\n .additionalProperties;\n if (ap === true || isRecord(ap)) {\n const kvEntry = plan.byId.get('aux.kv');\n if (kvEntry) {\n addFieldRaw(\n fields,\n seen,\n '_extra',\n tableType({\n rowType: namedTypeRef({ name: kvEntry.abapName }),\n tableKind: 'hashed',\n uniqueness: 'unique',\n keyFields: ['key'],\n }),\n );\n }\n }\n\n return fields;\n}\n\nfunction addFieldRaw(\n fields: StructureField[],\n seen: Map<string, TypeRef>,\n rawName: string,\n type: TypeRef,\n): void {\n const name = sanitizeIdent(rawName, 'param');\n if (seen.has(name)) return;\n seen.set(name, type);\n fields.push({ name, type });\n}\n\nfunction shallowTypeRefEqual(a: TypeRef, b: TypeRef): boolean {\n if (a.kind !== b.kind) return false;\n if (a.kind === 'BuiltinType' && b.kind === 'BuiltinType') {\n return a.name === b.name;\n }\n if (a.kind === 'NamedTypeRef' && b.kind === 'NamedTypeRef') {\n return a.name === b.name;\n }\n return false;\n}\n\nfunction variantFieldName(sub: JsonSchema, idx: number): string {\n if (isRef(sub)) {\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(sub.$ref);\n if (m) return m[1];\n }\n const title = (sub as { title?: unknown }).title;\n if (typeof title === 'string' && title) return title;\n return `variant_${idx}`;\n}\n\n/** Build a TypeDef node for a single plan entry. */\nexport function mapSchemaToTypeDef(\n entry: TypePlanEntry,\n plan: TypePlan,\n): { typeDef: TypeDef; leadingComment?: Comment } {\n const schema = entry.schema;\n const ctx = { entryId: entry.id };\n\n // Enum shortcut: string with enum values.\n const enumValues = (schema as { enum?: unknown }).enum;\n const schemaType = pluckType(schema);\n if (\n Array.isArray(enumValues) &&\n (schemaType === 'string' || schemaType === undefined)\n ) {\n const members = buildEnumMembers(enumValues);\n if (members.length > 0) {\n return {\n typeDef: typeDef({\n name: entry.abapName,\n type: enumType({\n baseType: builtinType({ name: 'string' }),\n members,\n }),\n }),\n };\n }\n }\n\n // Array alias.\n if (schemaType === 'array') {\n const items = (schema as { items?: unknown }).items;\n const rowSchema: JsonSchema = isRecord(items) ? (items as JsonSchema) : {};\n return {\n typeDef: typeDef({\n name: entry.abapName,\n type: tableType({\n rowType: mapSchemaToTypeRef(rowSchema, plan, ctx),\n tableKind: 'standard',\n }),\n }),\n };\n }\n\n // Object / combinator.\n const hasObjectShape =\n schemaType === 'object' ||\n isRecord((schema as { properties?: unknown }).properties) ||\n Array.isArray((schema as { allOf?: unknown }).allOf) ||\n Array.isArray((schema as { oneOf?: unknown }).oneOf) ||\n Array.isArray((schema as { anyOf?: unknown }).anyOf);\n\n if (hasObjectShape) {\n const fields = buildStructureFields(schema, plan, ctx);\n const struct =\n fields.length > 0\n ? structureType({ fields })\n : structureType({\n fields: [\n {\n name: '_placeholder',\n type: builtinType({ name: 'string' }),\n },\n ],\n });\n const discriminator = (schema as { discriminator?: unknown }).discriminator;\n const leadingComment =\n Array.isArray((schema as { oneOf?: unknown }).oneOf) &&\n isRecord(discriminator)\n ? comment({\n text: ` Tagged union: only one variant field is populated at a time (kind discriminator).`,\n style: 'star',\n })\n : undefined;\n return {\n typeDef: typeDef({ name: entry.abapName, type: struct }),\n leadingComment,\n };\n }\n\n // Primitive alias.\n return {\n typeDef: typeDef({\n name: entry.abapName,\n type: builtinType({ name: mapPrimitive(schema) }),\n }),\n };\n}\n","/**\n * Central name derivation for the v2 openai-codegen emitter pipeline.\n *\n * Each OpenAPI spec emits four global ABAP artifacts:\n * 1. Types interface (ZIF_<BASE>_TYPES)\n * 2. Operations interface (ZIF_<BASE>)\n * 3. Exception class (ZCX_<BASE>_ERROR)\n * 4. Implementation class (ZCL_<BASE>)\n *\n * Plus a handful of local helper classes bundled inside the implementation\n * class (lcl_http, lcl_response, json, lcl_json_parser).\n *\n * All names are overridable individually; the simplest path is to provide a\n * single `base` name from which the four global names are derived.\n */\n\nexport interface NamesConfig {\n /** Logical base name — defaults become ZCL_<upper>, ZIF_<upper>, etc. */\n base?: string;\n /** Override each individually (takes precedence over base-derived). */\n typesInterface?: string;\n operationsInterface?: string;\n implementationClass?: string;\n exceptionClass?: string;\n /** Local class names bundled inside zcl_<name>. */\n localHttpClass?: string;\n localResponseClass?: string;\n localJsonClass?: string;\n localJsonParserClass?: string;\n}\n\nexport interface ResolvedNames {\n typesInterface: string;\n operationsInterface: string;\n implementationClass: string;\n exceptionClass: string;\n localHttpClass: string;\n localResponseClass: string;\n localJsonClass: string;\n localJsonParserClass: string;\n}\n\nexport class NamesConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NamesConfigError';\n }\n}\n\nconst GLOBAL_NAME_RE = /^[ZY][A-Z0-9_]*$/;\nconst LOCAL_NAME_RE = /^[a-z][a-z0-9_]*$/;\nconst MAX_LEN = 30;\n\nconst DEFAULT_LOCAL_HTTP = 'lcl_http';\nconst DEFAULT_LOCAL_RESPONSE = 'lcl_response';\nconst DEFAULT_LOCAL_JSON = 'json';\nconst DEFAULT_LOCAL_JSON_PARSER = 'lcl_json_parser';\n\nfunction validateGlobal(field: keyof ResolvedNames, value: string): void {\n if (value.length === 0) {\n throw new NamesConfigError(\n `Invalid ABAP global name for \"${field}\": value is empty.`,\n );\n }\n if (value.length > MAX_LEN) {\n throw new NamesConfigError(\n `Invalid ABAP global name for \"${field}\": \"${value}\" exceeds ${MAX_LEN} characters.`,\n );\n }\n if (!GLOBAL_NAME_RE.test(value)) {\n throw new NamesConfigError(\n `Invalid ABAP global name for \"${field}\": \"${value}\" must start with Z or Y and contain only uppercase letters, digits, and underscores.`,\n );\n }\n}\n\nfunction validateLocal(field: keyof ResolvedNames, value: string): void {\n if (value.length === 0) {\n throw new NamesConfigError(\n `Invalid ABAP local class name for \"${field}\": value is empty.`,\n );\n }\n if (value.length > MAX_LEN) {\n throw new NamesConfigError(\n `Invalid ABAP local class name for \"${field}\": \"${value}\" exceeds ${MAX_LEN} characters.`,\n );\n }\n if (!LOCAL_NAME_RE.test(value)) {\n throw new NamesConfigError(\n `Invalid ABAP local class name for \"${field}\": \"${value}\" must start with a lowercase letter and contain only lowercase letters, digits, and underscores.`,\n );\n }\n}\n\nfunction deriveFromBase(base: string): {\n typesInterface: string;\n operationsInterface: string;\n implementationClass: string;\n exceptionClass: string;\n} {\n const trimmed = base.trim();\n if (trimmed.length === 0) {\n throw new NamesConfigError(\n 'Invalid \"base\" name: value is empty or whitespace.',\n );\n }\n // Permit letters/digits/underscore in the base; we'll uppercase it.\n if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(trimmed)) {\n throw new NamesConfigError(\n `Invalid \"base\" name: \"${base}\" must start with a letter and contain only letters, digits, and underscores.`,\n );\n }\n const upper = trimmed.toUpperCase();\n return {\n typesInterface: `ZIF_${upper}_TYPES`,\n operationsInterface: `ZIF_${upper}`,\n implementationClass: `ZCL_${upper}`,\n exceptionClass: `ZCX_${upper}_ERROR`,\n };\n}\n\nexport function resolveNames(config?: NamesConfig): ResolvedNames {\n const cfg = config ?? {};\n\n const hasBase = typeof cfg.base === 'string' && cfg.base.trim().length > 0;\n const hasAnyGlobalOverride =\n cfg.typesInterface !== undefined ||\n cfg.operationsInterface !== undefined ||\n cfg.implementationClass !== undefined ||\n cfg.exceptionClass !== undefined;\n\n if (!hasBase && !hasAnyGlobalOverride) {\n throw new NamesConfigError(\n 'Names configuration requires at least \"base\" or one of the individual overrides ' +\n '(typesInterface, operationsInterface, implementationClass, exceptionClass).',\n );\n }\n\n const derived = hasBase\n ? deriveFromBase(cfg.base as string)\n : {\n typesInterface: '',\n operationsInterface: '',\n implementationClass: '',\n exceptionClass: '',\n };\n\n const typesInterface = (cfg.typesInterface ?? derived.typesInterface).trim();\n const operationsInterface = (\n cfg.operationsInterface ?? derived.operationsInterface\n ).trim();\n const implementationClass = (\n cfg.implementationClass ?? derived.implementationClass\n ).trim();\n const exceptionClass = (cfg.exceptionClass ?? derived.exceptionClass).trim();\n\n if (!typesInterface) {\n throw new NamesConfigError(\n 'Cannot resolve \"typesInterface\": provide --base or --types-interface.',\n );\n }\n if (!operationsInterface) {\n throw new NamesConfigError(\n 'Cannot resolve \"operationsInterface\": provide --base or --operations-interface.',\n );\n }\n if (!implementationClass) {\n throw new NamesConfigError(\n 'Cannot resolve \"implementationClass\": provide --base or --class-name.',\n );\n }\n if (!exceptionClass) {\n throw new NamesConfigError(\n 'Cannot resolve \"exceptionClass\": provide --base or --exception-class.',\n );\n }\n\n const localHttpClass = cfg.localHttpClass ?? DEFAULT_LOCAL_HTTP;\n const localResponseClass = cfg.localResponseClass ?? DEFAULT_LOCAL_RESPONSE;\n const localJsonClass = cfg.localJsonClass ?? DEFAULT_LOCAL_JSON;\n const localJsonParserClass =\n cfg.localJsonParserClass ?? DEFAULT_LOCAL_JSON_PARSER;\n\n const resolved: ResolvedNames = {\n typesInterface,\n operationsInterface,\n implementationClass,\n exceptionClass,\n localHttpClass,\n localResponseClass,\n localJsonClass,\n localJsonParserClass,\n };\n\n validateGlobal('typesInterface', resolved.typesInterface);\n validateGlobal('operationsInterface', resolved.operationsInterface);\n validateGlobal('implementationClass', resolved.implementationClass);\n validateGlobal('exceptionClass', resolved.exceptionClass);\n validateLocal('localHttpClass', resolved.localHttpClass);\n validateLocal('localResponseClass', resolved.localResponseClass);\n validateLocal('localJsonClass', resolved.localJsonClass);\n validateLocal('localJsonParserClass', resolved.localJsonParserClass);\n\n return resolved;\n}\n","/**\n * Layer-1 types interface emitter.\n *\n * Builds a single global ABAP interface (e.g. `ZIF_PETSTORE_TYPES`) that\n * declares every OpenAPI component schema as a `TYPES` entry, in\n * topological order. Naming follows the v2 convention: no `ty_` prefix —\n * the OpenAPI schema name is snake_cased directly.\n *\n * See packages/openai-codegen/AGENTS.md style references. This module\n * intentionally bypasses the existing `ty_`-prefixed `mapSchemaToTypeDef`\n * in `../types/map` and reconstructs TypeDef nodes from scratch so it can\n * honour the v2 rules (bare names, per-schema map types, cyclic back-ref\n * detection, controllable null flags, polymorphism union merge).\n */\nimport {\n builtinType,\n enumType,\n interfaceDef,\n namedTypeRef,\n structureType,\n tableType,\n typeDef,\n type InterfaceDef,\n type StructureField,\n type TypeDef,\n type TypeRef,\n} from '@abapify/abap-ast';\nimport type { JsonSchema, NormalizedSpec } from '../oas/types';\nimport { isRef } from '../oas/types';\nimport type { TypePlan, TypePlanEntry } from '../types/plan';\nimport { makeNameAllocator, sanitizeIdent } from '../types/naming';\n\n// -----------------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------------\n\nexport interface EmitTypesInterfaceOptions {\n /** UPPERCASE ABAP global interface name, e.g. 'ZIF_PETSTORE_TYPES'. */\n readonly name: string;\n /**\n * When true, nullable fields (`nullable: true` or `type: [..., \"null\"]`)\n * receive a sibling `<field>_is_null TYPE abap_bool` flag. Default false.\n */\n readonly emitNullFlags?: boolean;\n /** Optional ABAPDoc header lines for the interface itself. */\n readonly interfaceAbapDoc?: readonly string[];\n}\n\nexport interface EmitTypesInterfaceResult {\n readonly interface: InterfaceDef;\n readonly typeDefs: readonly TypeDef[];\n}\n\n/** Raised when polymorphism variants disagree on the type of a named field. */\nexport class PolymorphismConflictError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'PolymorphismConflictError';\n }\n}\n\nexport function emitTypesInterface(\n spec: NormalizedSpec,\n plan: TypePlan,\n opts: EmitTypesInterfaceOptions,\n): EmitTypesInterfaceResult {\n if (!opts.name) {\n throw new Error('emitTypesInterface: opts.name is required');\n }\n const ctx = buildContext(spec, plan, opts);\n\n const typeDefs: TypeDef[] = [];\n for (const entry of plan.entries) {\n if (entry.source === 'auxiliary') {\n // Skip the shared `aux.kv` entry — v2 emits per-schema map types.\n continue;\n }\n const aux = ctx.mapAux.get(entry.id);\n if (aux) {\n typeDefs.push(aux.entryTypeDef);\n typeDefs.push(aux.mapTypeDef);\n }\n typeDefs.push(buildEntryTypeDef(entry, ctx));\n }\n\n return {\n interface: interfaceDef({\n name: opts.name,\n members: typeDefs,\n abapDoc: opts.interfaceAbapDoc,\n }),\n typeDefs,\n };\n}\n\n// -----------------------------------------------------------------------------\n// Internals\n// -----------------------------------------------------------------------------\n\ninterface MapAux {\n readonly entryName: string;\n readonly mapName: string;\n readonly entryTypeDef: TypeDef;\n readonly mapTypeDef: TypeDef;\n}\n\ninterface Ctx {\n readonly spec: NormalizedSpec;\n readonly plan: TypePlan;\n readonly opts: EmitTypesInterfaceOptions;\n /** entry.id → emitted v2 name. */\n readonly nameOf: ReadonlyMap<string, string>;\n /** entry.id → position in plan.entries. */\n readonly positionOf: ReadonlyMap<string, number>;\n /** entry.id → original OpenAPI schema name (component schemas only). */\n readonly originalNameOf: ReadonlyMap<string, string>;\n /** entry.id → per-schema map aux types (when additionalProperties present). */\n readonly mapAux: ReadonlyMap<string, MapAux>;\n /**\n * Per entry-id, list of back-edge notes accumulated while building fields.\n * Flushed into the TypeDef's abapDoc.\n */\n readonly backRefs: Map<string, string[]>;\n}\n\nfunction isRecord(x: unknown): x is Record<string, unknown> {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\nfunction pluckType(schema: JsonSchema): string | undefined {\n const t = (schema as { type?: unknown }).type;\n if (typeof t === 'string') return t;\n if (Array.isArray(t)) {\n const nonNull = t.filter((x): x is string => x !== 'null');\n if (nonNull.length >= 1) return nonNull[0];\n }\n return undefined;\n}\n\nfunction isNullable(schema: JsonSchema): boolean {\n const rec = schema as Record<string, unknown>;\n if (rec.nullable === true) return true;\n const t = rec.type;\n if (Array.isArray(t) && t.includes('null')) return true;\n return false;\n}\n\nfunction componentNameFromRef(ref: string): string | undefined {\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n return m ? m[1] : undefined;\n}\n\nfunction originalNameFromId(id: string): string | undefined {\n const m = /^components\\.schemas\\.(.+)$/.exec(id);\n return m ? m[1] : undefined;\n}\n\n/** Normalise a raw name for v2: replace `$` with `_`, then snake_case ≤ 30. */\nfunction v2Name(\n raw: string,\n allocator: ReturnType<typeof makeNameAllocator>,\n): string {\n const pre = raw.replaceAll(/\\$/g, '_');\n return allocator(pre, 'type');\n}\n\n// -----------------------------------------------------------------------------\n// Context construction\n// -----------------------------------------------------------------------------\n\nfunction buildContext(\n spec: NormalizedSpec,\n plan: TypePlan,\n opts: EmitTypesInterfaceOptions,\n): Ctx {\n const used = new Set<string>();\n const alloc = makeNameAllocator(used);\n\n const nameOf = new Map<string, string>();\n const originalNameOf = new Map<string, string>();\n const positionOf = new Map<string, number>();\n plan.entries.forEach((e, idx) => positionOf.set(e.id, idx));\n\n // Allocate v2 names for all non-auxiliary entries first.\n for (const entry of plan.entries) {\n if (entry.source === 'auxiliary') continue;\n const raw = deriveRawName(entry);\n const v2 = v2Name(raw, alloc);\n nameOf.set(entry.id, v2);\n const orig = originalNameFromId(entry.id);\n if (orig !== undefined) originalNameOf.set(entry.id, orig);\n }\n\n // Pre-compute per-schema map aux types for entries with additionalProperties.\n const mapAux = new Map<string, MapAux>();\n const backRefs = new Map<string, string[]>();\n for (const entry of plan.entries) backRefs.set(entry.id, []);\n\n const ctxStub: Ctx = {\n spec,\n plan,\n opts,\n nameOf,\n positionOf,\n originalNameOf,\n mapAux,\n backRefs,\n };\n\n for (const entry of plan.entries) {\n if (entry.source === 'auxiliary') continue;\n const ap = (entry.schema as { additionalProperties?: unknown })\n .additionalProperties;\n if (ap === undefined || ap === false) continue;\n const base = nameOf.get(entry.id)!;\n const entryName = v2Name(`${base}_map_entry`, alloc);\n const mapName = v2Name(`${base}_map`, alloc);\n const valueSchema: JsonSchema = isRecord(ap)\n ? (ap as JsonSchema)\n : {\n type: 'string',\n };\n const valueRef = asFieldTypeRef(\n resolveTypeRef(valueSchema, entry.id, ctxStub),\n );\n const entryTypeDef = typeDef({\n name: entryName,\n type: structureType({\n fields: [\n { name: 'key', type: builtinType({ name: 'string' }) },\n { name: 'value', type: valueRef },\n ],\n }),\n abapDoc: [`@openapi-map-entry ${originalNameFromId(entry.id) ?? base}`],\n });\n const mapTypeDef = typeDef({\n name: mapName,\n type: tableType({\n rowType: namedTypeRef({ name: entryName }),\n tableKind: 'standard',\n }),\n abapDoc: [`@openapi-map ${originalNameFromId(entry.id) ?? base}`],\n });\n mapAux.set(entry.id, { entryName, mapName, entryTypeDef, mapTypeDef });\n }\n\n return ctxStub;\n}\n\nfunction deriveRawName(entry: TypePlanEntry): string {\n // Strip the `ty_` prefix the planner applied; if the original schema name\n // was something exotic (inline), fall back to a path-derived identifier.\n const stripped = entry.abapName.replace(/^ty_/, '');\n const orig = originalNameFromId(entry.id);\n if (orig !== undefined) return orig;\n // Inline entries: keep the sanitized ty-stripped name.\n return stripped || entry.id;\n}\n\n// -----------------------------------------------------------------------------\n// TypeDef construction per entry\n// -----------------------------------------------------------------------------\n\nfunction buildEntryTypeDef(entry: TypePlanEntry, ctx: Ctx): TypeDef {\n const name = ctx.nameOf.get(entry.id)!;\n const schema = entry.schema;\n const leadingDoc: string[] = [];\n const original = ctx.originalNameOf.get(entry.id);\n if (original !== undefined) {\n leadingDoc.push(`@openapi-schema ${original}`);\n } else if (entry.source === 'inline') {\n leadingDoc.push(`@openapi-path ${entry.id}`);\n }\n const description = (schema as { description?: unknown }).description;\n if (typeof description === 'string' && description.trim()) {\n for (const line of description.split(/\\r?\\n/)) {\n leadingDoc.push(`@openapi-description ${line}`);\n }\n }\n\n // Enum shortcut: string with enum values.\n const enumValues = (schema as { enum?: unknown }).enum;\n const schemaType = pluckType(schema);\n if (\n Array.isArray(enumValues) &&\n (schemaType === 'string' || schemaType === undefined)\n ) {\n const members: { name: string; value: string | number }[] = [];\n const seen = new Set<string>();\n for (const v of enumValues) {\n if (typeof v === 'string') {\n let nm = sanitizeIdent(v, 'type');\n let i = 2;\n while (seen.has(nm)) {\n nm = `${nm}_${i++}`;\n }\n seen.add(nm);\n members.push({ name: nm, value: v });\n } else if (typeof v === 'number') {\n let nm = sanitizeIdent(`v_${v}`, 'type');\n let i = 2;\n while (seen.has(nm)) {\n nm = `${nm}_${i++}`;\n }\n seen.add(nm);\n members.push({ name: nm, value: v });\n }\n }\n if (members.length > 0) {\n return typeDef({\n name,\n type: enumType({\n baseType: builtinType({ name: 'string' }),\n members,\n }),\n abapDoc: leadingDoc.length > 0 ? leadingDoc : undefined,\n });\n }\n }\n\n // Array alias at top level: `TYPES foo TYPE STANDARD TABLE OF <x> ...`.\n if (schemaType === 'array') {\n const items = (schema as { items?: unknown }).items;\n const rowSchema: JsonSchema = isRecord(items) ? (items as JsonSchema) : {};\n const def = typeDef({\n name,\n type: tableType({\n rowType: resolveTypeRef(rowSchema, entry.id, ctx),\n tableKind: 'standard',\n }),\n abapDoc: finaliseDoc(leadingDoc, ctx.backRefs.get(entry.id) ?? []),\n });\n return def;\n }\n\n // Object / combinator / map: emit STRUCTURE.\n const hasObjectShape =\n schemaType === 'object' ||\n isRecord((schema as { properties?: unknown }).properties) ||\n Array.isArray((schema as { allOf?: unknown }).allOf) ||\n Array.isArray((schema as { oneOf?: unknown }).oneOf) ||\n Array.isArray((schema as { anyOf?: unknown }).anyOf) ||\n ctx.mapAux.has(entry.id);\n\n if (hasObjectShape) {\n const fields = buildStructureFields(entry, ctx);\n const finalFields =\n fields.length > 0\n ? fields\n : [\n {\n name: '_placeholder',\n type: builtinType({ name: 'string' }),\n } satisfies StructureField,\n ];\n return typeDef({\n name,\n type: structureType({ fields: finalFields }),\n abapDoc: finaliseDoc(leadingDoc, ctx.backRefs.get(entry.id) ?? []),\n });\n }\n\n // Primitive alias.\n return typeDef({\n name,\n type: builtinType({ name: mapPrimitiveLocal(schema) }),\n abapDoc: finaliseDoc(leadingDoc, ctx.backRefs.get(entry.id) ?? []),\n });\n}\n\nfunction finaliseDoc(\n base: string[],\n backRefs: readonly string[],\n): readonly string[] | undefined {\n const out = [...base];\n for (const br of backRefs) out.push(br);\n return out.length > 0 ? out : undefined;\n}\n\n// -----------------------------------------------------------------------------\n// Structure field construction (merge allOf / oneOf / anyOf / properties /\n// additionalProperties).\n// -----------------------------------------------------------------------------\n\nfunction buildStructureFields(\n entry: TypePlanEntry,\n ctx: Ctx,\n): StructureField[] {\n const schema = entry.schema;\n const fields: StructureField[] = [];\n const seen = new Map<string, TypeRef>();\n\n const addField = (rawName: string, rawType: TypeRef, src: JsonSchema) => {\n const type = asFieldTypeRef(rawType);\n const fieldName = sanitizeIdent(rawName.replaceAll(/\\$/g, '_'), 'param');\n const prev = seen.get(fieldName);\n if (prev !== undefined) {\n if (!typeRefEqual(prev, type)) {\n throw new PolymorphismConflictError(\n `buildStructureFields: conflicting types for field \"${fieldName}\" in \"${entry.id}\"`,\n );\n }\n return;\n }\n seen.set(fieldName, type);\n fields.push({ name: fieldName, type });\n if (ctx.opts.emitNullFlags && isNullable(src)) {\n const flagName = sanitizeIdent(`${rawName}_is_null`, 'param');\n if (!seen.has(flagName)) {\n const flagType = builtinType({ name: 'abap_bool' });\n seen.set(flagName, flagType);\n fields.push({ name: flagName, type: flagType });\n }\n }\n };\n\n const mergeProperties = (src: JsonSchema) => {\n const props = (src as { properties?: unknown }).properties;\n if (isRecord(props)) {\n for (const [propName, propSchema] of Object.entries(props)) {\n if (!isRecord(propSchema)) continue;\n const ref = resolveTypeRef(\n propSchema as JsonSchema,\n entry.id,\n ctx,\n propName,\n );\n addField(propName, ref, propSchema as JsonSchema);\n }\n }\n };\n\n // 1) allOf — merged union of properties; conflicting field types throw.\n const allOf = (schema as { allOf?: unknown }).allOf;\n if (Array.isArray(allOf)) {\n for (const sub of allOf) {\n if (!isRecord(sub)) continue;\n if (isRef(sub)) {\n const refEntry = resolveRefEntry(sub.$ref, ctx);\n if (refEntry !== undefined) mergeProperties(refEntry.schema);\n } else {\n mergeProperties(sub as JsonSchema);\n }\n }\n }\n\n // 2) own properties.\n mergeProperties(schema);\n\n // 3) oneOf / anyOf — union of properties from each variant.\n for (const combinator of ['oneOf', 'anyOf'] as const) {\n const arr = (schema as Record<string, unknown>)[combinator];\n if (!Array.isArray(arr)) continue;\n for (const sub of arr) {\n if (!isRecord(sub)) continue;\n if (isRef(sub)) {\n const refEntry = resolveRefEntry(sub.$ref, ctx);\n if (refEntry !== undefined) mergeProperties(refEntry.schema);\n } else {\n mergeProperties(sub as JsonSchema);\n }\n }\n }\n\n // 4) additionalProperties → replace escape-hatch with per-schema map type.\n const aux = ctx.mapAux.get(entry.id);\n if (aux) {\n const fieldName = sanitizeIdent('entries', 'param');\n if (!seen.has(fieldName)) {\n const ref = namedTypeRef({ name: aux.mapName });\n seen.set(fieldName, ref);\n fields.push({ name: fieldName, type: ref });\n }\n }\n\n return fields;\n}\n\nfunction resolveRefEntry(ref: string, ctx: Ctx): TypePlanEntry | undefined {\n const name = componentNameFromRef(ref);\n if (!name) return undefined;\n return ctx.plan.byId.get(`components.schemas.${name}`);\n}\n\nfunction typeRefEqual(a: TypeRef, b: TypeRef): boolean {\n if (a.kind !== b.kind) return false;\n if (a.kind === 'BuiltinType' && b.kind === 'BuiltinType') {\n return a.name === b.name;\n }\n if (a.kind === 'NamedTypeRef' && b.kind === 'NamedTypeRef') {\n return a.name === b.name;\n }\n if (a.kind === 'TableType' && b.kind === 'TableType') {\n return typeRefEqual(a.rowType, b.rowType);\n }\n return false;\n}\n\n/**\n * Convert a TypeRef that may be a TableType into a form that can appear as a\n * structure-field type. The underlying ABAP printer only accepts BuiltinType\n * or NamedTypeRef inline; we synthesise a NamedTypeRef whose \"name\" is the\n * full inline table expression so the printer emits it verbatim.\n */\nfunction asFieldTypeRef(t: TypeRef): TypeRef {\n if (t.kind !== 'TableType') return t;\n const row = t.rowType;\n let rowExpr: string;\n if (row.kind === 'BuiltinType') {\n rowExpr = row.name;\n } else if (row.kind === 'NamedTypeRef') {\n rowExpr = row.name;\n } else {\n // Nested table/structure as row — ABAP has no clean inline syntax for\n // this. Degrade to `string` row; callers should emit a named wrapper\n // when they need fidelity.\n rowExpr = 'string';\n }\n return namedTypeRef({\n name: `STANDARD TABLE OF ${rowExpr} WITH EMPTY KEY`,\n });\n}\n\n// -----------------------------------------------------------------------------\n// TypeRef resolution for arbitrary nested schemas.\n// -----------------------------------------------------------------------------\n\nfunction resolveTypeRef(\n schema: JsonSchema,\n ownerEntryId: string,\n ctx: Ctx,\n fieldName?: string,\n): TypeRef {\n if (isRef(schema)) {\n const target = resolveRefEntry(schema.$ref, ctx);\n if (target === undefined) {\n // Unresolvable — degrade to string.\n return builtinType({ name: 'string' });\n }\n const ownerPos = ctx.positionOf.get(ownerEntryId) ?? -1;\n const targetPos = ctx.positionOf.get(target.id) ?? -1;\n const isBackEdge = targetPos >= 0 && ownerPos >= 0 && targetPos >= ownerPos;\n const isSelf = target.id === ownerEntryId;\n if (isSelf || isBackEdge) {\n const targetOriginal =\n ctx.originalNameOf.get(target.id) ??\n ctx.nameOf.get(target.id) ??\n target.id;\n const backRefs = ctx.backRefs.get(ownerEntryId);\n if (backRefs !== undefined) {\n const label = fieldName\n ? `${fieldName}:${targetOriginal}`\n : targetOriginal;\n backRefs.push(`@openapi-ref ${label}`);\n }\n // NamedTypeRef with a multi-token name — the printer emits it verbatim\n // after `TYPE `, yielding `TYPE REF TO data`.\n return namedTypeRef({ name: 'REF TO data' });\n }\n return namedTypeRef({ name: ctx.nameOf.get(target.id) ?? target.abapName });\n }\n\n const type = pluckType(schema);\n\n if (type === 'array') {\n const items = (schema as { items?: unknown }).items;\n const rowSchema: JsonSchema = isRecord(items) ? (items as JsonSchema) : {};\n return tableType({\n rowType: resolveTypeRef(rowSchema, ownerEntryId, ctx, fieldName),\n tableKind: 'standard',\n });\n }\n\n const props = (schema as { properties?: unknown }).properties;\n if (type === 'object' || isRecord(props)) {\n // Prefer a planned entry for this exact schema object if one exists.\n const matched = findPlannedEntryBySchema(schema, ctx.plan, ownerEntryId);\n if (matched !== undefined) {\n const name = ctx.nameOf.get(matched.id);\n if (name !== undefined) {\n return namedTypeRef({ name });\n }\n }\n // No matching plan entry — degrade to string (inline objects that the\n // planner did not extract are unusual; a downstream wave can extend this).\n return builtinType({ name: 'string' });\n }\n\n if (type === undefined) {\n for (const c of ['allOf', 'oneOf', 'anyOf'] as const) {\n if (Array.isArray((schema as Record<string, unknown>)[c])) {\n const matched = findPlannedEntryBySchema(\n schema,\n ctx.plan,\n ownerEntryId,\n );\n if (matched !== undefined) {\n const name = ctx.nameOf.get(matched.id);\n if (name !== undefined) return namedTypeRef({ name });\n }\n return builtinType({ name: 'string' });\n }\n }\n return builtinType({ name: 'string' });\n }\n\n return builtinType({ name: mapPrimitiveLocal(schema) });\n}\n\nfunction findPlannedEntryBySchema(\n schema: JsonSchema,\n plan: TypePlan,\n excludeId: string | undefined,\n): TypePlanEntry | undefined {\n for (const entry of plan.entries) {\n if (entry.id === excludeId) continue;\n if (entry.schema === schema) return entry;\n }\n return undefined;\n}\n\nfunction mapPrimitiveLocal(\n schema: JsonSchema,\n):\n | 'i'\n | 'int8'\n | 'f'\n | 'decfloat34'\n | 'd'\n | 't'\n | 'timestampl'\n | 'string'\n | 'xstring'\n | 'abap_bool'\n | 'sysuuid_x16' {\n const type = pluckType(schema);\n const format = (schema as { format?: unknown }).format;\n if (type === 'boolean') return 'abap_bool';\n if (type === 'integer') {\n return format === 'int64' ? 'int8' : 'i';\n }\n if (type === 'number') {\n return format === 'float' || format === 'double' ? 'f' : 'decfloat34';\n }\n if (type === 'string') {\n switch (format) {\n case 'date':\n return 'd';\n case 'date-time':\n return 'timestampl';\n case 'uuid':\n return 'sysuuid_x16';\n case 'byte':\n case 'binary':\n return 'xstring';\n default:\n return 'string';\n }\n }\n return 'string';\n}\n","/**\n * Layer 2 emitter — OPERATIONS INTERFACE (`ZIF_<base>`).\n *\n * Produces a single global ABAP interface whose methods mirror the OpenAPI\n * `operations` list 1:1. All type references point into the types interface\n * emitted by the Wave 1 Layer-1 emitter (`ZIF_<base>_TYPES`).\n *\n * The design is deliberately conservative:\n * - RETURNING values carry a bare, natural name (no `rv_` / `rt_` prefix).\n * - IMPORTING parameters use the OpenAPI parameter name, snake-cased.\n * - Body parameters are always called `body`.\n * - Every method RAISES the single generated exception class.\n * - Cookie parameters are skipped with an `\"! @openapi-todo` note.\n *\n * The emitter also returns a parallel `operations` array describing each\n * method's mapping. The Wave 2 implementation-class emitter consumes this\n * array to build per-operation bodies.\n */\nimport {\n builtinType,\n interfaceDef,\n methodDef,\n methodParam,\n namedTypeRef,\n tableType,\n typeDef,\n type InterfaceDef,\n type MethodParam,\n type TypeDef,\n type TypeRef,\n} from '@abapify/abap-ast';\nimport type {\n JsonSchema,\n NormalizedOperation,\n NormalizedParameter,\n NormalizedResponse,\n NormalizedSpec,\n} from '../oas/types';\nimport { isRef } from '../oas/types';\nimport type { TypePlan } from '../types/plan';\nimport { mapPrimitive } from '../types/map';\nimport { makeNameAllocator, sanitizeIdent } from '../types/naming';\n\n// `ResolvedNames` is re-exported for downstream callers that want to thread\n// it through their own NamesConfig; we don't consume the type here.\nexport type { ResolvedNames } from './naming';\n\n// -----------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------\n\nexport interface EmitOperationsInterfaceOptions {\n /** Global interface name, e.g. 'ZIF_PETSTORE'. */\n readonly name: string;\n /** Name of the sibling types interface, e.g. 'ZIF_PETSTORE_TYPES'. */\n readonly typesInterfaceName: string;\n /** Name of the generated exception class, e.g. 'ZCX_PETSTORE_ERROR'. */\n readonly exceptionClassName: string;\n /** Optional ABAPDoc to attach to the interface itself. */\n readonly interfaceAbapDoc?: readonly string[];\n}\n\nexport interface OperationParamMapping {\n readonly name: string;\n readonly openapiName: string;\n readonly location: 'path' | 'query' | 'header';\n readonly required: boolean;\n readonly typeRefSource: string;\n /** True when the ABAP type is a STANDARD TABLE (array) alias. */\n readonly isTable: boolean;\n}\n\nexport interface OperationMapping {\n readonly operationId: string;\n readonly methodName: string;\n readonly method: string;\n readonly path: string;\n readonly params: readonly OperationParamMapping[];\n readonly hasBody: boolean;\n readonly successStatus: number | 'default';\n readonly successIsEmptyBody: boolean;\n readonly errorResponses: Readonly<Record<string, { description?: string }>>;\n readonly returningName: string;\n}\n\nexport interface EmitOperationsInterfaceResult {\n readonly interface: InterfaceDef;\n readonly operations: readonly OperationMapping[];\n}\n\n// -----------------------------------------------------------------------\n// Helpers\n// -----------------------------------------------------------------------\n\nfunction isRecord(x: unknown): x is Record<string, unknown> {\n return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\nfunction pluckType(schema: JsonSchema | undefined): string | undefined {\n if (!schema) return undefined;\n const t = (schema as { type?: unknown }).type;\n if (typeof t === 'string') return t;\n if (Array.isArray(t)) {\n const nonNull = t.filter((x): x is string => x !== 'null');\n if (nonNull.length >= 1) return nonNull[0];\n }\n return undefined;\n}\n\nfunction isPlainObjectSchema(schema: JsonSchema): boolean {\n const t = pluckType(schema);\n return (\n t === 'object' || isRecord((schema as { properties?: unknown }).properties)\n );\n}\n\nfunction componentNameFromRef(ref: string): string | undefined {\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n return m ? m[1] : undefined;\n}\n\ninterface ComponentIndex {\n /** Keys of `properties` — sorted, comma-joined — for fast lookup. */\n readonly byPropSig: ReadonlyMap<string, string>;\n}\n\nfunction buildComponentIndex(spec: NormalizedSpec): ComponentIndex {\n const byPropSig = new Map<string, string>();\n for (const [name, schema] of Object.entries(spec.schemas)) {\n if (!isRecord(schema)) continue;\n const props = (schema as { properties?: unknown }).properties;\n if (!isRecord(props)) continue;\n const keys = Object.keys(props)\n .sort((a, b) => a.localeCompare(b))\n .join(',');\n if (keys && !byPropSig.has(keys)) {\n byPropSig.set(keys, name);\n }\n }\n return { byPropSig };\n}\n\n/** Identify which component schema a (possibly dereferenced) schema refers to. */\nfunction matchComponent(\n schema: JsonSchema | undefined,\n index: ComponentIndex,\n): string | undefined {\n if (!schema) return undefined;\n if (isRef(schema)) return componentNameFromRef(schema.$ref);\n if (!isPlainObjectSchema(schema)) return undefined;\n const props = (schema as { properties?: unknown }).properties;\n if (!isRecord(props)) return undefined;\n const sig = Object.keys(props)\n .sort((a, b) => a.localeCompare(b))\n .join(',');\n if (!sig) return undefined;\n return index.byPropSig.get(sig);\n}\n\nfunction typeInterfaceMember(\n typesInterfaceName: string,\n componentName: string,\n): string {\n return `${typesInterfaceName.toLowerCase()}=>${sanitizeIdent(componentName, 'type')}`;\n}\n\n/** Render a schema as the printable form used inline after `TYPE`. */\nfunction renderSchemaTypeSource(\n schema: JsonSchema | undefined,\n index: ComponentIndex,\n typesInterfaceName: string,\n): string {\n if (!schema) return 'string';\n if (isRef(schema)) {\n const name = componentNameFromRef(schema.$ref);\n return name ? typeInterfaceMember(typesInterfaceName, name) : 'string';\n }\n const t = pluckType(schema);\n if (t === 'array') {\n const items = (schema as { items?: unknown }).items;\n const row = renderSchemaTypeSource(\n isRecord(items) ? (items as JsonSchema) : {},\n index,\n typesInterfaceName,\n );\n // Note: we deliberately omit `WITH EMPTY KEY` / `WITH DEFAULT KEY` here.\n // ABAP accepts `STANDARD TABLE OF <type>` in a METHODS parameter type,\n // but not the key clause inline — a named TYPES alias would be required\n // for that. Callers that want a specific key behaviour should declare a\n // named table type in the types interface and reference it directly.\n return `STANDARD TABLE OF ${row}`;\n }\n if (isPlainObjectSchema(schema)) {\n const comp = matchComponent(schema, index);\n return comp ? typeInterfaceMember(typesInterfaceName, comp) : 'string';\n }\n return mapPrimitive(schema);\n}\n\n/**\n * Build an ABAP `TypeRef` for a schema usable as an inline type reference.\n *\n * For array shapes we ALWAYS emit a named alias (`<ops-intf>=><name>_list`)\n * into the operations interface itself. Cloud ABAP does NOT accept inline\n * `STANDARD TABLE OF ...` clauses inside a METHODS parameter list (the SAP\n * ADT save endpoint returns \"An error occured during the save operation\"),\n * so every array-typed parameter or return must be a named type reference.\n * The aliases are collected via {@link registerTableAlias} and emitted as\n * TYPES declarations at the head of the interface in {@link emitOperationsInterface}.\n */\nfunction schemaToTypeRef(\n schema: JsonSchema | undefined,\n index: ComponentIndex,\n typesInterfaceName: string,\n opsInterfaceName: string,\n aliases: TableAliasRegistry,\n): TypeRef {\n if (!schema) return builtinType({ name: 'string' });\n if (isRef(schema)) {\n const name = componentNameFromRef(schema.$ref);\n if (name) {\n return namedTypeRef({\n name: typeInterfaceMember(typesInterfaceName, name),\n });\n }\n return builtinType({ name: 'string' });\n }\n const t = pluckType(schema);\n if (t === 'array') {\n const items = (schema as { items?: unknown }).items;\n const rowSchema: JsonSchema = isRecord(items) ? (items as JsonSchema) : {};\n const rowType = renderSchemaTypeSource(\n rowSchema,\n index,\n typesInterfaceName,\n );\n const aliasName = registerTableAlias(aliases, rowType);\n return namedTypeRef({\n name: `${opsInterfaceName.toLowerCase()}=>${aliasName}`,\n });\n }\n if (isPlainObjectSchema(schema)) {\n const comp = matchComponent(schema, index);\n if (comp) {\n return namedTypeRef({\n name: typeInterfaceMember(typesInterfaceName, comp),\n });\n }\n return builtinType({ name: 'string' });\n }\n // Primitive.\n return builtinType({ name: mapPrimitive(schema) });\n}\n\n/**\n * Registry of `STANDARD TABLE OF <rowType> WITH EMPTY KEY` aliases emitted\n * into the operations interface. Keyed by the row-type source string so\n * identical row types share the same alias (`pet_list`, `string_list`, ...).\n */\ninterface TableAliasRegistry {\n readonly aliases: Map<string, string>;\n /** Insertion order, used when flushing TypeDefs to the interface. */\n readonly order: string[];\n}\n\nfunction createTableAliasRegistry(): TableAliasRegistry {\n return { aliases: new Map<string, string>(), order: [] };\n}\n\n/** Return the alias name for a given row type, registering it if new. */\nfunction registerTableAlias(\n registry: TableAliasRegistry,\n rowType: string,\n): string {\n const existing = registry.aliases.get(rowType);\n if (existing !== undefined) return existing;\n const alias = deriveTableAliasName(rowType, registry.aliases);\n registry.aliases.set(rowType, alias);\n registry.order.push(alias);\n return alias;\n}\n\n/**\n * Derive an alias name from the row-type source.\n * Strip any interface prefix (`zif_foo_types=>`) and keep only the schema\n * name, then append `_list`. Collisions get a `_2`, `_3` … suffix.\n */\nfunction deriveTableAliasName(\n rowType: string,\n existing: ReadonlyMap<string, string>,\n): string {\n const taken = new Set(existing.values());\n const bare = rowType.includes('=>')\n ? (rowType.split('=>').pop() ?? rowType)\n : rowType;\n const sanitized = bare.replaceAll(/[^a-z0-9_]/gi, '_').toLowerCase();\n const base = `${sanitized}_list`;\n if (!taken.has(base)) return base;\n let i = 2;\n while (taken.has(`${base}_${i}`)) i += 1;\n return `${base}_${i}`;\n}\n\n/** Build TypeDef nodes for every registered table alias. */\nfunction buildAliasTypeDefs(registry: TableAliasRegistry): readonly TypeDef[] {\n const inverse = new Map<string, string>();\n for (const [rowType, alias] of registry.aliases) {\n inverse.set(alias, rowType);\n }\n return registry.order.map((alias) => {\n const rowType = inverse.get(alias) ?? 'string';\n return typeDef({\n name: alias,\n type: tableType({\n rowType: namedTypeRef({ name: rowType }),\n tableKind: 'standard',\n }),\n });\n });\n}\n\n// ----- Response selection ------------------------------------------------\n\ninterface SuccessPick {\n readonly response: NormalizedResponse;\n readonly status: number | 'default';\n readonly schema?: JsonSchema;\n}\n\nfunction pickSuccess(op: NormalizedOperation): SuccessPick | undefined {\n const successes = op.responses.filter((r) => r.isSuccess);\n if (successes.length === 0) return undefined;\n let chosen: NormalizedResponse | undefined;\n chosen = successes.find((r) => r.statusCode === '200');\n if (!chosen) {\n // Smallest 2xx, otherwise 'default'.\n const twoXx = successes\n .filter((r) => /^2\\d\\d$/.test(r.statusCode))\n .sort((a, b) => Number(a.statusCode) - Number(b.statusCode));\n chosen = twoXx[0] ?? successes[0];\n }\n const status: number | 'default' =\n chosen.statusCode === 'default' ? 'default' : Number(chosen.statusCode);\n // Prefer application/json; then application/octet-stream; then first.\n const content = chosen.content;\n const preferred =\n content['application/json'] ??\n content['application/octet-stream'] ??\n content[Object.keys(content)[0] ?? ''];\n const schema = preferred?.schema;\n const hasSchema = schema !== undefined && Object.keys(schema).length > 0;\n return { response: chosen, status, schema: hasSchema ? schema : undefined };\n}\n\nfunction pickRequestBodySchema(\n op: NormalizedOperation,\n): JsonSchema | undefined {\n const rb = op.requestBody;\n if (!rb) return undefined;\n const c = rb.content;\n const preferred =\n c['application/json'] ??\n c['application/octet-stream'] ??\n c[Object.keys(c)[0] ?? ''];\n const schema = preferred?.schema;\n if (!schema) return undefined;\n return Object.keys(schema).length > 0 ? schema : undefined;\n}\n\n// ----- Returning-name derivation ----------------------------------------\n\nfunction deriveReturningName(\n schema: JsonSchema | undefined,\n index: ComponentIndex,\n): string {\n if (!schema) return 'result';\n if (isRef(schema)) {\n const name = componentNameFromRef(schema.$ref);\n return name ? sanitizeIdent(name, 'param') : 'result';\n }\n const t = pluckType(schema);\n if (t === 'array') {\n const items = (schema as { items?: unknown }).items;\n if (isRecord(items)) {\n const inner = deriveReturningName(items as JsonSchema, index);\n if (inner === 'result') return 'results';\n return pluralize(inner);\n }\n return 'results';\n }\n if (isPlainObjectSchema(schema)) {\n const comp = matchComponent(schema, index);\n if (comp) return sanitizeIdent(comp, 'param');\n return 'result';\n }\n return 'result';\n}\n\nfunction pluralize(name: string): string {\n if (!name) return 'results';\n if (/(s|x|z|ch|sh)$/i.test(name)) return `${name}_list`;\n if (/y$/i.test(name) && !/[aeiou]y$/i.test(name)) {\n return `${name.slice(0, -1)}ies`;\n }\n return `${name}s`;\n}\n\n// ----- Parameter ordering ------------------------------------------------\n\nfunction orderParams(params: readonly NormalizedParameter[]): {\n emitted: readonly NormalizedParameter[];\n cookieSkipped: readonly NormalizedParameter[];\n} {\n const path = params.filter((p) => p.in === 'path');\n const query = params.filter((p) => p.in === 'query');\n const header = params.filter((p) => p.in === 'header');\n const cookie = params.filter((p) => p.in === 'cookie');\n return {\n emitted: [...path, ...query, ...header],\n cookieSkipped: cookie,\n };\n}\n\n// ----- ABAPDoc assembly --------------------------------------------------\n\nfunction buildMethodAbapDoc(\n op: NormalizedOperation,\n cookieSkipped: readonly NormalizedParameter[],\n): string[] {\n const lines: string[] = [];\n lines.push(`@openapi-operation ${op.operationId}`);\n lines.push(`@openapi-path ${op.method.toUpperCase()} ${op.path}`);\n if (op.summary) {\n for (const l of op.summary.split(/\\r?\\n/)) {\n if (l.trim().length > 0) lines.push(l.trim());\n }\n }\n if (op.deprecated) {\n lines.push('@openapi-deprecated');\n }\n for (const c of cookieSkipped) {\n lines.push(`@openapi-todo cookie param '${c.name}' not mapped`);\n }\n return lines;\n}\n\n// -----------------------------------------------------------------------\n// Main entry\n// -----------------------------------------------------------------------\n\nexport function emitOperationsInterface(\n spec: NormalizedSpec,\n _plan: TypePlan,\n opts: EmitOperationsInterfaceOptions,\n): EmitOperationsInterfaceResult {\n const compIndex = buildComponentIndex(spec);\n\n // Method-name allocator — scoped to the interface.\n const usedMethodNames = new Set<string>();\n const allocMethod = makeNameAllocator(usedMethodNames);\n\n const methods: ReturnType<typeof methodDef>[] = [];\n const mappings: OperationMapping[] = [];\n const tableAliases = createTableAliasRegistry();\n const opsInterfaceName = opts.name;\n\n for (const op of spec.operations) {\n const methodName = allocMethod(op.operationId, 'method');\n const { emitted, cookieSkipped } = orderParams(op.parameters);\n\n // Per-method param-name allocator (avoid clashing with `body`, returning).\n const usedParamNames = new Set<string>();\n const allocParam = makeNameAllocator(usedParamNames);\n\n const abapParams: MethodParam[] = [];\n const paramMappings: OperationParamMapping[] = [];\n\n for (const p of emitted) {\n const abapName = allocParam(p.name, 'param');\n const ref = schemaToTypeRef(\n p.schema,\n compIndex,\n opts.typesInterfaceName,\n opsInterfaceName,\n tableAliases,\n );\n abapParams.push(\n methodParam({\n paramKind: 'importing',\n name: abapName,\n typeRef: ref,\n optional: !p.required,\n }),\n );\n paramMappings.push({\n name: abapName,\n openapiName: p.name,\n location: p.in as 'path' | 'query' | 'header',\n required: p.required,\n typeRefSource: renderTypeRefSource(ref),\n isTable: pluckType(p.schema) === 'array',\n });\n }\n\n const bodySchema = pickRequestBodySchema(op);\n const hasBody = bodySchema !== undefined;\n if (hasBody) {\n const bodyName = allocParam('body', 'param');\n const ref = schemaToTypeRef(\n bodySchema,\n compIndex,\n opts.typesInterfaceName,\n opsInterfaceName,\n tableAliases,\n );\n abapParams.push(\n methodParam({\n paramKind: 'importing',\n name: bodyName,\n typeRef: ref,\n optional: op.requestBody?.required === false ? true : false,\n }),\n );\n }\n\n // Returning.\n const success = pickSuccess(op);\n let successStatus: number | 'default';\n let successIsEmptyBody: boolean;\n let returningName: string;\n let returningRef: TypeRef;\n\n if (!success) {\n successStatus = 200;\n successIsEmptyBody = true;\n returningName = allocParam('success', 'param');\n returningRef = builtinType({ name: 'abap_bool' });\n } else if (success.schema === undefined) {\n successStatus = success.status;\n successIsEmptyBody = true;\n returningName = allocParam('success', 'param');\n returningRef = builtinType({ name: 'abap_bool' });\n } else {\n successStatus = success.status;\n successIsEmptyBody = false;\n const derived = deriveReturningName(success.schema, compIndex);\n returningName = allocParam(derived, 'param');\n returningRef = schemaToTypeRef(\n success.schema,\n compIndex,\n opts.typesInterfaceName,\n opsInterfaceName,\n tableAliases,\n );\n }\n\n abapParams.push(\n methodParam({\n paramKind: 'returning',\n name: returningName,\n typeRef: returningRef,\n }),\n );\n\n // Error responses.\n const errorResponses: Record<string, { description?: string }> = {};\n for (const r of op.responses) {\n if (!r.isError) continue;\n errorResponses[r.statusCode] = r.description\n ? { description: r.description }\n : {};\n }\n\n const method = methodDef({\n name: methodName,\n visibility: 'public',\n params: abapParams,\n raising: [namedTypeRef({ name: opts.exceptionClassName.toLowerCase() })],\n abapDoc: buildMethodAbapDoc(op, cookieSkipped),\n });\n methods.push(method);\n\n mappings.push({\n operationId: op.operationId,\n methodName,\n method: op.method.toUpperCase(),\n path: op.path,\n params: paramMappings,\n hasBody,\n successStatus,\n successIsEmptyBody,\n errorResponses,\n returningName,\n });\n }\n\n const aliasTypeDefs = buildAliasTypeDefs(tableAliases);\n const iface = interfaceDef({\n name: opts.name.toLowerCase(),\n members: [...aliasTypeDefs, ...methods],\n abapDoc: opts.interfaceAbapDoc,\n });\n\n return { interface: iface, operations: mappings };\n}\n\nfunction renderTypeRefSource(ref: TypeRef): string {\n switch (ref.kind) {\n case 'BuiltinType':\n return ref.name;\n case 'NamedTypeRef':\n return ref.name;\n case 'TableType':\n case 'StructureType':\n return ref.kind;\n }\n}\n","/**\n * Emit the generated ABAP exception class that carries HTTP error detail\n * (status code, reason phrase, raw body, response headers).\n *\n * The class inherits from `cx_static_check` and is FINAL with CREATE PUBLIC.\n * It exposes four READ-ONLY attributes and a constructor that assigns them\n * after delegating to `super->constructor( )`.\n */\n\nimport {\n assign,\n attributeDef,\n builtinType,\n call,\n classDef,\n identifierExpr,\n methodDef,\n methodImpl,\n methodParam,\n namedTypeRef,\n section,\n structureType,\n tableType,\n typeDef,\n type ClassDef,\n type MethodImpl,\n} from '@abapify/abap-ast';\n\nexport interface EmitExceptionClassOptions {\n /** Global ABAP class name, e.g. `ZCX_PETSTORE_ERROR`. */\n readonly name: string;\n /** Optional class-level ABAPDoc lines. */\n readonly interfaceAbapDoc?: readonly string[];\n}\n\nexport interface EmitExceptionClassResult {\n readonly class: ClassDef;\n}\n\n/** Build the constructor's IMPLEMENTATION body (super call + 4 assignments). */\nfunction buildConstructorImpl(): MethodImpl {\n const superCall = call({\n receiver: identifierExpr({ name: 'super' }),\n method: 'constructor',\n callKind: 'instance',\n args: [],\n });\n\n const fields: readonly string[] = [\n 'status',\n 'description',\n 'body',\n 'headers',\n ];\n const assignments = fields.map((f) =>\n assign({\n target: identifierExpr({ name: `me->${f}` }),\n value: identifierExpr({ name: f }),\n }),\n );\n\n return methodImpl({\n name: 'constructor',\n body: [superCall, ...assignments],\n });\n}\n\nexport function emitExceptionClass(\n opts: EmitExceptionClassOptions,\n): EmitExceptionClassResult {\n if (!opts.name) {\n throw new Error('emitExceptionClass: required field \"name\" is missing');\n }\n\n const kvType = typeDef({\n name: 'kv',\n type: structureType({\n fields: [\n { name: 'k', type: builtinType({ name: 'string' }) },\n { name: 'v', type: builtinType({ name: 'string' }) },\n ],\n }),\n });\n\n // Note: the AST cannot model `WITH EMPTY KEY`; `WITH DEFAULT KEY` is the\n // closest equivalent accepted by abaplint and is semantically fine for a\n // payload table of heterogeneous header pairs.\n const kvsType = typeDef({\n name: 'kvs',\n type: tableType({\n rowType: namedTypeRef({ name: 'kv' }),\n tableKind: 'standard',\n }),\n });\n\n const statusAttr = attributeDef({\n name: 'status',\n type: builtinType({ name: 'i' }),\n visibility: 'public',\n readOnly: true,\n });\n const descriptionAttr = attributeDef({\n name: 'description',\n type: builtinType({ name: 'string' }),\n visibility: 'public',\n readOnly: true,\n });\n const bodyAttr = attributeDef({\n name: 'body',\n type: builtinType({ name: 'xstring' }),\n visibility: 'public',\n readOnly: true,\n });\n const headersAttr = attributeDef({\n name: 'headers',\n type: namedTypeRef({ name: 'kvs' }),\n visibility: 'public',\n readOnly: true,\n });\n\n const ctor = methodDef({\n name: 'constructor',\n visibility: 'public',\n params: [\n methodParam({\n paramKind: 'importing',\n name: 'status',\n typeRef: builtinType({ name: 'i' }),\n }),\n methodParam({\n paramKind: 'importing',\n name: 'description',\n typeRef: builtinType({ name: 'string' }),\n optional: true,\n }),\n methodParam({\n paramKind: 'importing',\n name: 'body',\n typeRef: builtinType({ name: 'xstring' }),\n optional: true,\n }),\n methodParam({\n paramKind: 'importing',\n name: 'headers',\n typeRef: namedTypeRef({ name: 'kvs' }),\n optional: true,\n }),\n ],\n });\n\n const publicSection = section({\n visibility: 'public',\n members: [\n kvType,\n kvsType,\n statusAttr,\n descriptionAttr,\n bodyAttr,\n headersAttr,\n ctor,\n ],\n });\n\n const cls = classDef({\n name: opts.name,\n superclass: 'cx_static_check',\n isFinal: true,\n sections: [publicSection],\n implementations: [buildConstructorImpl()],\n abapDoc: opts.interfaceAbapDoc ? [...opts.interfaceAbapDoc] : undefined,\n });\n\n return { class: cls };\n}\n","/**\n * ABAP template: `<cls>.clas.locals_def.abap`.\n *\n * Declares four local classes bundled inside the generated implementation\n * class. The locals wrap kernel APIs only — they do NOT reference any\n * Z-prefixed objects.\n *\n * Design note on the exception class name:\n * `lcl_http->fetch` is intentionally generic and propagates only kernel\n * exceptions (`cx_web_http_client_error`, `cx_http_dest_provider_error`).\n * Mapping HTTP status codes to the generated ZCX is the responsibility of\n * the per-operation method, not the local HTTP class. The `exceptionClass`\n * name is accepted in the signature for symmetry with Wave 2, but is\n * currently not referenced in the emitted source.\n */\nexport interface LocalClassesNames {\n exceptionClass: string;\n localJsonClass: string;\n localJsonParserClass: string;\n localResponseClass: string;\n localHttpClass: string;\n}\n\nexport function buildLocalsDef(names: LocalClassesNames): string {\n const {\n localJsonClass: JSON_CLS,\n localJsonParserClass: JSON_PARSER,\n localResponseClass: RESPONSE,\n localHttpClass: HTTP,\n } = names;\n\n // The exceptionClass name is intentionally NOT rendered into the source.\n // Per-operation methods (generated by Wave 2) are responsible for mapping\n // HTTP status codes to the custom exception class; these locals only\n // propagate kernel exceptions.\n void names.exceptionClass;\n\n return `* Generated by @abapify/openai-codegen - local class declarations.\n* ZERO Z-dependencies: these locals wrap SAP kernel APIs only.\n* Per-operation methods map HTTP status codes to the custom exception.\n\nCLASS ${HTTP} DEFINITION DEFERRED.\nCLASS ${RESPONSE} DEFINITION DEFERRED.\nCLASS ${JSON_PARSER} DEFINITION DEFERRED.\nCLASS ${JSON_CLS} DEFINITION DEFERRED.\n\nCLASS ${HTTP} DEFINITION FINAL CREATE PUBLIC.\n PUBLIC SECTION.\n TYPES: BEGIN OF kv,\n name TYPE string,\n value TYPE string,\n END OF kv.\n TYPES kvs TYPE STANDARD TABLE OF kv WITH DEFAULT KEY.\n\n METHODS constructor\n IMPORTING destination TYPE string\n server TYPE string OPTIONAL.\n\n METHODS fetch\n IMPORTING method TYPE string\n path TYPE string\n query TYPE kvs OPTIONAL\n headers TYPE kvs OPTIONAL\n body TYPE string OPTIONAL\n binary TYPE xstring OPTIONAL\n RETURNING VALUE(response) TYPE REF TO ${RESPONSE}\n RAISING cx_web_http_client_error\n cx_http_dest_provider_error.\n\n PRIVATE SECTION.\n DATA destination TYPE string.\n DATA server TYPE string.\n\n METHODS build_query_string\n IMPORTING query TYPE kvs\n RETURNING VALUE(result) TYPE string.\nENDCLASS.\n\nCLASS ${RESPONSE} DEFINITION FINAL CREATE PRIVATE FRIENDS ${HTTP}.\n PUBLIC SECTION.\n METHODS status RETURNING VALUE(result) TYPE i.\n METHODS body RETURNING VALUE(result) TYPE xstring.\n METHODS text RETURNING VALUE(result) TYPE string.\n METHODS header\n IMPORTING name TYPE string\n RETURNING VALUE(result) TYPE string.\n METHODS headers RETURNING VALUE(result) TYPE ${HTTP}=>kvs.\n\n PRIVATE SECTION.\n METHODS constructor\n IMPORTING status_code TYPE i\n body_bytes TYPE xstring\n body_text TYPE string\n header_list TYPE ${HTTP}=>kvs.\n\n DATA status_code TYPE i.\n DATA body_bytes TYPE xstring.\n DATA body_text TYPE string.\n DATA header_list TYPE ${HTTP}=>kvs.\nENDCLASS.\n\nCLASS ${JSON_PARSER} DEFINITION FINAL CREATE PRIVATE FRIENDS ${JSON_CLS}.\n PUBLIC SECTION.\n METHODS to\n IMPORTING target TYPE REF TO data.\n\n PRIVATE SECTION.\n METHODS constructor\n IMPORTING json_text TYPE string.\n\n DATA json_text TYPE string.\nENDCLASS.\n\nCLASS ${JSON_CLS} DEFINITION FINAL CREATE PRIVATE.\n PUBLIC SECTION.\n CLASS-METHODS stringify\n IMPORTING data TYPE any\n RETURNING VALUE(result) TYPE string.\n\n CLASS-METHODS render\n IMPORTING data TYPE any\n RETURNING VALUE(result) TYPE xstring.\n\n CLASS-METHODS parse\n IMPORTING source TYPE any\n RETURNING VALUE(result) TYPE REF TO ${JSON_PARSER}.\nENDCLASS.\n`;\n}\n","/**\n * ABAP template: `<cls>.clas.locals_imp.abap`.\n *\n * Implementations for the four local classes declared in\n * `locals_def.abap`. Uses SAP kernel APIs that are part of the Steampunk\n * (s4-cloud) whitelist only:\n * - cl_http_destination_provider=>create_by_destination\n * (parameter name on cloud: `i_destination` (not `i_name` or `i_destination_name`))\n * - cl_web_http_client_manager=>create_by_http_destination\n * - if_web_http_request->set_binary (NOT set_binary_body — Steampunk\n * rejects with \"Method SET_BINARY_BODY does not exist\")\n * - if_web_http_client verb constants typed as `if_web_http_client=>method`\n * (SWITCH must produce the enum type, not `string`)\n * - /ui2/cl_json=>serialize / deserialize (camelCase mode)\n * - cl_abap_conv_codepage=>create_in / create_out\n * - cl_web_http_utility->escape_url (cl_http_utility is NOT permitted\n * in ABAP Cloud)\n * - cl_abap_typedescr=>describe_by_data (DESCRIBE FIELD is disallowed\n * in ABAP cloud; use RTTI)\n *\n * No reference to /ui2/cl_json=>generate, xco_cp_json, cl_http_client,\n * cl_http_utility, cl_rest_http_client, DESCRIBE FIELD, or any Z-prefixed\n * symbol.\n */\nimport type { LocalClassesNames } from './locals-def.abap';\n\nexport function buildLocalsImp(names: LocalClassesNames): string {\n const {\n localJsonClass: JSON_CLS,\n localJsonParserClass: JSON_PARSER,\n localResponseClass: RESPONSE,\n localHttpClass: HTTP,\n } = names;\n\n return `* Generated by @abapify/openai-codegen - local class implementations.\n* ZERO Z-dependencies: uses SAP kernel APIs only (Steampunk whitelist).\n\nCLASS ${HTTP} IMPLEMENTATION.\n\n METHOD constructor.\n me->destination = destination.\n me->server = server.\n ENDMETHOD.\n\n METHOD build_query_string.\n DATA parts TYPE string_table.\n LOOP AT query ASSIGNING FIELD-SYMBOL(<q>).\n DATA(enc_n) = cl_web_http_utility=>escape_url( unescaped = <q>-name ).\n DATA(enc_v) = cl_web_http_utility=>escape_url( unescaped = <q>-value ).\n APPEND |{ enc_n }={ enc_v }| TO parts.\n ENDLOOP.\n result = concat_lines_of( table = parts sep = \\`&\\` ).\n ENDMETHOD.\n\n METHOD fetch.\n \" Prefix with the configured server base path when set,\n \" so OpenAPI specs with a non-root server still resolve correctly.\n DATA full_path TYPE string.\n full_path = COND string(\n WHEN server IS INITIAL THEN path\n ELSE |{ server }{ path }| ).\n IF query IS NOT INITIAL.\n full_path = |{ full_path }?{ build_query_string( query ) }|.\n ENDIF.\n\n DATA dest TYPE REF TO if_http_destination.\n dest = cl_http_destination_provider=>create_by_destination(\n i_destination = CONV #( destination ) ).\n\n DATA client TYPE REF TO if_web_http_client.\n client = cl_web_http_client_manager=>create_by_http_destination(\n i_destination = dest ).\n\n \" All IO against client runs inside TRY ... CLEANUP so the HTTP\n \" connection is closed even when execute() / binary read / codepage\n \" conversion raise a kernel exception.\n TRY.\n DATA request TYPE REF TO if_web_http_request.\n request = client->get_http_request( ).\n request->set_uri_path( i_uri_path = full_path ).\n\n DATA verb TYPE if_web_http_client=>method.\n verb = SWITCH if_web_http_client=>method( method\n WHEN 'GET' THEN if_web_http_client=>get\n WHEN 'POST' THEN if_web_http_client=>post\n WHEN 'PUT' THEN if_web_http_client=>put\n WHEN 'DELETE' THEN if_web_http_client=>delete\n WHEN 'PATCH' THEN if_web_http_client=>patch\n WHEN 'HEAD' THEN if_web_http_client=>head\n WHEN 'OPTIONS' THEN if_web_http_client=>options\n ELSE if_web_http_client=>get ).\n\n LOOP AT headers ASSIGNING FIELD-SYMBOL(<h>).\n request->set_header_field( i_name = <h>-name\n i_value = <h>-value ).\n ENDLOOP.\n\n IF binary IS NOT INITIAL.\n request->set_binary( i_data = binary ).\n ELSEIF body IS NOT INITIAL.\n request->set_text( i_text = body ).\n ENDIF.\n\n DATA resp TYPE REF TO if_web_http_response.\n resp = client->execute( i_method = verb ).\n\n DATA status_code TYPE i.\n status_code = resp->get_status( )-code.\n\n DATA body_bytes TYPE xstring.\n body_bytes = resp->get_binary( ).\n\n DATA body_text TYPE string.\n IF body_bytes IS NOT INITIAL.\n body_text = cl_abap_conv_codepage=>create_in( )->convert(\n source = body_bytes ).\n ENDIF.\n\n DATA raw_headers TYPE if_web_http_request=>name_value_pairs.\n raw_headers = resp->get_header_fields( ).\n\n DATA header_list TYPE kvs.\n LOOP AT raw_headers ASSIGNING FIELD-SYMBOL(<rh>).\n APPEND VALUE #( name = <rh>-name\n value = <rh>-value ) TO header_list.\n ENDLOOP.\n\n response = NEW ${RESPONSE}(\n status_code = status_code\n body_bytes = body_bytes\n body_text = body_text\n header_list = header_list ).\n\n client->close( ).\n CLEANUP.\n client->close( ).\n ENDTRY.\n ENDMETHOD.\n\nENDCLASS.\n\nCLASS ${RESPONSE} IMPLEMENTATION.\n\n METHOD constructor.\n me->status_code = status_code.\n me->body_bytes = body_bytes.\n me->body_text = body_text.\n me->header_list = header_list.\n ENDMETHOD.\n\n METHOD status.\n result = status_code.\n ENDMETHOD.\n\n METHOD body.\n result = body_bytes.\n ENDMETHOD.\n\n METHOD text.\n result = body_text.\n ENDMETHOD.\n\n METHOD headers.\n result = header_list.\n ENDMETHOD.\n\n METHOD header.\n DATA needle TYPE string.\n needle = to_lower( name ).\n LOOP AT header_list ASSIGNING FIELD-SYMBOL(<h>).\n IF to_lower( <h>-name ) = needle.\n result = <h>-value.\n RETURN.\n ENDIF.\n ENDLOOP.\n ENDMETHOD.\n\nENDCLASS.\n\nCLASS ${JSON_PARSER} IMPLEMENTATION.\n\n METHOD constructor.\n me->json_text = json_text.\n ENDMETHOD.\n\n METHOD to.\n FIELD-SYMBOLS <t> TYPE any.\n ASSIGN target->* TO <t>.\n /ui2/cl_json=>deserialize(\n EXPORTING json = json_text\n pretty_name = /ui2/cl_json=>pretty_mode-camel_case\n CHANGING data = <t> ).\n ENDMETHOD.\n\nENDCLASS.\n\nCLASS ${JSON_CLS} IMPLEMENTATION.\n\n METHOD stringify.\n result = /ui2/cl_json=>serialize(\n data = data\n pretty_name = /ui2/cl_json=>pretty_mode-camel_case\n compress = abap_true ).\n ENDMETHOD.\n\n METHOD render.\n DATA text TYPE string.\n text = stringify( data ).\n result = cl_abap_conv_codepage=>create_out( )->convert(\n source = text ).\n ENDMETHOD.\n\n METHOD parse.\n DATA text TYPE string.\n FIELD-SYMBOLS <s> TYPE any.\n ASSIGN source TO <s>.\n \" RTTI dispatch — static type inspection is used instead of the\n \" legacy DESCRIBE statement, which is not allowed on ABAP cloud.\n DATA type_info TYPE REF TO cl_abap_typedescr.\n type_info = cl_abap_typedescr=>describe_by_data( <s> ).\n IF type_info->type_kind = cl_abap_typedescr=>typekind_xstring.\n DATA bytes TYPE xstring.\n bytes = <s>.\n text = cl_abap_conv_codepage=>create_in( )->convert(\n source = bytes ).\n ELSE.\n text = <s>.\n ENDIF.\n result = NEW ${JSON_PARSER}( json_text = text ).\n ENDMETHOD.\n\nENDCLASS.\n`;\n}\n","/**\n * Local-class bundle emitter for generated implementation classes.\n *\n * The generated ZCL_<name> class bundles four local helper classes inside\n * its abapGit `locals_def.abap` / `locals_imp.abap` includes. These locals\n * wrap SAP kernel APIs (cl_web_http_client_manager,\n * cl_http_destination_provider, cl_http_utility, /ui2/cl_json,\n * cl_abap_conv_codepage) and expose a fetch-like + JSON-like API.\n *\n * This module is a thin orchestrator over the two template files.\n */\nimport type { ResolvedNames } from './naming';\nimport { buildLocalsDef } from './templates/locals-def.abap';\nimport { buildLocalsImp } from './templates/locals-imp.abap';\n\nexport interface LocalClassesBundle {\n /** Content for <cls>.clas.locals_def.abap. */\n localsDef: string;\n /** Content for <cls>.clas.locals_imp.abap. */\n localsImp: string;\n}\n\nexport function emitLocalClasses(names: ResolvedNames): LocalClassesBundle {\n const templateNames = {\n exceptionClass: names.exceptionClass,\n localJsonClass: names.localJsonClass,\n localJsonParserClass: names.localJsonParserClass,\n localResponseClass: names.localResponseClass,\n localHttpClass: names.localHttpClass,\n };\n return {\n localsDef: buildLocalsDef(templateNames),\n localsImp: buildLocalsImp(templateNames),\n };\n}\n","/**\n * Response-mapper for openai-codegen v2.\n *\n * Produces the `CASE reply->status( ) ... ENDCASE.` block that lives inside\n * each generated implementation method, directly mapping the operation's\n * OpenAPI `responses` object onto ABAP branches.\n *\n * NOTE: `@abapify/abap-ast` does not currently model `CASE`/`WHEN` as a\n * dedicated statement node. To keep this change narrowly scoped (and to\n * avoid racing other agents on abap-ast), the emitted block is returned as\n * a single `raw({ source })` statement. The AST wrapper is only a transport\n * for the final ABAP source; callers append it to a method body exactly\n * like any other statement.\n */\nimport { raw, type Statement } from '@abapify/abap-ast';\nimport type { NormalizedOperation, NormalizedResponse } from '../oas/types';\n\nexport type SuccessBodyKind =\n | { kind: 'json'; returningName: string }\n | { kind: 'empty'; returningName: string }\n | { kind: 'binary'; returningName: string };\n\nexport interface ResponseMapperOptions {\n /** Fully-qualified ABAP exception class name. */\n exceptionClassName: string;\n /** Local class name used for JSON parsing (usually `json`). */\n localJsonClassName: string;\n /** Name of the local variable holding the fetch result. Default `response`. */\n responseVarName?: string;\n /** Determines how the 2xx / success branch is emitted. */\n successBody: SuccessBodyKind;\n}\n\nexport interface ResponseMapperResult {\n /** AST statement ready to append to a method body (wraps the CASE source). */\n statement: Statement;\n /** Raw ABAP source, formatted for insertion into a METHOD body. */\n source: string;\n}\n\n/**\n * Escape an arbitrary string so it can be embedded inside an ABAP single-\n * quoted literal. Single quotes are doubled; newlines collapse to spaces.\n */\nfunction escapeAbapLiteral(input: string): string {\n return input.replaceAll(/[\\r\\n]+/g, ' ').replaceAll(\"'\", \"''\");\n}\n\ninterface PickedSuccess {\n /** Either a numeric HTTP status code as a string, or 'default'. */\n statusCode: string;\n whenLabel: string; // '200' or 'OTHERS'\n}\n\n/**\n * Pick which response drives the success branch.\n *\n * Preference order:\n * 1. Lowest numeric 2xx status code.\n * 2. `default` if no 2xx exists (treated as success — WHEN OTHERS).\n * 3. `undefined` — caller falls back to synthesising a generic WHEN.\n */\nfunction pickSuccessStatus(\n responses: readonly NormalizedResponse[],\n): PickedSuccess | undefined {\n const twoXX = responses\n .filter((r) => /^2\\d\\d$/.test(r.statusCode))\n .map((r) => r.statusCode)\n .sort((a, b) => Number(a) - Number(b));\n if (twoXX.length > 0) {\n return { statusCode: twoXX[0], whenLabel: twoXX[0] };\n }\n const def = responses.find((r) => r.statusCode === 'default');\n // Only treat `default` as the success branch when it is NOT marked as an\n // error response. When it IS an error, fall through so the caller emits\n // a synthetic generic success WHEN and lets the error-branch loop /\n // OTHERS branch handle `default`.\n if (def !== undefined && !def.isError) {\n return { statusCode: 'default', whenLabel: 'OTHERS' };\n }\n return undefined;\n}\n\nfunction renderSuccessBody(opts: ResponseMapperOptions): string {\n const { successBody } = opts;\n const responseVar = opts.responseVarName ?? 'response';\n switch (successBody.kind) {\n case 'json':\n return `${opts.localJsonClassName}=>parse( ${responseVar}->body( ) )->to( REF #( ${successBody.returningName} ) ).`;\n case 'empty':\n return `${successBody.returningName} = abap_true.`;\n case 'binary':\n return `${successBody.returningName} = ${responseVar}->body( ).`;\n }\n}\n\nfunction renderErrorBranch(\n statusCode: string,\n description: string | undefined,\n opts: ResponseMapperOptions,\n): string[] {\n const responseVar = opts.responseVarName ?? 'response';\n const lines: string[] = [];\n lines.push(` WHEN ${statusCode}.`);\n lines.push(` RAISE EXCEPTION NEW ${opts.exceptionClassName}(`);\n lines.push(` status = ${statusCode}`);\n if (description !== undefined && description.length > 0) {\n lines.push(` description = '${escapeAbapLiteral(description)}'`);\n }\n lines.push(` body = ${responseVar}->body( ) ).`);\n return lines;\n}\n\nfunction renderOthersBranch(\n description: string | undefined,\n opts: ResponseMapperOptions,\n): string[] {\n const responseVar = opts.responseVarName ?? 'response';\n const lines: string[] = [];\n lines.push(` WHEN OTHERS.`);\n lines.push(` RAISE EXCEPTION NEW ${opts.exceptionClassName}(`);\n lines.push(` status = ${responseVar}->status( )`);\n if (description !== undefined && description.length > 0) {\n lines.push(` description = '${escapeAbapLiteral(description)}'`);\n }\n lines.push(` body = ${responseVar}->body( ) ).`);\n return lines;\n}\n\nexport function mapResponseHandling(\n operation: NormalizedOperation,\n opts: ResponseMapperOptions,\n): ResponseMapperResult {\n const responseVar = opts.responseVarName ?? 'response';\n const lines: string[] = [];\n lines.push(`CASE ${responseVar}->status( ).`);\n\n const success = pickSuccessStatus(operation.responses);\n\n const successConsumedOthers =\n success !== undefined && success.whenLabel === 'OTHERS';\n\n // Emit the explicit success WHEN first unless `default` itself is the\n // success (WHEN OTHERS), in which case we must defer it so it remains\n // the *last* branch — ABAP forbids any WHEN after OTHERS.\n if (success !== undefined && !successConsumedOthers) {\n lines.push(` WHEN ${success.whenLabel}.`);\n lines.push(` ${renderSuccessBody(opts)}`);\n }\n\n // Error branches: every isError response with a numeric status code gets\n // its own WHEN. Same description over multiple codes still emits one\n // branch per code (clarity > compression).\n for (const resp of operation.responses) {\n if (!resp.isError) continue;\n if (resp.statusCode === 'default') continue;\n if (!/^\\d+$/.test(resp.statusCode)) continue;\n lines.push(...renderErrorBranch(resp.statusCode, resp.description, opts));\n }\n\n // Final WHEN OTHERS:\n // - If `default` is the success (successConsumedOthers), emit it as\n // the terminal OTHERS branch now that all error WHENs are already\n // emitted.\n // - Else, emit a generic error fallback, using `default`'s description\n // when it exists and is an error.\n if (successConsumedOthers) {\n lines.push(` WHEN OTHERS.`);\n lines.push(` ${renderSuccessBody(opts)}`);\n } else {\n const defaultResp = operation.responses.find(\n (r) => r.statusCode === 'default',\n );\n const description =\n defaultResp !== undefined && defaultResp.isError\n ? defaultResp.description\n : undefined;\n lines.push(...renderOthersBranch(description, opts));\n }\n\n lines.push(`ENDCASE.`);\n const source = lines.join('\\n');\n return { statement: raw({ source }), source };\n}\n","/**\n * ABAP identifier validation shared by all format writers.\n *\n * Rules (SAP repository object naming):\n * - Must start with 'Z' or 'Y' (customer namespace)\n * - Allowed characters: A-Z, 0-9, '_'\n * - Max 30 characters\n * - Must be uppercase\n */\nexport function assertValidClassName(name: string): void {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('className must be a non-empty string');\n }\n if (name.length > 30) {\n throw new Error(`Invalid ABAP class name '${name}': exceeds 30 characters`);\n }\n if (!/^[ZY][A-Z0-9_]*$/.test(name)) {\n throw new Error(\n `Invalid ABAP class name '${name}': must be uppercase, start with Z or Y, and contain only A-Z, 0-9, _`,\n );\n }\n}\n","/**\n * abapGit format writer.\n *\n * Produces the canonical layout consumed by the abapGit import flow:\n *\n * <outDir>/\n * package.devc.xml\n * src/<name>.clas.abap\n * src/<name>.clas.xml\n * src/<name>.clas.testclasses.abap (optional)\n * src/<name>.clas.locals_def.abap (optional)\n *\n * File names are lowercase (abapGit convention). The `.clas.xml` envelope is\n * parameterised on CLSNAME / DESCRIPT / LANGU only — STATE/CLSCCINCL/FIXPT/\n * UNICODE are fixed to the defaults emitted by the SAP serializer for a\n * freshly-generated global class (mirrors samples/petstore-abapgit/).\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { ClassArtifact, InterfaceArtifact, WriteResult } from './types';\nimport { assertValidClassName } from './validate';\n\nconst PACKAGE_DEVC_XML = `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<asx:abap xmlns:asx=\"http://www.sap.com/abapxml\" version=\"1.0\">\n <asx:values>\n <DEVC>\n <CTEXT>Generated by @abapify/openai-codegen</CTEXT>\n </DEVC>\n </asx:values>\n</asx:abap>\n`;\n\nfunction buildClasXml(\n className: string,\n description: string,\n language: string,\n): string {\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<abapGit version=\"v1.0.0\" serializer=\"LCL_OBJECT_CLAS\" serializer_version=\"v1.0.0\">\n <asx:abap xmlns:asx=\"http://www.sap.com/abapxml\" version=\"1.0\">\n <asx:values>\n <VSEOCLASS>\n <CLSNAME>${className}</CLSNAME>\n <LANGU>${language}</LANGU>\n <DESCRIPT>${escapeXml(description)}</DESCRIPT>\n <STATE>1</STATE>\n <CLSCCINCL>X</CLSCCINCL>\n <FIXPT>X</FIXPT>\n <UNICODE>X</UNICODE>\n <ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>\n </VSEOCLASS>\n </asx:values>\n </asx:abap>\n</abapGit>\n`;\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll(/&/g, '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll(\"'\", '&apos;');\n}\n\nexport async function writeAbapgitLayout(\n artifact: ClassArtifact,\n outDir: string,\n): Promise<WriteResult> {\n assertValidClassName(artifact.className);\n\n const language = artifact.language ?? 'E';\n const description = artifact.description ?? artifact.className;\n const base = artifact.className.toLowerCase();\n\n const srcDir = join(outDir, 'src');\n await mkdir(srcDir, { recursive: true });\n\n const written: string[] = [];\n\n const pkgPath = join(outDir, 'package.devc.xml');\n await writeFile(pkgPath, PACKAGE_DEVC_XML, 'utf-8');\n written.push('package.devc.xml');\n\n const mainAbap = join(srcDir, `${base}.clas.abap`);\n await writeFile(mainAbap, artifact.mainSource, 'utf-8');\n written.push(`src/${base}.clas.abap`);\n\n const clasXml = join(srcDir, `${base}.clas.xml`);\n await writeFile(\n clasXml,\n buildClasXml(artifact.className, description, language),\n 'utf-8',\n );\n written.push(`src/${base}.clas.xml`);\n\n if (artifact.testSource !== undefined) {\n const p = join(srcDir, `${base}.clas.testclasses.abap`);\n await writeFile(p, artifact.testSource, 'utf-8');\n written.push(`src/${base}.clas.testclasses.abap`);\n }\n\n if (artifact.localsDefSource !== undefined) {\n const p = join(srcDir, `${base}.clas.locals_def.abap`);\n await writeFile(p, artifact.localsDefSource, 'utf-8');\n written.push(`src/${base}.clas.locals_def.abap`);\n }\n\n if (artifact.localsImpSource !== undefined) {\n const p = join(srcDir, `${base}.clas.locals_imp.abap`);\n await writeFile(p, artifact.localsImpSource, 'utf-8');\n written.push(`src/${base}.clas.locals_imp.abap`);\n }\n\n written.sort((a, b) => a.localeCompare(b));\n return { files: written };\n}\n\nfunction buildIntfXml(\n name: string,\n description: string,\n language: string,\n): string {\n return `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<abapGit version=\"v1.0.0\" serializer=\"LCL_OBJECT_INTF\" serializer_version=\"v1.0.0\">\n <asx:abap xmlns:asx=\"http://www.sap.com/abapxml\" version=\"1.0\">\n <asx:values>\n <VSEOINTERF>\n <CLSNAME>${name}</CLSNAME>\n <LANGU>${language}</LANGU>\n <DESCRIPT>${escapeXml(description)}</DESCRIPT>\n <EXPOSURE>2</EXPOSURE>\n <STATE>1</STATE>\n <UNICODE>X</UNICODE>\n <ABAP_LANGUAGE_VERSION>5</ABAP_LANGUAGE_VERSION>\n </VSEOINTERF>\n </asx:values>\n </asx:abap>\n</abapGit>\n`;\n}\n\nexport async function writeAbapgitInterface(\n artifact: InterfaceArtifact,\n outDir: string,\n): Promise<WriteResult> {\n assertValidClassName(artifact.name);\n\n const language = artifact.language ?? 'E';\n const description = artifact.description ?? artifact.name;\n const base = artifact.name.toLowerCase();\n\n const srcDir = join(outDir, 'src');\n await mkdir(srcDir, { recursive: true });\n\n const written: string[] = [];\n\n const pkgPath = join(outDir, 'package.devc.xml');\n await writeFile(pkgPath, PACKAGE_DEVC_XML, 'utf-8');\n written.push('package.devc.xml');\n\n const intfAbap = join(srcDir, `${base}.intf.abap`);\n await writeFile(intfAbap, artifact.source, 'utf-8');\n written.push(`src/${base}.intf.abap`);\n\n const intfXml = join(srcDir, `${base}.intf.xml`);\n await writeFile(\n intfXml,\n buildIntfXml(artifact.name, description, language),\n 'utf-8',\n );\n written.push(`src/${base}.intf.xml`);\n\n written.sort((a, b) => a.localeCompare(b));\n return { files: written };\n}\n","/**\n * gCTS / AFF format writer.\n *\n * gCTS (git-enabled CTS) and AFF (SAP/abap-file-formats) share the same\n * on-disk layout: JSON metadata, per-object subdirectory named after the\n * lowercased object name, `<name>.<type>.<ext>` naming.\n *\n * For a class this produces:\n *\n * <outDir>/\n * package.devc.json\n * CLAS/<name>/<name>.clas.json\n * CLAS/<name>/<name>.clas.abap\n * CLAS/<name>/<name>.clas.testclasses.abap (optional)\n * CLAS/<name>/<name>.clas.locals_def.abap (optional)\n * CLAS/<name>/<name>.clas.locals_imp.abap (optional)\n *\n * The `CLAS/` object-type subdirectory mirrors the layout used by gCTS\n * repositories (objects grouped under their type code). See\n * `packages/adt-plugin-gcts/` for filename conventions.\n */\n\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { ClassArtifact, InterfaceArtifact, WriteResult } from './types';\nimport { assertValidClassName } from './validate';\n\nconst PACKAGE_DEVC_JSON =\n JSON.stringify(\n {\n header: {\n formatVersion: '1.0',\n description: 'Generated by @abapify/openai-codegen',\n },\n package: {\n softwareComponent: 'LOCAL',\n },\n },\n null,\n 2,\n ) + '\\n';\n\nfunction buildClasJson(\n className: string,\n description: string,\n language: string,\n): string {\n return (\n JSON.stringify(\n {\n header: {\n formatVersion: '1.0',\n description,\n originalLanguage: language,\n // `5` = ABAP for Cloud Development (Steampunk). Required for\n // deployments that target ABAP Cloud — without it gCTS imports\n // default to Standard ABAP and the object fails to activate on\n // BTP with S_ABPLNGVS errors.\n abapLanguageVersion: '5',\n },\n class: {\n name: className,\n category: '00',\n visibility: 'public',\n final: true,\n abstract: false,\n fixedPointArithmetic: true,\n unicodeChecksActive: true,\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport async function writeGctsLayout(\n artifact: ClassArtifact,\n outDir: string,\n): Promise<WriteResult> {\n assertValidClassName(artifact.className);\n\n const language = artifact.language ?? 'E';\n const description = artifact.description ?? artifact.className;\n const base = artifact.className.toLowerCase();\n const objectDir = join(outDir, 'CLAS', base);\n\n await mkdir(objectDir, { recursive: true });\n\n const written: string[] = [];\n\n const pkgPath = join(outDir, 'package.devc.json');\n await writeFile(pkgPath, PACKAGE_DEVC_JSON, 'utf-8');\n written.push('package.devc.json');\n\n const metaPath = join(objectDir, `${base}.clas.json`);\n await writeFile(\n metaPath,\n buildClasJson(artifact.className, description, language),\n 'utf-8',\n );\n written.push(`CLAS/${base}/${base}.clas.json`);\n\n const mainPath = join(objectDir, `${base}.clas.abap`);\n await writeFile(mainPath, artifact.mainSource, 'utf-8');\n written.push(`CLAS/${base}/${base}.clas.abap`);\n\n if (artifact.testSource !== undefined) {\n const p = join(objectDir, `${base}.clas.testclasses.abap`);\n await writeFile(p, artifact.testSource, 'utf-8');\n written.push(`CLAS/${base}/${base}.clas.testclasses.abap`);\n }\n\n if (artifact.localsDefSource !== undefined) {\n const p = join(objectDir, `${base}.clas.locals_def.abap`);\n await writeFile(p, artifact.localsDefSource, 'utf-8');\n written.push(`CLAS/${base}/${base}.clas.locals_def.abap`);\n }\n\n if (artifact.localsImpSource !== undefined) {\n const p = join(objectDir, `${base}.clas.locals_imp.abap`);\n await writeFile(p, artifact.localsImpSource, 'utf-8');\n written.push(`CLAS/${base}/${base}.clas.locals_imp.abap`);\n }\n\n written.sort((a, b) => a.localeCompare(b));\n return { files: written };\n}\n\nfunction buildIntfJson(\n name: string,\n description: string,\n language: string,\n): string {\n return (\n JSON.stringify(\n {\n header: {\n formatVersion: '1.0',\n description,\n originalLanguage: language,\n // Mirrors the class-envelope rule: every gCTS metadata file\n // carries `abapLanguageVersion: '5'` so BTP Steampunk imports\n // don't default back to Standard ABAP.\n abapLanguageVersion: '5',\n },\n interface: {\n name,\n visibility: 'public',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport async function writeGctsInterface(\n artifact: InterfaceArtifact,\n outDir: string,\n): Promise<WriteResult> {\n assertValidClassName(artifact.name);\n\n const language = artifact.language ?? 'E';\n const description = artifact.description ?? artifact.name;\n const base = artifact.name.toLowerCase();\n const objectDir = join(outDir, 'INTF', base);\n\n await mkdir(objectDir, { recursive: true });\n\n const written: string[] = [];\n\n const pkgPath = join(outDir, 'package.devc.json');\n await writeFile(pkgPath, PACKAGE_DEVC_JSON, 'utf-8');\n written.push('package.devc.json');\n\n const metaPath = join(objectDir, `${base}.intf.json`);\n await writeFile(\n metaPath,\n buildIntfJson(artifact.name, description, language),\n 'utf-8',\n );\n written.push(`INTF/${base}/${base}.intf.json`);\n\n const mainPath = join(objectDir, `${base}.intf.abap`);\n await writeFile(mainPath, artifact.source, 'utf-8');\n written.push(`INTF/${base}/${base}.intf.abap`);\n\n written.sort((a, b) => a.localeCompare(b));\n return { files: written };\n}\n","/**\n * Format plugins barrel.\n *\n * Exposes per-format writers and a {@link writeLayout} dispatch helper that\n * selects the writer from an {@link OutputFormat} string. A\n * {@link writeClientBundle} helper writes the full four-artifact client\n * (types interface, operations interface, exception class, implementation\n * class) in one shot.\n */\n\nimport { writeAbapgitInterface, writeAbapgitLayout } from './abapgit';\nimport { writeGctsInterface, writeGctsLayout } from './gcts';\nimport type {\n ClassArtifact,\n InterfaceArtifact,\n OutputFormat,\n WriteResult,\n} from './types';\n\nexport { writeAbapgitInterface, writeAbapgitLayout } from './abapgit';\nexport { writeGctsInterface, writeGctsLayout } from './gcts';\nexport type {\n ArtifactKind,\n ClassArtifact,\n InterfaceArtifact,\n OutputFormat,\n WriteResult,\n} from './types';\n\nfunction isInterfaceArtifact(\n artifact: ClassArtifact | InterfaceArtifact,\n): artifact is InterfaceArtifact {\n return (\n typeof (artifact as InterfaceArtifact).name === 'string' &&\n typeof (artifact as InterfaceArtifact).source === 'string'\n );\n}\n\nexport function writeLayout(\n artifact: ClassArtifact | InterfaceArtifact,\n format: OutputFormat,\n outDir: string,\n): Promise<WriteResult> {\n if (isInterfaceArtifact(artifact)) {\n switch (format) {\n case 'abapgit':\n return writeAbapgitInterface(artifact, outDir);\n case 'gcts':\n return writeGctsInterface(artifact, outDir);\n default: {\n const exhaustive: never = format;\n throw new Error(`Unknown output format: ${String(exhaustive)}`);\n }\n }\n }\n\n switch (format) {\n case 'abapgit':\n return writeAbapgitLayout(artifact, outDir);\n case 'gcts':\n return writeGctsLayout(artifact, outDir);\n default: {\n const exhaustive: never = format;\n throw new Error(`Unknown output format: ${String(exhaustive)}`);\n }\n }\n}\n\nexport interface ClientBundle {\n types: InterfaceArtifact;\n operations: InterfaceArtifact;\n exception: ClassArtifact;\n implementation: ClassArtifact;\n}\n\nexport async function writeClientBundle(\n artifacts: ClientBundle,\n format: OutputFormat,\n outDir: string,\n): Promise<WriteResult> {\n const all = new Set<string>();\n for (const artifact of [\n artifacts.types,\n artifacts.operations,\n artifacts.exception,\n artifacts.implementation,\n ] as const) {\n const r = await writeLayout(artifact, format, outDir);\n for (const f of r.files) {\n all.add(f);\n }\n }\n return { files: [...all].sort((a, b) => a.localeCompare(b)) };\n}\n","/**\n * Layer 3 emitter — IMPLEMENTATION CLASS (`ZCL_<base>`).\n *\n * The generated class is deliberately minimal: it INTERFACES the operations\n * interface, holds one private reference to the bundled local HTTP client,\n * and emits one METHOD per operation whose body:\n *\n * 1. Calls `client->fetch( ... )` with method / path / query / headers /\n * body, capturing the result in `DATA(response)`.\n * 2. Delegates to the response-mapper to emit the `CASE response->status( )`\n * block that turns each OpenAPI response onto either a RETURNING\n * assignment or a `RAISE EXCEPTION NEW zcx_...` statement.\n *\n * The @abapify/abap-ast printer does not currently model `CASE` / `WHEN`\n * nodes, and modelling a mixed-indent multi-line method call via the call\n * expression is awkward. For these two shapes we use `raw({ source })`\n * statements — the printer emits them verbatim at the current indent.\n */\nimport {\n attributeDef,\n builtinType,\n classDef,\n literal,\n methodDef,\n methodImpl,\n methodParam,\n namedTypeRef,\n raw,\n section,\n type ClassDef,\n type Statement,\n} from '@abapify/abap-ast';\n\nimport { mapResponseHandling, type SuccessBodyKind } from './response-mapper';\nimport type { ResolvedNames } from './naming';\nimport type { OperationMapping } from './operations-interface';\nimport type {\n JsonSchema,\n NormalizedOperation,\n NormalizedResponse,\n NormalizedSpec,\n} from '../oas/types';\nimport { isRef } from '../oas/types';\n\n// -----------------------------------------------------------------------\n// Public API\n// -----------------------------------------------------------------------\n\nexport interface EmitImplementationClassOptions {\n readonly names: ResolvedNames;\n /** Default server path written into the constructor DEFAULT clause. */\n readonly defaultServer?: string;\n}\n\nexport interface EmitImplementationClassResult {\n readonly class: ClassDef;\n}\n\nexport function emitImplementationClass(\n spec: NormalizedSpec,\n operations: readonly OperationMapping[],\n opts: EmitImplementationClassOptions,\n): EmitImplementationClassResult {\n const { names } = opts;\n const className = names.implementationClass;\n const ifaceName = names.operationsInterface.toLowerCase();\n const httpLocal = names.localHttpClass;\n const jsonLocal = names.localJsonClass;\n const excLocal = names.exceptionClass.toLowerCase();\n const defaultServer = opts.defaultServer ?? '/api/v3';\n\n // -- PUBLIC SECTION ---------------------------------------------------\n // INTERFACES zif_<op>. plus METHODS constructor.\n const ctorDecl = methodDef({\n name: 'constructor',\n visibility: 'public',\n params: [\n methodParam({\n paramKind: 'importing',\n name: 'destination',\n typeRef: builtinType({ name: 'string' }),\n }),\n methodParam({\n paramKind: 'importing',\n name: 'server',\n typeRef: builtinType({ name: 'string' }),\n default: literal({ literalKind: 'string', value: defaultServer }),\n }),\n ],\n });\n\n const publicSection = section({\n visibility: 'public',\n members: [ctorDecl],\n });\n\n // -- PRIVATE SECTION --------------------------------------------------\n // DATA client TYPE REF TO lcl_http.\n // Abused: NamedTypeRef stores the raw inline type after \"TYPE \".\n const clientAttr = attributeDef({\n name: 'client',\n type: namedTypeRef({ name: `REF TO ${httpLocal}` }),\n visibility: 'private',\n });\n\n const privateSection = section({\n visibility: 'private',\n members: [clientAttr],\n });\n\n // -- IMPLEMENTATIONS -------------------------------------------------\n const ctorImpl = methodImpl({\n name: 'constructor',\n body: [\n raw({\n source: `client = NEW ${httpLocal}( destination = destination server = server ).`,\n }),\n ],\n });\n\n const byId = new Map<string, NormalizedOperation>();\n for (const op of spec.operations) byId.set(op.operationId, op);\n\n const operationImpls = operations.map((mapping) => {\n const op = byId.get(mapping.operationId);\n if (op === undefined) {\n throw new Error(\n `emitImplementationClass: operation \"${mapping.operationId}\" not found in spec`,\n );\n }\n const bodyStmts = buildOperationBody(op, mapping, {\n httpLocal,\n jsonLocal,\n exceptionClassName: excLocal,\n });\n return methodImpl({\n name: `${ifaceName}~${mapping.methodName}`,\n body: bodyStmts,\n });\n });\n\n const cls = classDef({\n name: className,\n interfaces: [ifaceName],\n sections: [publicSection, privateSection],\n implementations: [ctorImpl, ...operationImpls],\n });\n\n return { class: cls };\n}\n\n// -----------------------------------------------------------------------\n// Method body construction\n// -----------------------------------------------------------------------\n\ninterface BodyCtx {\n readonly httpLocal: string;\n readonly jsonLocal: string;\n readonly exceptionClassName: string;\n}\n\nfunction buildOperationBody(\n op: NormalizedOperation,\n mapping: OperationMapping,\n ctx: BodyCtx,\n): Statement[] {\n const bodySchema = pickRequestBodySchema(op);\n const bodyIsBinary = isBinaryRequestBody(op, bodySchema);\n\n const fetchSource = renderFetchCall(mapping, bodyIsBinary, ctx.jsonLocal);\n\n const successBody = decideSuccessBody(op, mapping);\n const caseResult = mapResponseHandling(op, {\n exceptionClassName: ctx.exceptionClassName,\n localJsonClassName: ctx.jsonLocal,\n successBody,\n });\n\n // Wrap the body in TRY/CATCH so that kernel HTTP exceptions\n // (CX_WEB_HTTP_CLIENT_ERROR, CX_HTTP_DEST_PROVIDER_ERROR) are translated\n // into the codegen's own exception type. This keeps the public method\n // signature RAISING only the generated exception class and satisfies the\n // Steampunk 'exception not caught or declared' activation warning.\n const excName = ctx.exceptionClassName;\n return [\n raw({ source: 'TRY.' }),\n raw({ source: fetchSource }),\n caseResult.statement,\n raw({\n source: ` CATCH cx_web_http_client_error cx_http_dest_provider_error INTO DATA(_http_err).`,\n }),\n raw({\n source:\n ` RAISE EXCEPTION NEW ${excName}(\\n` +\n ` status = 0\\n` +\n ` description = _http_err->get_text( ) ).`,\n }),\n raw({ source: 'ENDTRY.' }),\n ];\n}\n\n// -----------------------------------------------------------------------\n// fetch( ... ) call rendering\n// -----------------------------------------------------------------------\n\nfunction renderFetchCall(\n mapping: OperationMapping,\n bodyIsBinary: boolean,\n jsonLocalClass: string,\n): string {\n type Arg = { readonly key: string; readonly value: string };\n const args: Arg[] = [];\n\n args.push({ key: 'method', value: `'${mapping.method}'` });\n args.push({ key: 'path', value: renderPathValue(mapping) });\n\n const queryParams = mapping.params.filter((p) => p.location === 'query');\n if (queryParams.length > 0) {\n // Non-table params become direct entries; table params use FOR loop\n // comprehensions. Both forms mix inside a single VALUE #( ... ) table.\n const items = queryParams\n .map((p) => {\n const key = escapeSingleQuotes(p.openapiName);\n if (p.isTable) {\n const loopVar = `_${p.name}`;\n return `FOR ${loopVar} IN ${p.name} ( name = '${key}' value = ${loopVar} )`;\n }\n return `( name = '${key}' value = ${p.name} )`;\n })\n .join(' ');\n args.push({ key: 'query', value: `VALUE #( ${items} )` });\n }\n\n const headerParams = mapping.params.filter((p) => p.location === 'header');\n const headerItems: string[] = [];\n\n if (mapping.hasBody) {\n if (bodyIsBinary) {\n args.push({ key: 'binary', value: 'body' });\n } else {\n args.push({\n key: 'body',\n value: `${jsonLocalClass}=>stringify( body )`,\n });\n headerItems.push(`( name = 'Content-Type' value = 'application/json' )`);\n }\n }\n\n for (const h of headerParams) {\n headerItems.push(\n `( name = '${escapeSingleQuotes(h.openapiName)}' value = ${h.name} )`,\n );\n }\n\n if (headerItems.length > 0) {\n args.push({ key: 'headers', value: `VALUE #( ${headerItems.join(' ')} )` });\n }\n\n const head = 'DATA(response) = client->fetch(';\n // Single-line form for ≤ 2 args.\n if (args.length <= 2) {\n const inline = args.map((a) => `${a.key} = ${a.value}`).join(' ');\n return `${head} ${inline} ).`;\n }\n\n // Multi-line aligned form for 3+ args.\n const maxKey = Math.max(...args.map((a) => a.key.length));\n const lines: string[] = [head];\n args.forEach((a, idx) => {\n const pad = ' '.repeat(maxKey - a.key.length);\n const isLast = idx === args.length - 1;\n const tail = isLast ? ' ).' : '';\n lines.push(` ${a.key}${pad} = ${a.value}${tail}`);\n });\n return lines.join('\\n');\n}\n\n/** `'<path>'` when no path params, otherwise a `|...|` string template. */\nfunction renderPathValue(mapping: OperationMapping): string {\n const pathParams = mapping.params.filter((p) => p.location === 'path');\n if (pathParams.length === 0) {\n return `'${escapeSingleQuotes(mapping.path)}'`;\n }\n const byOriginal = new Map<string, string>();\n for (const p of pathParams) byOriginal.set(p.openapiName, p.name);\n\n let out = '|';\n let i = 0;\n const src = mapping.path;\n while (i < src.length) {\n const open = src.indexOf('{', i);\n if (open === -1) {\n out += src.slice(i);\n break;\n }\n out += src.slice(i, open);\n const close = src.indexOf('}', open);\n if (close === -1) {\n // Unclosed placeholder — emit verbatim to preserve source fidelity.\n out += src.slice(open);\n break;\n }\n const placeholder = src.slice(open + 1, close);\n const abapName = byOriginal.get(placeholder) ?? placeholder;\n out += `{ ${abapName} }`;\n i = close + 1;\n }\n out += '|';\n return out;\n}\n\n// -----------------------------------------------------------------------\n// Response-body and request-body shape inspection\n// -----------------------------------------------------------------------\n\nfunction decideSuccessBody(\n op: NormalizedOperation,\n mapping: OperationMapping,\n): SuccessBodyKind {\n if (mapping.successIsEmptyBody) {\n return { kind: 'empty', returningName: mapping.returningName };\n }\n const picked = pickSuccessResponse(op);\n const schema = picked ? pickPreferredSchema(picked.content) : undefined;\n if (schema !== undefined && isBinarySchema(schema)) {\n return { kind: 'binary', returningName: mapping.returningName };\n }\n // Default: JSON.\n return { kind: 'json', returningName: mapping.returningName };\n}\n\nfunction pickSuccessResponse(\n op: NormalizedOperation,\n): NormalizedResponse | undefined {\n const twoXX = op.responses\n .filter((r) => /^2\\d\\d$/.test(r.statusCode))\n .sort((a, b) => Number(a.statusCode) - Number(b.statusCode));\n if (twoXX.length > 0) return twoXX[0];\n return op.responses.find((r) => r.statusCode === 'default');\n}\n\nfunction pickRequestBodySchema(\n op: NormalizedOperation,\n): JsonSchema | undefined {\n const rb = op.requestBody;\n if (!rb) return undefined;\n return pickPreferredSchema(rb.content);\n}\n\nfunction pickPreferredSchema(\n content: Record<string, { schema: JsonSchema }> | undefined,\n): JsonSchema | undefined {\n if (!content) return undefined;\n const json = content['application/json'];\n if (json !== undefined) {\n return nonEmpty(json.schema);\n }\n const octet = content['application/octet-stream'];\n if (octet !== undefined) {\n return nonEmpty(octet.schema);\n }\n const first = Object.keys(content)[0];\n if (first !== undefined) return nonEmpty(content[first].schema);\n return undefined;\n}\n\nfunction nonEmpty(schema: JsonSchema | undefined): JsonSchema | undefined {\n if (schema === undefined) return undefined;\n return Object.keys(schema).length > 0 ? schema : undefined;\n}\n\nfunction isBinarySchema(schema: JsonSchema | undefined): boolean {\n if (!schema) return false;\n if (isRef(schema)) return false;\n const t = (schema as { type?: unknown }).type;\n const f = (schema as { format?: unknown }).format;\n return t === 'string' && (f === 'binary' || f === 'byte');\n}\n\nfunction isBinaryRequestBody(\n op: NormalizedOperation,\n schema: JsonSchema | undefined,\n): boolean {\n if (isBinarySchema(schema)) return true;\n const content = op.requestBody?.content;\n if (!content) return false;\n // If the only media type is octet-stream, treat as binary.\n const keys = Object.keys(content);\n if (keys.length === 1 && keys[0] === 'application/octet-stream') {\n return true;\n }\n return false;\n}\n\n// -----------------------------------------------------------------------\n// Misc.\n// -----------------------------------------------------------------------\n\nfunction escapeSingleQuotes(s: string): string {\n return s.replaceAll(\"'\", \"''\");\n}\n","/**\n * End-to-end pipeline for the v2 openai-codegen emitter.\n *\n * Loads an OpenAPI spec, plans types, runs the Layer-1 / Layer-2 / exception\n * / implementation / local-class emitters, prints each ABAP node through\n * `@abapify/abap-ast`, and hands the four artifacts to the configured format\n * writer (`abapgit` or `gcts`).\n */\n\nimport { print } from '@abapify/abap-ast';\nimport { loadSpec } from './oas/index';\nimport type { NormalizedSpec } from './oas/types';\nimport { planTypes } from './types/plan';\nimport {\n resolveNames,\n type NamesConfig,\n type ResolvedNames,\n} from './emit/naming';\nimport { emitTypesInterface } from './emit/types-interface';\nimport { emitOperationsInterface } from './emit/operations-interface';\nimport { emitExceptionClass } from './emit/exception-class';\nimport { emitImplementationClass } from './emit/implementation-class';\nimport { emitLocalClasses } from './emit/local-classes';\nimport {\n writeClientBundle,\n type ClassArtifact,\n type InterfaceArtifact,\n} from './format/index';\n\nexport type GenerateTarget =\n | 's4-cloud'\n | 's4-onprem-modern'\n | 'on-prem-classic';\n\nexport interface GenerateOptions {\n /** Path to the OpenAPI spec file, a URL, or a pre-parsed spec object. */\n input: string | URL | object;\n /** Output directory. Created if missing. */\n outDir: string;\n /** Output format (`abapgit` or `gcts`). */\n format: 'abapgit' | 'gcts';\n /** Target profile. Only `s4-cloud` is supported in v1. */\n target?: GenerateTarget;\n /**\n * Naming configuration. Exactly one of `names.base` or the individual\n * overrides must resolve all four global names.\n */\n names: NamesConfig;\n /**\n * Default server path written into the implementation-class constructor\n * DEFAULT clause. When omitted, derived from `spec.servers[0].url`\n * (path component) with a final fallback of `'/'`.\n */\n defaultServer?: string;\n /**\n * Class-level description embedded in `.clas.xml` / `.intf.xml` metadata.\n * Defaults to each artifact's own name.\n */\n description?: string;\n /**\n * When true, nullable fields receive a sibling `<field>_is_null` flag in\n * the types interface. Default false.\n */\n emitNullFlags?: boolean;\n}\n\nexport interface GenerateResult {\n /** All written files, relative to `outDir`, sorted. */\n files: readonly string[];\n /** Resolved ABAP global / local names used by the pipeline. */\n resolvedNames: ResolvedNames;\n /** Number of type plan entries emitted into the types interface. */\n typeCount: number;\n /** Number of operations emitted into the operations interface. */\n operationCount: number;\n}\n\nfunction assertSupportedTarget(target: GenerateTarget): void {\n if (target !== 's4-cloud') {\n throw new Error(\n `generate: target \"${target}\" is not supported in v1 (only 's4-cloud').`,\n );\n }\n}\n\nfunction deriveDefaultServer(spec: NormalizedSpec): string {\n const first = spec.servers[0]?.url;\n if (!first || first.length === 0) {\n return '/';\n }\n try {\n const u = new URL(first);\n return u.pathname && u.pathname.length > 0 ? u.pathname : '/';\n } catch {\n // Relative URL — use as-is.\n return first;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Implementation-class emitter is provided by `./emit/implementation-class`.\n// ---------------------------------------------------------------------------\n\nexport async function generate(\n options: GenerateOptions,\n): Promise<GenerateResult> {\n const target: GenerateTarget = options.target ?? 's4-cloud';\n let step = 'validate-target';\n try {\n assertSupportedTarget(target);\n\n step = 'resolve-names';\n const names = resolveNames(options.names);\n\n step = 'load-spec';\n const spec = await loadSpec(options.input);\n\n step = 'plan-types';\n // planTypes always prepends `ty_` — an empty extra prefix is fine.\n const plan = planTypes(spec, { typePrefix: '' });\n\n step = 'emit-types-interface';\n const typesIF = emitTypesInterface(spec, plan, {\n name: names.typesInterface,\n emitNullFlags: options.emitNullFlags ?? false,\n interfaceAbapDoc: [`Generated types for ${names.implementationClass}.`],\n });\n\n step = 'emit-operations-interface';\n const opsIF = emitOperationsInterface(spec, plan, {\n name: names.operationsInterface,\n typesInterfaceName: names.typesInterface,\n exceptionClassName: names.exceptionClass,\n });\n\n step = 'emit-exception-class';\n const zcx = emitExceptionClass({ name: names.exceptionClass });\n\n step = 'emit-implementation-class';\n const implResult = emitImplementationClass(spec, opsIF.operations, {\n names,\n defaultServer: options.defaultServer ?? deriveDefaultServer(spec),\n });\n\n step = 'emit-local-classes';\n const locals = emitLocalClasses(names);\n\n step = 'print';\n const typesSource = print(typesIF.interface);\n const opsSource = print(opsIF.interface);\n const zcxSource = print(zcx.class);\n const implSource = print(implResult.class);\n\n step = 'assemble-artifacts';\n const types: InterfaceArtifact = {\n name: names.typesInterface,\n source: typesSource,\n description:\n options.description ?? `Types for ${names.implementationClass}`,\n };\n const operationsArtifact: InterfaceArtifact = {\n name: names.operationsInterface,\n source: opsSource,\n description:\n options.description ?? `Operations for ${names.implementationClass}`,\n };\n const exception: ClassArtifact = {\n className: names.exceptionClass,\n mainSource: zcxSource,\n description:\n options.description ??\n `Error exception for ${names.implementationClass}`,\n };\n const implementation: ClassArtifact = {\n className: names.implementationClass,\n mainSource: implSource,\n description: options.description ?? names.implementationClass,\n localsDefSource: locals.localsDef,\n localsImpSource: locals.localsImp,\n };\n\n step = 'write';\n const written = await writeClientBundle(\n { types, operations: operationsArtifact, exception, implementation },\n options.format,\n options.outDir,\n );\n\n return {\n files: written.files,\n resolvedNames: names,\n typeCount: plan.entries.length,\n operationCount: opsIF.operations.length,\n };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const wrapped = new Error(\n `openai-codegen generate failed at step \"${step}\": ${message}`,\n );\n if (err instanceof Error && err.stack) {\n wrapped.stack = err.stack;\n }\n throw wrapped;\n }\n}\n"],"mappings":";;;;;;;;AAeA,SAAgB,MAAM,GAAgC;CACpD,OACE,OAAO,MAAM,YACb,MAAM,QACN,OAAQ,EAAyB,SAAS;AAE9C;;;ACFA,MAAM,eAAsC;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAASA,WAAS,GAAgC;CAChD,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAChE;AAEA,SAAS,SAAS,GAAgC;CAChD,OAAO,OAAO,MAAM,WAAW,IAAI;AACrC;AAEA,SAAS,OAAO,GAAY,UAA4B;CACtD,OAAO,OAAO,MAAM,YAAY,IAAI;AACtC;AAEA,SAAS,QAAQ,GAAuB;CACtC,OAAO,MAAM,QAAQ,CAAC,IAAI,IAAI,CAAC;AACjC;AAEA,SAAS,cAAc,GAAsB;CAC3C,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,MAAmB,OAAO,MAAM,QAAQ;AACpE;;;;;;;AAQA,eAAsB,SACpB,OACyB;CACzB,IAAI;CAEJ,IAAI,OAAO,UAAU,YAAY,YAAY,KAAK,KAAK,GAAG;EACxD,MAAM,OAAO,MAAM,SAAS,OAAO,MAAM;EACzC,MAAM,KAAK,MAAM,IAAI;CACvB,OAAO,IAAI,iBAAiB,KAC1B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