//#region src/compat/policy.d.ts /** Policy hints that determine what constitutes a breaking change. */ interface CompatPolicyHints { /** Callers reference parameter names at the call site (PHP named args, Python/Ruby keyword args, Kotlin/C# named args). */ callerUsesParamNames: boolean; /** Constructor positional order is part of the public API. */ constructorOrderMatters: boolean; /** Method parameter names are visible to callers. */ methodParameterNamesArePublicApi: boolean; /** Constructor parameter names are visible to callers. */ constructorParameterNamesArePublicApi: boolean; /** Method overload sets are part of the public API (Kotlin, C#). */ overloadsArePublicApi: boolean; /** Function arity is part of the public API (Elixir, Go). */ arityIsPublicApi: boolean; } /** Get the built-in default policy for a language. */ declare function getDefaultPolicy(language: LanguageId): CompatPolicyHints; /** Merge user overrides onto language defaults. Only provided keys are overridden. */ declare function mergePolicy(defaults: CompatPolicyHints, overrides: Partial): CompatPolicyHints; /** All supported language IDs. */ declare const ALL_LANGUAGE_IDS: readonly LanguageId[]; //#endregion //#region src/compat/ir.d.ts /** Language identifier for emitter targets. */ type LanguageId = 'node' | 'php' | 'python' | 'ruby' | 'go' | 'kotlin' | 'dotnet' | 'elixir' | 'rust' | 'ios'; /** A full compatibility snapshot of an SDK's public API surface. */ interface CompatSnapshot { schemaVersion: string; source: { specSha?: string; extractedAt: string; /** Language the snapshot was extracted for. Older snapshots omit this; * the differ falls back to no type-form normalization when absent. */ language?: LanguageId; }; policies: CompatPolicyHints; symbols: CompatSymbol[]; } /** Kind of public API symbol. */ type CompatSymbolKind = 'service_accessor' | 'callable' | 'constructor' | 'field' | 'property' | 'enum' | 'enum_member' | 'alias'; /** Visibility level of a symbol. */ type CompatVisibility = 'public' | 'protected' | 'internal'; /** Stability classification of a symbol. */ type CompatStability = 'stable' | 'unstable' | 'deprecated'; /** How the symbol was generated. */ type CompatSourceKind = 'generated_service_wrapper' | 'generated_model_constructor' | 'generated_resource_constructor' | 'generated_enum' | 'compat_alias'; /** A single public API symbol with its full metadata. */ interface CompatSymbol { id: string; kind: CompatSymbolKind; fqName: string; ownerFqName?: string; displayName: string; visibility: CompatVisibility; stability: CompatStability; sourceKind: CompatSourceKind; operationId?: string; schemaName?: string; route?: { method: string; path: string; }; parameters?: CompatParameter[]; returns?: CompatTypeRef; /** Type reference for field/property symbols. */ typeRef?: CompatTypeRef; /** Value for enum member symbols. */ value?: string | number; /** Whether a callable is a static/type-level method. Absent when the * extractor does not capture staticness; the classifier only compares * it when both snapshots define it, so older snapshots never diff. */ isStatic?: boolean; /** Relative path to the source file where this symbol is defined. */ sourceFile?: string; } /** How a parameter is passed at the call site. */ type CompatPassingStyle = 'positional' | 'keyword' | 'named' | 'keyword_or_positional' | 'options_object' | 'builder'; /** A parameter on a callable or constructor symbol. */ interface CompatParameter { publicName: string; wireName?: string; position: number; required: boolean; nullable: boolean; hasDefault: boolean; passing: CompatPassingStyle; type: CompatTypeRef; sensitivity: ParameterSensitivity; } /** Which aspects of this parameter are part of the public API contract. */ interface ParameterSensitivity { order: boolean; publicName: boolean; requiredness: boolean; type: boolean; } /** A type reference — either a named type or an inline description. */ interface CompatTypeRef { name: string; nullable?: boolean; array?: boolean; generic?: string[]; } /** * Convert a legacy ApiSurface to a CompatSnapshot. * * This bridge allows existing extractors (which produce ApiSurface) to feed * into the new classified diff engine without requiring immediate migration. */ declare function apiSurfaceToSnapshot(surface: ApiSurface): CompatSnapshot; //#endregion //#region src/compat/types.d.ts interface ApiSurface { language: string; extractedFrom: string; extractedAt: string; classes: Record; interfaces: Record; typeAliases: Record; enums: Record; exports: Record; } interface ApiClass { name: string; sourceFile?: string; methods: Record; properties: Record; constructorParams: ApiParam[]; /** Present when the class JSDoc carries `@deprecated`. Emitters use this * to propagate deprecation to the service property on the client class * so IDEs surface the strikethrough at the access site, not just when * users instantiate the class directly. */ deprecationMessage?: string; } interface ApiMethod { name: string; params: ApiParam[]; returnType: string; async: boolean; /** Whether this is a static/type-level method. Absent when the extractor * does not capture staticness; the differ only compares it when both * sides define it. */ isStatic?: boolean; } interface ApiParam { name: string; type: string; optional: boolean; /** Per-parameter passing style, populated by extractors. * When absent, the bridge infers from language defaults. */ passingStyle?: CompatPassingStyle; } interface ApiProperty { name: string; type: string; readonly: boolean; } interface ApiInterface { name: string; sourceFile?: string; fields: Record; extends: string[]; /** True if the resource class defines its own constructFromResponse (not inherited). */ hasCustomConstructor?: boolean; } interface ApiField { name: string; type: string; optional: boolean; } interface ApiTypeAlias { name: string; sourceFile?: string; value: string; } interface ApiEnum { name: string; sourceFile?: string; members: Record; } interface LanguageHints { /** Strip nullable wrapper, return inner type. null if not nullable. * Node: "string | null" → "string" * Go: "*Organization" → "Organization" * Python: "Optional[str]" → "str" */ stripNullable(type: string): string | null; /** True if a and b differ only by nullability. */ isNullableOnlyDifference(a: string, b: string): boolean; /** True if a and b are union types with same members in different order. */ isUnionReorder(a: string, b: string): boolean; /** True if type is a generic type parameter the extractor can't resolve. */ isGenericTypeParam(type: string): boolean; /** True if type is an extraction artifact (extractor couldn't resolve). * Node: "any"; Python: "Any"; Go: "interface{}" */ isExtractionArtifact(type: string): boolean; /** Whether a missing type alias should be tolerated when the candidate * has the same name as an interface or class (TS allows this). */ tolerateCategoryMismatch: boolean; /** Extract innermost meaningful type name from a return type string. * Node: "Promise>" → "Organization" */ extractReturnTypeName(returnType: string): string | null; /** Extract meaningful type name from a param type string. null for primitives. */ extractParamTypeName(paramType: string): string | null; /** True if sdkResourceProperty maps to className. * Node: camelCase ("organizations" → "Organizations") * Ruby: snake_case ("organizations" → "Organizations") */ propertyMatchesClass(propertyName: string, className: string): boolean; /** Additional names derived from a model name by this language's emitter. * Node: ["FooResponse", "SerializedFoo"] * Go: ["FooResponse"] */ derivedModelNames(modelName: string): string[]; /** True if two type strings are semantically equivalent even when * structurally different — e.g., a named enum vs an inline union * of its string literal values. The candidate surface is provided * so the hint can look up enum definitions. * Returns true to suppress the mismatch, false to report it. */ isTypeEquivalent?(baselineType: string, candidateType: string, candidateSurface: ApiSurface): boolean; /** True if two method signatures should be considered equivalent despite * structural differences. Called as a fallback when strict positional * matching fails — e.g., when the baseline unpacks body fields into * individual params while the candidate uses a dict/array payload. * Returns true to suppress the mismatch. */ isSignatureEquivalent?(baseline: ApiMethod, candidate: ApiMethod, candidateSurface: ApiSurface): boolean; /** Base class names that indicate a data model (→ ApiInterface). * Python: ["BaseModel"]; PHP: ["BaseResource"]. * Extractors should provide these for their SDK. */ modelBaseClasses?: string[]; /** Base class names that indicate an exception class. * Python: ["Exception", "BaseException"]; PHP: ["Exception"]. */ exceptionBaseClasses?: string[]; /** Type names for list/paginated resource wrappers (for return type unwrapping). * The first type argument is extracted as the inner item type. * e.g., ["ListResource"] causes `ListResource[Org, ...]` → `Org`. */ listResourcePatterns?: string[]; } interface Extractor { language: string; extract(sdkPath: string): Promise; extractSnapshot(sdkPath: string): Promise; hints: LanguageHints; } interface MethodOverlay { className: string; methodName: string; params: ApiParam[]; returnType: string; } interface OverlayLookup { /** HTTP method + path → existing method info */ methodByOperation: Map; /** Reverse map: "ClassName.methodName" → HTTP key for patchOverlay */ httpKeyByMethod: Map; /** IR interface name → existing interface name */ interfaceByName: Map; /** IR type alias name → existing type alias name */ typeAliasByName: Map; /** Barrel file path → symbols that must be exported */ requiredExports: Map>; /** IR model name → SDK interface name (auto-inferred from field structure) */ modelNameByIR: Map; /** IR symbol name → relative file path in the live SDK */ fileBySymbol: Map; } type ViolationCategory = 'public-api' | 'signature' | 'export-structure' | 'behavioral' | 'staleness'; type ViolationSeverity = 'breaking' | 'warning'; interface Violation { category: ViolationCategory; severity: ViolationSeverity; symbolPath: string; baseline: string; candidate: string; message: string; } interface Addition { symbolPath: string; symbolType: 'class' | 'method' | 'interface' | 'type-alias' | 'enum' | 'property'; } interface DiffResult { preservationScore: number; totalBaselineSymbols: number; preservedSymbols: number; violations: Violation[]; additions: Addition[]; } //#endregion //#region src/compat/config.d.ts /** Breaking change categories — changes that break callers. */ type BreakingChangeCategory = 'symbol_removed' | 'symbol_renamed' | 'parameter_removed' | 'parameter_renamed' | 'parameter_requiredness_increased' | 'parameter_type_narrowed' | 'parameter_position_changed_order_sensitive' | 'constructor_position_changed_order_sensitive' | 'named_arg_name_removed' | 'keyword_name_removed' | 'overload_removed' | 'union_wrapper_migration_without_compat_alias' | 'field_type_changed' | 'return_type_changed' | 'enum_member_value_changed' | 'staticness_changed'; /** Soft-risk change categories — may affect callers depending on usage. */ type SoftRiskChangeCategory = 'parameter_added_non_terminal_optional' | 'constructor_reordered_named_friendly' | 'default_value_changed' | 'wrapper_stricter_than_previous_sdk_but_matches_spec' | 'doc_surface_drift'; /** Additive change categories — safe to ship. */ type AdditiveChangeCategory = 'symbol_added' | 'parameter_added_optional_terminal' | 'new_constructor_overload_added' | 'new_wrapper_alias_added'; /** All change categories. */ type CompatChangeCategory = BreakingChangeCategory | SoftRiskChangeCategory | AdditiveChangeCategory; /** Change severity levels. */ type CompatChangeSeverity = 'breaking' | 'soft-risk' | 'additive'; /** Provenance bucket — where the drift originated. */ type CompatProvenance = 'spec_shape_change' | 'spec_ordering_change' | 'emitter_template_change' | 'compat_extractor_change' | 'operation_hint_change' | 'manual_override_change' | 'normalization_change' | 'unknown'; /** Level at which `verify` should fail. */ type CompatFailLevel = 'none' | 'breaking' | 'soft-risk'; /** A single intentional-break approval in `oagen.config.ts`. */ interface CompatApproval { /** Fully-qualified symbol (e.g., "Acme\\Service\\Users::createUser"). */ symbol: string; /** The kind of change being approved. */ category: CompatChangeCategory; /** Languages this approval applies to. Omit for all impacted languages. */ appliesTo?: LanguageId[] | 'all-impacted-languages'; /** Optional narrowing criteria. */ match?: { parameter?: string; member?: string; oldName?: string; newName?: string; }; /** Minimum release level required for this break. */ allowedReleaseLevel?: 'major' | 'minor' | 'patch'; /** Human-readable reason for this approval. */ reason: string; /** Issue tracker reference (e.g., "SDK-1234"). */ issue?: string; /** Auto-expire this approval after a version is released. */ expiresAfterVersion?: string; /** Whether this approval is currently active. */ approved?: boolean; } /** The `compat` section of `oagen.config.ts`. */ interface CompatConfig { /** Level at which `oagen verify` should fail. Default: 'breaking'. */ failOn?: CompatFailLevel; /** Path to write the machine-readable compat report. */ reportPath?: string; /** Include provenance explanations in reports. */ explain?: boolean; /** Path to the baseline compatibility snapshot. */ baselinePath?: string; /** Per-language policy overrides. Sparse — only override what diverges. */ languagePolicy?: Partial>>; /** Intentional break approvals. */ allow?: CompatApproval[]; } /** Get the default severity for a change category. */ declare function defaultSeverityForCategory(category: CompatChangeCategory): CompatChangeSeverity; /** Check whether a severity meets or exceeds a fail threshold. */ declare function severityMeetsThreshold(severity: CompatChangeSeverity, threshold: CompatFailLevel): boolean; //#endregion //#region src/ir/sdk-behavior.d.ts /** * SDK Behavior IR — language-agnostic runtime policies for generated SDKs. * * These types capture the "what" of SDK behavior (retry, telemetry, errors, etc.) * while emitters provide the "how" (language-specific mechanism). * * Emitters access these via `ctx.spec.sdk` — always populated, never undefined. */ /** Retry policy — when and how to retry failed requests. */ interface RetryPolicy { /** HTTP status codes that trigger a retry. */ retryableStatusCodes: number[]; /** Maximum number of retry attempts (0 = no retries). */ maxRetries: number; /** Whether to retry on connection errors (DNS failure, TCP reset). */ retryOnConnectionError: boolean; /** Whether to retry on timeout errors. */ retryOnTimeout: boolean; /** Backoff strategy between retries. */ backoff: BackoffStrategy; } /** Exponential backoff configuration. * * Formula: `delay = min(initialDelay * multiplier^attempt, maxDelay)` * With jitter: `delay += delay * jitterFactor * random(0, 1)` */ interface BackoffStrategy { /** Initial delay in seconds before the first retry. */ initialDelay: number; /** Multiplier applied to the delay on each subsequent retry. */ multiplier: number; /** Maximum delay in seconds (cap). */ maxDelay: number; /** Jitter factor (0..1). 0.5 means up to 50% random jitter added. */ jitterFactor: number; } /** Error mapping — status codes to named exception kinds. */ interface ErrorPolicy { /** Map from HTTP status code to a logical error kind name (e.g. 400 → 'BadRequest'). * Emitters append language-specific suffixes (e.g. 'BadRequestException'). */ statusCodeMap: Record; /** Catch-all error kind for 5xx status codes not in the map. */ serverErrorKind: string; /** Catch-all error kind for unrecognized status codes. */ clientErrorKind: string; /** URL template for error documentation. Use {code} as placeholder for the API error code. */ errorDocUrlTemplate?: string; } /** Telemetry — what request metrics to track and send. */ interface TelemetryPolicy { /** Whether telemetry is enabled by default. Users can opt out via constructor param. */ enabledByDefault: boolean; /** Header name for client telemetry data (previous request's ID + latency). */ headerName: string; /** Response header name for the request ID. */ requestIdHeader: string; } /** Pagination behavior defaults. */ interface PaginationPolicy { /** Delay in milliseconds between pages during auto-pagination. 0 = no delay. */ autoPageDelayMs: number; } /** Idempotency auto-generation rules. */ interface IdempotencyPolicy { /** Header name for the idempotency key. */ headerName: string; /** Whether to auto-generate a UUID v4 idempotency key for POST requests when retries > 0. */ autoGenerateForPost: boolean; } /** Logging contract — what to log at which level. */ interface LoggingPolicy { /** Whether structured logging hooks are generated. */ enabled: boolean; /** Log events that the generated client emits. */ events: LogEvent[]; } /** A discrete loggable event in the request lifecycle. */ type LogEvent = 'request.start' | 'request.success' | 'request.retry' | 'request.rate_limited' | 'request.error' | 'request.connection_error'; /** User-Agent construction rules. */ interface UserAgentPolicy { /** Template for the SDK identifier string. * Placeholders: {name} = spec name, {lang} = emitter language, {version} = SDK version. * Each emitter interpolates with its own language string and casing conventions. * Example: '{name} {lang}/{version}' → 'Acme PHP/4.32.0' */ sdkIdentifierTemplate: string; /** Whether to append the runtime/language version (e.g. PHP 8.2, Python 3.12). */ includeRuntimeVersion: boolean; /** Whether to allow app info enrichment via setAppInfo(name, version, url). */ allowAppInfo: boolean; /** AI agent environment variable detection entries. */ aiAgentEnvVars: AiAgentEnvVar[]; } /** Maps an environment variable to an AI agent slug for User-Agent enrichment. */ interface AiAgentEnvVar { /** Environment variable to check (e.g. 'CLAUDE_CODE'). */ envVar: string; /** Agent name to append to User-Agent (e.g. 'ClaudeCode'). */ agentName: string; } /** Guards that validate request params before sending. */ interface RequestGuardPolicy { /** Keys that should be in RequestOptions, not in params. * If detected in the body or query params, the SDK throws an error. */ optionKeys: string[]; } /** Timeout configuration. */ interface TimeoutPolicy { /** Default HTTP request timeout in seconds. */ defaultTimeoutSeconds: number; /** Environment variable name to override the timeout (e.g. 'SDK_REQUEST_TIMEOUT'). */ timeoutEnvVar?: string; } /** Language-agnostic runtime policies for generated SDKs. * Attached to `ApiSpec.sdk` and consumed by emitters via `ctx.spec.sdk`. */ interface SdkBehavior { retry: RetryPolicy; errors: ErrorPolicy; telemetry: TelemetryPolicy; pagination: PaginationPolicy; idempotency: IdempotencyPolicy; logging: LoggingPolicy; userAgent: UserAgentPolicy; requestGuard: RequestGuardPolicy; timeout: TimeoutPolicy; } /** * Canonical SDK behavior defaults. Per-language or per-project overrides can * be applied via `mergeSdkBehavior()` in each SDK's `oagen.config.ts`. * * - Retry: exponential backoff with jitter, retries on 429/5xx * - Errors: standard HTTP status → exception kind mapping * - Telemetry: enabled by default, tracks request ID + latency * - Pagination: no inter-page delay (Node overrides to 350ms) * - Idempotency: auto-generate UUID v4 for retryable POSTs * - Logging: all lifecycle events enabled * - User-Agent: SDK identifier + runtime version + app info + AI agent detection * - Request guards: detect misplaced RequestOptions keys in params * - Timeout: 60s default (Python overrides to 30s) */ declare function defaultSdkBehavior(): SdkBehavior; /** Recursive partial type for deep overrides. */ type DeepPartial = { [K in keyof T]?: T[K] extends (infer U)[] ? U[] : T[K] extends object ? DeepPartial : T[K]; }; /** * Deep-merge partial overrides into the canonical defaults. * Arrays replace entirely (so `retryableStatusCodes: [429]` replaces the full list, * rather than appending). Object properties are merged recursively. */ declare function mergeSdkBehavior(overrides: DeepPartial): SdkBehavior; //#endregion //#region src/ir/types.d.ts /** * Authentication scheme extracted from OpenAPI `components.securitySchemes`. * * `schemeName` is the key under `components.securitySchemes`, spelled exactly as * in the document. The requirements under `ApiSpec.security` and * `Operation.security` refer to the same key, so emitters join a requirement to * its scheme on that field. `description` is present only when the document * declares one. */ type AuthScheme = { description?: string; schemeName: string; } & ({ kind: 'basic'; } | { kind: 'bearer'; } | { kind: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string; } | { kind: 'oauth2'; flows: Record; }); /** * A variable in a templated server URL (`https://{region}.api.example.com`), * from the server's `variables` map. */ interface ServerVariable { /** Substituted for the placeholder when the caller picks no value; OpenAPI requires one. */ default: string; /** The values the variable may take. Present only when the document declares a non-empty list. */ enum?: string[]; description?: string; } /** A server entry from the OpenAPI servers array */ interface ServerEntry { /** * As written in the document, placeholders included. `ApiSpec.baseUrl` is * the first server's URL with its variables' defaults filled in; resolve any * other entry the same way with `resolveServerUrl` from `ir/server-url.ts`. */ url: string; description?: string; /** The template's variables, keyed by placeholder name. Present only when the document declares them. */ variables?: Record; } /** * A link to documentation outside the OpenAPI document (an External * Documentation Object). Present on a node only when the document declares * one with a non-blank `url`; an emitter can surface it in a doc comment (a * JSDoc `@see`, say). `url` is exactly as written — OpenAPI allows a value * relative to the document's own location, which the parser does not know, so * it neither resolves nor rewrites it. `description` is present only when it * has non-whitespace content. */ interface ExternalDocs { url: string; description?: string; } /** * The specification extensions (`x-*` keys) an OpenAPI object declares, * each under the key as written with its value verbatim — a string, a * boolean, a number, `null`, an array or an object, nested values * included — in document order. Carried on `Operation`, `Model`, `Field` * and `Enum` as `extensions`, present only when the object declares at * least one key the parser does not already read into a typed field (an * Operation Object's `x-pagination`, `x-oagen-async`, * `x-mutually-exclusive-parameter-groups` and * `x-mutually-exclusive-body-groups`; a Schema Object's * `x-enum-descriptions` and `x-enumDescriptions`), so an emitter can read * the keys it knows (`x-idempotent`, `x-since`) without the parser knowing * each one. Not shape: two schemas that differ only in their extensions * are one model or one enum wherever the parser decides that, and the * differ reports a change to them as additive (`extensionsChanged`, * `field-extensions-changed`), never as a type change. Values come from * the document unvalidated, so an emitter that writes one into generated * source must escape it as it escapes a `description`. */ type Extensions = Record; /** Root IR node representing the full API surface */ interface ApiSpec { name: string; version: string; description?: string; /** The document's top-level `externalDocs`, when it declares a usable one. */ externalDocs?: ExternalDocs; baseUrl: string; servers?: ServerEntry[]; services: Service[]; /** * The requests the API sends to its users, from the document's top-level * `webhooks` map (OpenAPI 3.1), in document order. Absent — not an empty * list — when the document declares none, so the IR of a document without * webhooks is unchanged. A webhook is not an SDK method: it belongs to no * service, gets no resolved operation name, and is untouched by operation * hints and mount rules. See `Webhook`. */ webhooks?: Webhook[]; models: Model[]; enums: Enum[]; auth?: AuthScheme[]; /** * Document-level security requirements: the default every operation uses * unless it declares its own `Operation.security`. Same shape and semantics * as that field. `undefined` when the document declares none. */ security?: SecurityRequirementSet[]; /** Language-agnostic runtime policies (retry, errors, telemetry, etc.). */ sdk: SdkBehavior; } /** * A request the API sends to its users: one HTTP method of one entry in the * document's top-level `webhooks` map (OpenAPI 3.1). An entry whose path item * declares several methods yields one `Webhook` per method, so `name` alone * does not identify a webhook; `name` + `httpMethod` does. * * Everything here is read from the receiver's side of the wire: the request * body is the payload the receiver is handed, the parameters are the headers * (signatures, event types) and query values the request carries, and * `responses` are the status codes the sender expects back. An emitter uses * this to generate a payload type or a typed handler per event. A webhook is * never an SDK method: it has no path, belongs to no `Service`, and gets no * resolved operation name. * * An operation's `callbacks` (OpenAPI 3.x), whose path items have this * shape, are read the same way: each is a `Callback`, a `Webhook` tied to * the operation that registers it, carried on `Operation.callbacks` — and * on `callbacks` here, since a `webhooks` operation may declare its own * (#382). */ interface Webhook { /** The key under `webhooks`, verbatim (`petAdopted`, `user.created`). */ name: string; /** * The operation's `operationId`, verbatim, when the document declares one * that names something: one with no ASCII letter or digit once its trailing * overload markers are stripped (`' '`, `'-'`, `'[1]'`, `'[1][2]'`) is left * out, as `''` is and as on an `Operation`, and the webhook's models are * named from its key (#564). No `operationIdTransform` is applied to it. */ operationId?: string; httpMethod: HttpMethod; /** * The `summary` alone, read as `Operation.summary` is: the operation's own, * else the path item's. Absent when neither has content. */ summary?: string; /** * The `description` alone, read as `Operation.description` is: the * operation's own, else the path item's, never built from the summary (a * `description` identical to the `summary` is kept in both). Absent when * neither has content. */ description?: string; /** * The operation's own `externalDocs`, when it declares a usable one, as on * `Operation.externalDocs`. A Path Item Object has no `externalDocs`, so * there is nothing to fall back to. */ externalDocs?: ExternalDocs; /** Present, and `true`, only when the document marks the webhook deprecated. */ deprecated?: boolean; /** The operation's `tags`, read exactly as `Operation.tags` is. */ tags?: string[]; /** Header parameters the request carries, typed like `Operation.headerParams`. */ headerParams: Parameter[]; /** Query parameters the request carries, typed like `Operation.queryParams`. */ queryParams: Parameter[]; /** Cookie parameters; present only when the document declares at least one. */ cookieParams?: Parameter[]; /** * The payload the receiver is handed. An inline object schema is * materialized as a model named `Payload`, where the stem is the * `operationId` when there is one and the webhook's name otherwise (see the * parser's `resolveWebhookModelStems` for how the stem is kept unique). * Read from the content entry the same pick as `Operation.requestBody` * chooses, by media type essence. Absent when the operation declares no * `requestBody`, or one none of whose media types is read — which the * parser warns about. */ requestBody?: TypeRef; /** How the payload is encoded, read like `Operation.requestBodyEncoding`. */ requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text'; /** * The media type the payload was read from, by essence, read like * `Operation.requestBodyContentType` (`application/merge-patch+json`; * `application/json` for `application/json; charset=utf-8`): what the * sender labels the request with, so a handler can check it. Present * exactly when `requestBody` is. */ requestBodyContentType?: string; /** * Present, and `true`, only when the document marks the request body * `required` and the body declares a media type (`requestBodyContentTypes` * is set), the presence rule `Operation.requestBodyRequired` follows: a * payload carried in `requestBodyContents` alone keeps it, and a body with * no `content`, or an empty map, has no entry. */ requestBodyRequired?: boolean; /** * Doc text for the payload, read as `Operation.requestBodyDescription` * is: the Request Body Object's own `description`, else the `description` * written on the schema of the content entry `requestBody` is read from (a * `$ref` is not followed; a nullable `oneOf`/`anyOf` or a single-member * `allOf`, `oneOf` or `anyOf` is read to its branch, its own text first, * an `allOf` member that declares no type being part of the wrapper, #555; a * `oneOf`/`anyOf` of consts read as an enum is read as itself, never to a * variant, #535). Present only when one of the two has non-whitespace * content, kept verbatim. */ requestBodyDescription?: string; /** * Media types the payload declares under `content`, in document order and * exactly as written, read as `Operation.requestBodyContentTypes` is. * Present only when at least one is declared. */ requestBodyContentTypes?: string[]; /** * One entry per `requestBodyContentTypes` entry, in the same order, typed * as `Operation.requestBodyContents` is: the entry for the media type * `requestBody` was read from carries that same TypeRef; an inline object * under another media type is materialized as `Payload` * (`PetAdoptedTextCsvPayload`). Present only when `requestBodyContentTypes` * is. */ requestBodyContents?: RequestBodyContent[]; /** * The responses the sender expects from the receiver, in document order: * one entry per status code key (three digits, 100–599) the operation * declares. `default`, range (`2XX`) and `x-` keys are not carried; a key * that is none of those (`error`, `6XX`, `600`) is ignored with a warning. * An entry at a status code that is not an object — `200: "oops"`, * `null`, `7` — is no Response Object and no Reference Object: it is * skipped with one warning naming the site (`200 response of * webhooks.petAdopted.post is not a Response Object ("oops"); skipping * it.`), as is a `$ref` whose chain ends on a `components/responses` entry * that is not an object (`Gone: []`), the warning naming the component * (`components/responses/Gone (the 200 response of * webhooks.petAdopted.post) is not a Response Object ([]); skipping it.`), * and a `responses` that is not an object at all is read as declaring * none, with a warning (#617); a callback's are read the same way. * Body schemas on these responses are not carried either: a webhook * response is an acknowledgement, and typing it would mint models no * handler needs. */ responses: WebhookResponse[]; /** * The security the request carries, mirroring the OpenAPI document exactly * as `Operation.security` does: `undefined` inherits `ApiSpec.security`, * `[]` means none, otherwise one alternative per requirement object. */ security?: SecurityRequirementSet[]; /** * The callbacks the webhook's operation declares, read exactly as * `Operation.callbacks` is: present only when at least one is readable, in * document order. A callback nests through this field in turn, since a * `Callback` is a `Webhook`. */ callbacks?: Callback[]; } /** One status code a webhook's sender expects back, with the document's description of it. */ interface WebhookResponse { statusCode: number; description?: string; } /** * A request the API sends to a URL the caller handed it: one HTTP method of * one path item under one runtime expression of one `callbacks` entry * (OpenAPI 3.x). Read from the receiver's side exactly as a `Webhook` is — * the payload, parameters, responses, docs, deprecation, tags and security * are the same fields, read by the same code — and tied to the operation * or webhook that registers it through `Operation.callbacks` / * `Webhook.callbacks` (#382). A callback has no fixed path: the path item * is keyed by a runtime expression the sender evaluates per request, kept * verbatim as `expression`. One `callbacks` key may map several expressions * to path items, each declaring several methods, so `name` + `expression` * + `httpMethod` identifies a callback, and that triple is what `oagen * diff` keys its `callback-added` / `callback-removed` / `callback-modified` * changes on. A callback is never an SDK method, as a webhook is not. * * Its payload is materialized as `Payload` where the stem is the * callback operation's `operationId` when it declares one that names * something and no other callback operation declares the same, else the * owner's stem followed by the key PascalCased — `createPet`'s `petAdopted` * mints `CreatePetPetAdoptedPayload` (see the parser's `extractCallbacks`). */ interface Callback extends Webhook { /** The key under the operation's `callbacks` map, verbatim (`petAdopted`). */ name: string; /** The runtime expression the path item is keyed by, verbatim (`{$request.body#/callbackUrl}`); a callback has no fixed path. */ expression: string; } /** * The site a callback is read and reported under, below its owner's * `context` — an operation's `operationId` (else `METHOD /path`) or * `.`, a webhook's `webhooks..`, a parent * callback's own: `.callbacks...` * (`createPet.callbacks.petAdopted.{$request.body#/callbackUrl}.post`). * One format for the parser's warnings and for every walker's diagnostics * (#382). */ declare function callbackContext(context: string, callback: Pick): string; /** A service groups related operations (maps to an SDK resource class) */ interface Service { name: string; description?: string; /** * A document tag's `externalDocs`, resolved by the same rule as * `description`: a service named after a declared tag takes that tag's; a * split-off service inherits it from the first linked tag its operations * carry, chosen independently of the tag its description comes from. * Absent when no tag gives one. */ externalDocs?: ExternalDocs; operations: Operation[]; } /** One scheme a request must satisfy, with the scopes it needs. */ interface SecurityRequirement { /** Key under `components.securitySchemes`; joins to `AuthScheme.schemeName`. */ schemeName: string; scopes: string[]; } /** * One alternative from an OpenAPI security requirement list: a request must * satisfy *every* scheme in the set together ("all of"). A list of sets is * satisfied by *any one* of them ("either of"). An empty set is an alternative * that needs no credentials at all, which is how a document makes * authentication optional (`security: [{ userToken: [] }, {}]`). */ type SecurityRequirementSet = SecurityRequirement[]; /** A single API operation (maps to an SDK method) */ interface Operation { name: string; /** * The operation's `operationId`, verbatim, when the document declares one * that names something: one with no ASCII letter or digit once its trailing * overload markers are stripped — every `[N]` at the end, so `' '`, `'-'`, * `'[1]'` and `'[1][2]'` alike — is left out, as `''` is, and the operation * is path-named. `name` is what the parser made of it * (`operationIdTransform` applied, after the markers are stripped: * `listPets[1][2]` is `listPets`); this says that `name` came from one at * all, which is what `resolveOperations` reads to prefer it over the * path-derived method name. Left out as well when the transform returns a * name that names nothing by the same reading (`''`, `' '`, `'-'`, `'[1]'`), * or no string at all: the operation is path-named, with one warning, as * if the document had declared no `operationId` (#570). */ operationId?: string; /** * The `summary` alone: the OpenAPI operation's own, or — when the operation * declares none with non-whitespace content — the `summary` of the Path * Item it sits on (the `paths` entry, or the Path Item a `$ref` entry * leads to), which OpenAPI applies to every operation on that * path. Present only when one of the two has content; a summary that is not * a string, or is empty or whitespace-only, is treated as absent at either * level. `description` below never includes it, so an emitter that * shows the summary — as a one-line label, or above the description — * reads it from here. */ summary?: string; /** * The `description` alone, read as `summary` above is: the operation's own, * else the Path Item's. It is never built from the summary, so an operation * that declares only a `summary` has none; a `description` identical to the * `summary` is kept in both, since each is the document's own text. A value * that is not a string, or is * empty or whitespace-only, is treated as absent, and text with content is * kept verbatim. */ description?: string; /** The operation's own `externalDocs`, when it declares a usable one. */ externalDocs?: ExternalDocs; httpMethod: HttpMethod; path: string; /** * The servers this operation is served from, when they differ from the * document's: the operation's own `servers`, else its Path Item's (OpenAPI * precedence). Absent when the operation inherits `ApiSpec.servers` — it * declares none at either level, or what it declares is the document's list * again (same URLs, descriptions and variables, in the same order), or both * it and the document mean OpenAPI's default server (no servers, * `servers: []`, or nothing but `/`, whatever its description or * variables — `/` references none; `isDefaultServerList` in * `ir/server-url.ts`). Same * shape as `ApiSpec.servers`, variables included, so `resolveServerUrl` * from `ir/server-url.ts` fills a template's defaults the way `baseUrl` was * produced. To find where a request goes, take `op.servers ?? spec.servers`. */ servers?: ServerEntry[]; pathParams: Parameter[]; queryParams: Parameter[]; /** * Query parameters the spec also declares as request-body properties on a * body-carrying method (POST/PUT/PATCH). They travel in the body only, so * they are excluded from `queryParams`; they are kept here so inline enums * they declare stay reachable and the compat surface still sees them. * Emitters never serialize these to the URL. */ bodyOwnedQueryParams?: Parameter[]; headerParams: Parameter[]; cookieParams?: Parameter[]; /** * The request body's type, read from one content entry of the Request Body * Object (after a `components/requestBodies` `$ref` is resolved). Media * types are matched by essence — parameters and case aside, so * `application/json; charset=utf-8` and `APPLICATION/JSON` are * `application/json` — and tried in a fixed order: `application/json`, then * a `+json` media type (`application/vnd.api+json`; never a range such as * `application/*+json`), then `multipart/form-data`, then * `application/x-www-form-urlencoded`, each * only when it declares a schema; then `application/octet-stream`, then * `text/plain`, with or without one (a schema-less binary body is a binary * string, a schema-less text body a string). An inline object body is * materialized as `Request`; an inline enum body, or an array of one, * is promoted to `spec.enums` under that name, numbered on a clash with an * enum of other members. Absent when the operation declares no * body, or one none of whose media types is read — which the parser warns * about once, so a body is never dropped silently. */ requestBody?: TypeRef; /** * The wire encoding of the media type `requestBody` was read from: `json` * for `application/json` and any concrete `+json` media type, `form-data` * for `multipart/form-data`, `form-urlencoded` for * `application/x-www-form-urlencoded`, `binary` for * `application/octet-stream`, `text` for `text/plain`. Set exactly when * `requestBody` is. */ requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text'; /** * The media type `requestBody` was read from, by essence — `type/subtype` * with parameters and case stripped: `application/merge-patch+json` for a * body declared under that key, `application/json` for one under * `application/json; charset=utf-8`, `multipart/form-data` for one under * `multipart/form-data; boundary=x`. This is what an emitter sends as the * request's `Content-Type`, so a server that requires its declared media * type accepts the request; parameters such as a multipart boundary are * the emitter's to produce. `requestBodyEncoding` says how to serialize * the body, this says how to label it. The key as written is the * `contentType` of the `requestBodyContents` entry that shares * `requestBody`'s type. Set exactly when `requestBody` is. */ requestBodyContentType?: string; /** * Whether a caller must send the request body: the Request Body Object's * `required`, read after a `components/requestBodies` `$ref` is resolved. * OpenAPI defaults the flag to `false`, so a body the document does not * mark required comes through as `false`. Present exactly when * `requestBodyContentTypes` is — whenever the body declares a media type, * whether it is read as `requestBody` or carried in `requestBodyContents` * alone — so it is set beside every `requestBody` but does not imply one; * an operation without a body, or whose body declares no media type, has * no entry. */ requestBodyRequired?: boolean; /** * Doc text for the request body, e.g. "The pet to add to the shelter." — * what an emitter prints for the body argument, as `responseDescription` * is what it prints for the return. The Request Body Object's own * `description`, read after a `components/requestBodies` `$ref` is * resolved; when that has no non-whitespace content, the `description` * written on the schema of the content entry `requestBody` is read from, * as it stands there: a `$ref` is not followed, so a component's text * stays on its model, while a `description` written beside the `$ref` is * read; a wrapper the parser collapses or sees through — a nullable * `oneOf`/`anyOf`, a single-member `allOf`, `oneOf` or `anyOf` — is read * to its branch, its own text first, an `allOf` member that declares no * type being part of the wrapper (`allOf: [{ $ref: Pet }, { description }]` * carries that text; #555), while a `oneOf`/`anyOf` of consts * read as an enum, nullable or not, is the schema that declares the * members and is read as itself, never to a variant (#535). When both * have content the body's own wins. The schema's text is also the `description` of the model an * inline object body is materialized as (`Request`), and the `description` of the `Enum` * an inline enum body is lifted to (`Request` in `enums`); for a body * no model or enum carries — an inline `oneOf`, an array, a primitive — * this field is the only place that text reaches. Present only when one * of the two has non-whitespace content, kept verbatim. The body's own text is * carried whether or not a media type is read as `requestBody`; the * schema's is read only from the entry that is. */ requestBodyDescription?: string; /** * Media types the request body declares under `content`, in document * order and exactly as written (`application/json; charset=utf-8`, * `multipart/form-data; boundary=x`, `text/csv`), so an emitter can offer * each verbatim as a `Content-Type`. Present only when the body declares at * least one media type — whether or not one of them is read as * `requestBody` — as `responseContentTypes` is on the response side. */ requestBodyContentTypes?: string[]; /** * One entry per `requestBodyContentTypes` entry, in the same order, with * the type that media type resolves to. The entry for the media type * `requestBody` was read from carries that very TypeRef, so the two never * disagree. Every other entry is typed as it would be were it the only one * declared: from its schema when it has one (an inline object materialized * as `Request`, `ReplaceWidgetTextCsvRequest`), else a * binary string for `application/octet-stream`, a string for `text/plain`, * and `unknown` for any other media type. Present only when * `requestBodyContentTypes` is. */ requestBodyContents?: RequestBodyContent[]; /** * The primary success response's body type: the lowest declared status code * from 200 to 399 whose type is not `unknown` — the lowest 2xx with a typed * body, so a `200` left `unknown` by the media-type rules (a schema-less * `text/csv`) yields to a `201` typed from a schema, and a 3xx entry (always * `unknown`) never wins over a typed 2xx — falling back to the lowest * declared code (an untyped 2xx, or a 3xx when no 2xx is declared). * `responseHeaders` and `responseDescription` come from the same entry. * Never promoted from a `2XX` range or the `default` response: an * operation declaring no 2xx or 3xx response at all (only `default` or * `2XX`, only a `404`, an empty `responses` map, or no `responses` key) * has `{ kind: 'primitive', type: 'unknown' }` here — the type of a body * the document does not describe — with no `responseHeaders` or * `responseDescription`, and an emitter should take the success body * from `rangeResponses` (`2XX`), then `defaultResponse` — the same order * it resolves any status: the explicit entry, then the matching range, * then the default. A body that is itself an inline enum is promoted to * `spec.enums` as `Response`, and an array of one as `Item` (see * `SuccessResponse.type` for one of several success bodies). */ response: TypeRef; /** * The status code of the response `response` was read from — the primary * success response chosen as described there: `200`; `201` when an untyped * `200` yielded to a typed `201`; `302` for a lone redirect; a POST's lone * `200`. Present exactly when the operation declares at least one 2xx or * 3xx response, and absent when it declares none (only `default`, a range, * 4xx/5xx codes, an empty `responses` map or no `responses` key) — the * case where `response` is `unknown`. When `successResponses` is set, this * equals the `statusCode` of the entry `response` was taken from. Read it * to check or document the status an operation succeeds with instead of * guessing one from the HTTP method. The differ pairs a lone 2xx/3xx with * the other spec's entry of this code, so an entry added beside it is not * mistaken for it, and reports it moving while both specs carry one as * `responseStatusCodeChanged`, breaking unless the new spec still declares * the old code among its 2xx/3xx (#407). */ responseStatusCode?: number; /** * Headers the primary success response declares (the one `response` is the * body of). Present only when the spec declares at least one. Each entry of * `successResponses` carries its own `headers`, but that list is only set * when an operation declares more than one 2xx or 3xx response (counted * together), so the primary response's headers need a home of their own. */ responseHeaders?: ResponseHeader[]; /** * Media types the primary success response declares under `content`, in * document order and exactly as written (`application/json; charset=utf-8`, * `application/vnd.api+json`, a wildcard such as `application/*`). Present * only when it declares at least one. Like `responseHeaders`, this lifts * the primary entry's `contentTypes`, because `successResponses` only * exists when an operation declares more than one 2xx or 3xx response. */ responseContentTypes?: string[]; /** * One entry per `responseContentTypes` entry, in the same order, with the * type that media type's schema resolves to. The entry for the media type * `response` was read from carries that same TypeRef. Present only when * `responseContentTypes` is. */ responseContents?: ResponseContent[]; /** * The `description` of the primary success response (the one `response` is * the body of), e.g. "The pet, with its owner." — often the clearest * statement of what an operation gives back, so an emitter can print it as * a `@returns` tag. Present only when that response declares one with * non-whitespace content; the text is kept verbatim. Each entry of * `successResponses` carries its own `description`, but that list is only * set when an operation declares more than one 2xx or 3xx response (counted * together), so the primary response's description needs a home of its own. */ responseDescription?: string; /** * Every declared 2xx and 3xx response, one `SuccessResponse` per status * code, each with its own `type`, `headers` and `description`. A 2xx entry's * `type` is its body, read by media type compared by essence, parameters * and case aside (the JSON schema — `application/json`, else a `+json` * media type; else binary string for `application/octet-stream` / * `application/pdf`; else `string` for `text/plain`, `text/html`, * `text/xml`, `application/xml`; else the schema of the first media type * that declares one) and `unknown` when none applies, a schema-less * `text/csv` included; a 3xx entry's `type` is always * `unknown`, and the entry is kept so an emitter can * recognize a redirect endpoint. Set only when more than one such response * is declared, counting 2xx and 3xx together: `200` + `201`, `200` + `302` * and `301` + `302` all set it, while a lone `200` (or a lone `302`) leaves * it `undefined` and `response` / `responseHeaders` / `responseDescription` * describe that single response alone. 4xx and 5xx responses go to * `errors`; `default` and the ranges `1XX`–`5XX` to `defaultResponse` and * `rangeResponses`; an explicit 1xx code is not carried. A key is a status * code only when it is exactly three digits in 100–599: `6XX`, `4XXX`, * `20X`, `600` and `200 ` are no status code and no range, so they are * ignored with a warning, like `error`, never read from a numeric prefix. * An entry that is not an object — `200: "oops"`, `null`, `7`, `true`, * `[]` — under any key a reader reads (a status code, `default`, a range) * is no Response Object and no Reference Object: it is skipped with one * warning naming the site (`200 response of listPets is not a Response * Object ("oops"); skipping it.`) and the operation is read from its other * entries, so `listPets` with `200: "oops"` beside a `204` is read from * the `204`, with no entry here, in `errors`, `defaultResponse` or * `rangeResponses` for the skipped key; a `$ref` whose chain ends on a * `components/responses` entry that is not an object (`Gone: []`) is * skipped the same way, the warning naming the component * (`components/responses/Gone (the 200 response of listPets) is not a * Response Object ([]); skipping it.`), so the inline and `$ref` * spellings give one IR; a `responses` that is not an object at all is * read as absent, with a warning (#617). */ successResponses?: SuccessResponse[]; errors: ErrorResponse[]; /** * The document's `default` response: what the operation returns for every * status it does not list explicitly or by range. Present only when the * spec declares one. It is kept apart from `errors` because it carries no * status code (`ErrorResponse.statusCode` is a number emitters compare and * format as one) and is not always an error — a spec may use it for its * success body too. An emitter should treat its `type` as the fallback for * any status that neither `errors`/`successResponses` nor `rangeResponses` * covers. `response` is never promoted from it: when the operation declares * no explicit 2xx, the emitter takes the success body from the `2XX` entry * of `rangeResponses`, then from here. */ defaultResponse?: DefaultResponse; /** * The document's `1XX`–`5XX` range responses, in declaration order. Present * only when the spec declares at least one. A range covers every status in * its hundred that the operation does not list explicitly, so an emitter * resolves a status in the order OpenAPI does: the explicit entry, then * the range, then `defaultResponse`. Ranges never feed `response`, * `successResponses` or `errors`, whose numeric `statusCode` could not say * which codes an entry stands for. */ rangeResponses?: RangeResponse[]; pagination?: PaginationMeta; injectIdempotencyKey: boolean; deprecated?: boolean; async?: boolean; /** * The operation's `tags`, in document order, with every entry that is not * a string with non-whitespace content dropped and a repeated entry folded * onto its first occurrence. Present only when at least one remains. The * parser names the service from the first entry that still has a name once * PascalCased (`tags[0]`, unless it has no ASCII letter or digit, like * `-`), or from the path when none has one, as for an untagged operation; * the list is kept so an emitter can group or document the method by every * tag. */ tags?: string[]; /** * Per-operation security requirements, mirroring the OpenAPI document: * - `undefined` — the operation declares nothing and inherits * `ApiSpec.security` (which may itself be `undefined`). * - `[]` — `security: []`: the operation needs no authentication. * - otherwise one `SecurityRequirementSet` per requirement object; the * request must satisfy any one set, and every scheme within it. */ security?: SecurityRequirementSet[]; /** * Mutually-exclusive parameter groups parsed from `x-mutually-exclusive-parameter-groups`. * Each group represents a logical choice the caller must (or may) make between * several subsets of query/path/header parameters. The grouped parameters remain * in their original arrays (queryParams, pathParams, etc.) for wire-format purposes; * this field adds the grouping metadata so emitters can render sum types. */ parameterGroups?: ParameterGroup[]; /** * The Operation Object's own `x-*` keys (see `Extensions`), less the ones * the parser reads into typed fields: `x-pagination` (`pagination`), * `x-oagen-async` (`async`), `x-mutually-exclusive-parameter-groups` and * `x-mutually-exclusive-body-groups` (`parameterGroups`). A Path Item * Object's extensions are not read. Present only when at least one key * remains. */ extensions?: Extensions; /** * The requests the API sends back to URLs the caller supplied, from the * Operation Object's `callbacks` map (OpenAPI 3.x), each read as a * `Webhook` is (see `Callback`; #382). Present only when the operation * declares at least one readable callback, in document order: `callbacks` * key order, then expression order within each Callback Object, then the * path item's method order. A callback is not an SDK method: it belongs * to no service, gets no resolved operation name, and is untouched by * operation hints and mount rules; an emitter types its payload, or a * handler for it, beside the operation. Its models are named from this * operation's stem (`CreatePetPetAdoptedPayload`) and assigned to this * operation's service, as the operation's own are. */ callbacks?: Callback[]; } /** * A mutually-exclusive parameter group. The caller must supply exactly one * variant (when `optional` is false) or may omit the group entirely (when true). */ interface ParameterGroup { /** Group name from the extension (e.g. "parent_resource"). */ name: string; /** True when the whole group may be omitted. */ optional: boolean; /** Ordered variants (insertion order matches the spec). */ variants: ParameterGroupVariant[]; /** * Base name emitters must use for this group's generated wrapper type, in * place of `name`. * * Two operations commonly share one group name — create and update both * declare `protocol_options` — and emitters name the wrapper from the group * name alone, so both operations collapse onto one type. That is correct * only while their members agree. When they disagree (create's * `saml_options` is a `CreateConnectionSAMLOptions`, update's is a * `PatchConnectionSAMLOptions`) one wrapper silently forces one operation to * use the other operation's type. * * The parser therefore fingerprints each group's members across every * operation declaring it and qualifies this with the operation name * (`update_connection_protocol_options`) only where they genuinely diverge. * Groups that agree — including ones differing only by nullability, or by * duplicate inline enums carrying identical values — keep the bare group * name, so already-published wrapper types are never renamed. */ wrapperName?: string; } /** * One variant within a mutually-exclusive parameter group. */ interface ParameterGroupVariant { /** Variant name from the extension (e.g. "by_id", "by_external_id"). */ name: string; /** * References to the actual parameter IR nodes. These are the same * objects that live in operation.queryParams / .pathParams / .headerParams -- * shared by identity, not duplicated. */ parameters: Parameter[]; /** * Names of parameters that may be omitted when this variant is used — * optional modifiers of the variant's required fields, from the * extension's `optionalFields`. Absent means every parameter in the * variant is required with it. */ optionalParameters?: string[]; } /** * How an operation's list is paged — what an auto-paging iterator sends to * reach the next page: * * - `cursor` — `param` carries an opaque cursor taken from the previous * response; iteration ends when the response yields no next cursor. * - `offset` — `param` is the number of items to skip; advance it by the * number of items received, with `limitParam` as the page size. * - `page` — `param` is a page *number*; start at `pageStart` (the * parameter's `default`, else its `minimum`, else 1) and advance it by * exactly one per request, with `limitParam` as the page size. * - `link-header` — follow the RFC 5988 `Link: <…>; rel="next"` response * header instead of building the next request from `param`. * * Under every strategy an empty page ends the iteration; `endOfIteration` * names a response field that ends it earlier. */ type PaginationStrategy = 'cursor' | 'offset' | 'page' | 'link-header'; /** * The response field that tells an iterator the last page has been reached. * `path` is a dotted property path from the response root, in the convention * `dataPath` uses: `has_more` at the top level, `pagination.totalPages` one * level down inside the pagination companion. * * - `hasMore` — a boolean; stop when it is `false`. * - `totalPages` — an integer count of pages; stop once the pages fetched so * far reach it. For the `page` strategy that is * `page - pageStart + 1 >= totalPages` — `page >= totalPages` when pages * start at 1, `page + 1 >= totalPages` when they start at 0 — for * `offset` it is `floor(offset / limit) + 1 >= totalPages`, and for * `cursor`, whose opaque cursor carries no page number, it is the number * of requests made so far `>= totalPages`. * - `totalCount` — an integer count of items; stop once the items received * so far reach it. * * An empty page ends the iteration under every kind and every strategy. */ interface PaginationEndOfIteration { kind: 'hasMore' | 'totalPages' | 'totalCount'; path: string; } /** * Structured pagination metadata for auto-paging iterator generation. * * Present only when a query parameter the operation declares drives the * iterator — the one detection recognized, or the one an override names — * so `param` is always a query parameter of the operation. A list envelope * returned by an operation that declares no such parameter (a `page` * without a page size, no paging parameter at all) is kept as a plain * response model and has no entry here. */ interface PaginationMeta { strategy: PaginationStrategy; /** Query parameter that selects the page: the cursor, the offset, or the page number. */ param: string; /** Query parameter that sets the page size (`offset` and `page` strategies). */ limitParam?: string; /** * First page number the API expects; set for the `page` strategy only. The * page parameter's integer `default`, else its `minimum`, else 1 — read * from the parameter's schema as written, through a `$ref`, `allOf` * members and nullable wrappers — or the value an override sets (an * override may set it under the `page` strategy only). An * iterator sends `pageStart` first and `pageStart + n` after `n` pages; * `PaginationEndOfIteration` shows how the base enters the `totalPages` * stop rule, so emitters never re-derive it. */ pageStart?: number; /** * Path to the data array the response was unwrapped on (`data`, * `result.items`); absent when the response is the array itself. The * property is the array in every spelling a field is typed as one: * written as an array, under a nullable wrapper or an `allOf` read as * its member, a `$ref` to an array component, or a JSON Pointer deeper * into a component that lands on a schema typed as an array where it * stands (`#/components/schemas/Holder/properties/owners`; #609), read * ahead from the document as the settle will type it — so `response` is * the pointed array once settled and `itemType` its items, the model the * pointed schema's items built, never a copy. */ dataPath?: string; /** * The description the document gives the data array property itself — the * one `dataPath` names — so an emitter that documents what a list method * returns can read it here instead of from the document. Like a `Field`'s * `description` it is the property's own text, never the item schema's. * * Present only when the property declares one; absent whenever `dataPath` * is, since there is no property to take it from. */ dataDescription?: string; itemType: TypeRef; /** * Every property the list envelope carries besides the data array, in * document order: the pagination companion (`list_metadata`, `pagination`, * `has_more`, …, recognized in any spelling — `pageInfo` as much as * `page_info`) and any discriminant such as `object: "list"`. Together * with `dataPath` and `itemType` this is the envelope's full shape, so an * emitter can type what the endpoint returns and read the page details it * needs for the next request without parsing the document itself. * * An inline companion object is lifted to a model. Because the same envelope * recurs on every list endpoint of an API, copies that agree structurally * share one model named from the property alone (`list_metadata` → * `ListMetadata`, or the component schema of that name when one exists); a * copy whose shape differs keeps an operation-qualified name * (`ListUsersListMetadata`) so it can never change another type's shape. * * Absent when the response is a bare array, or when pagination was inferred * from query parameters alone and no envelope was detected. */ envelopeFields?: Field[]; /** * Where the response says the iteration is over (see * `PaginationEndOfIteration`). Detected from a recognized list envelope * when it carries an obvious field — a boolean `has_more`/`hasMore`, an * integer `total_pages`/`totalPages`, or an integer `total`/`total_count`, * each in any spelling that separates its words (`HasMore`, `has-more`) — * beside the array a nested `dataPath` names (`result.total_pages`), beside * each object the path passes through on its way there, nearest the array * first, at the top level, or one level down inside a pagination companion * object (`pagination.totalPages`), in that order, and the same way from * the body an explicit `dataPath` keeps as a wrapper — a component the * response is a `$ref` to, or an inline body detection did not recognize; * a `hasMore` field is preferred over a * `totalPages` one, which is preferred over a count. The operation's * `x-pagination` extension or its `operationHints` entry can set it * explicitly, to a field of the primary response whose type fits the kind. * Absent when nothing recognizable is declared; an emitter then * stops on an empty page (and, for `cursor`, on a missing next cursor). */ endOfIteration?: PaginationEndOfIteration; } type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace'; /** * JSON Schema validation keywords declared directly on a schema, carried so an * emitter can document a value's limits ("at most 100"), check a value before * sending it, or keep a generated example within range. Every member is * optional and present only when the document declares it; a schema with no * validation keyword has no `constraints` at all. * * Numeric bounds use the OpenAPI 3.1 / JSON Schema 2020-12 shape, where * `exclusiveMinimum` / `exclusiveMaximum` are the bound itself. OpenAPI 3.0 * spells them as booleans that make `minimum` / `maximum` exclusive; the * parser normalizes that form, so `{ minimum: 0, exclusiveMinimum: true }` * arrives as `{ exclusiveMinimum: 0 }` with no `minimum`, and a `false` is * dropped. Emitters read one shape whichever version produced it. * * The keywords on the field, parameter or model schema itself are carried, * conjoined with those of its inline `allOf` members (a single-member * `allOf` is unwrapped by the parser, so its limit is the value's own; a * `$ref` member contributes the keywords written beside the reference while * the referenced model keeps its own). A nullable wrapper — `oneOf`/`anyOf` * with a single non-null, non-`$ref` branch — conjoins that branch's * keywords with its own. * * The types carry them too (#545). Every `TypeRef` the parser builds from a * schema it types in place — a `primitive`, `literal`, `array`, `map` or * `union` — carries that schema's keywords as `constraints`, read exactly * as a field's are: the schema's own conjoined with its `allOf` members' * and, through a nullable wrapper, the wrapper's with its branch's (so * `nullable` itself carries none; its `inner` does), and for a `$ref` to * an array or primitive component the component's and each alias's * conjoined with any written beside the reference, as `Field.constraints` * conjoins them, and for a JSON Pointer `$ref` deeper into a component * (#539) the limits the pointed schema's own type carries, conjoined the * same way once the site is settled. A `model` or `enum` reference carries none: the model it * names carries its own (`Model.constraints`), and what is written around * such a `$ref` is the field's or parameter's alone. So a field's or * parameter's `constraints` equal those of its type (under its nullable * wrapper) whenever the type can carry them — the field keeps its own copy * so an emitter can read a value's limits without descending into its type * — and the type carries them where no field could: an array's `items`, a * union's variants, a map's values, a response header's or a body's type. * `{ type: 'array', items: { type: 'string', pattern: '^tag_' } }` has * `{ pattern: '^tag_' }` on its `items`; `anyOf: [{ type: 'string', * pattern: '^pet_' }, { type: 'string' }]` has it on its first variant and * none on the second, so an emitter can type the two apart * (`` `pet_${string}` | (string & {}) ``). A union built from a type list * (`type: ['string', 'integer']`) carries the schema's keywords itself and * its variants none: each variant is the same schema read as one of its * types, so the limits are read from the union for whichever type the * value takes. * * `oagen diff` compares them on every node that carries them, the type's * at every level included, and reports each keyword tightened or loosened * (`field-constraints-changed`, `param-constraints-changed`, * `header-constraints-changed`, `variant-constraints-changed`, * `constraintsChanged` on a model), breaking when tightened on a * request-facing site (#599; see docs/cli.md). */ interface Constraints { /** Inclusive lower bound (`minimum`). */ minimum?: number; /** Inclusive upper bound (`maximum`). */ maximum?: number; /** Exclusive lower bound as a number; the OAS 3.0 boolean form is normalized to this. */ exclusiveMinimum?: number; /** Exclusive upper bound as a number; the OAS 3.0 boolean form is normalized to this. */ exclusiveMaximum?: number; /** The value must be an integer multiple of this (`multipleOf`). */ multipleOf?: number; /** Minimum string length in characters (`minLength`). */ minLength?: number; /** Maximum string length in characters (`maxLength`). */ maxLength?: number; /** ECMA-262 regular expression the string must match (`pattern`), verbatim from the document. */ pattern?: string; /** Minimum number of array items (`minItems`). */ minItems?: number; /** Maximum number of array items (`maxItems`). */ maxItems?: number; /** Present, and `true`, when array items must be unique; `uniqueItems: false` restates the default and is dropped. */ uniqueItems?: boolean; /** Minimum number of items matching the schema's `contains` (`minContains`). */ minContains?: number; /** Maximum number of items matching the schema's `contains` (`maxContains`). */ maxContains?: number; /** Minimum number of object properties (`minProperties`). */ minProperties?: number; /** Maximum number of object properties (`maxProperties`). */ maxProperties?: number; /** Property name → properties that must also be present when it is (`dependentRequired`). */ dependentRequired?: Record; } interface Parameter { /** * The name as the document wrote it (`X-Pet-Token`); emitters apply their * own casing. A parameter's identity is its location and name — * `parameterKey` in `ir/parameter-key.ts`, which compares a header's name * case-insensitively (RFC 9110 §5.1) and every other as written. The * parser merges a path item's parameters into its operations on that * identity, and the differ pairs parameters on it. */ name: string; /** * The parameter schema's type. The parameter's schema is its `schema` or, * for a parameter declared with a `content` map in its place, the schema * of the entry read from that map: `application/json` or a `+json` media * type when the entry declares a schema, else `text/plain` with or without * one, each matched by media type essence (parameters and case stripped). * A `text/plain` entry without a schema types the parameter as a string; * a map none of whose media types is read does too, with a parser warning * that names them; a `schema` beside a `content` map wins. Every field of * this interface that reads "the parameter's schema" reads this schema, * so a parameter declared either way is typed by one rule. * * An inline object schema (a `deepObject` query parameter, say), or an * array, map, union or nullable wrapper holding one, references a model * the parser creates for it, named from the service and parameter * (`PetsFilter`; a header's name lower-cased first, so `X-RateLimit-Meta` * and `x-ratelimit-meta` both reference `PetsXRatelimitMeta`) and * qualified by location or operation when that name already belongs to * another shape (see "Response Headers" in docs/architecture/ir-types.md); * a webhook's is named under the webhook's stem. A primitive, a `$ref`, an * inline enum (named the same way) or an array of either is typed as * written. */ type: TypeRef; required: boolean; description?: string; deprecated?: boolean; /** * The parameter schema's `externalDocs`, when it declares a usable one; * a schema that is a `$ref` falls back to the component it points at, * the way `description` and `deprecated` do. A Parameter Object has no * `externalDocs` of its own. Absent when neither level gives one. */ externalDocs?: ExternalDocs; default?: unknown; /** * A single illustrative value, resolved level by level: the parameter's own * `example` (else the first entry of its `examples` map), then — for a * parameter declared with `content` — the same on the Media Type Object * its schema was read from, then the parameter schema's `example` (else * the first of its `examples` list), then the same on the component schema * its `$ref` points at. A level with neither falls through; an explicit * `null` is kept. Absent when no level gives one. */ example?: unknown; /** * Every example value the document gives, in document order: the * parameter's `examples` map of Example Objects (each entry's `value`, with * `$ref`s resolved against `components.examples`), else — for a parameter * declared with `content` — the same map on the Media Type Object its * schema was read from, else the JSON Schema `examples` list on the * parameter's schema, else the list on the component schema its `$ref` * points at. Present only when at least one value exists. */ examples?: unknown[]; style?: 'form' | 'simple' | 'label' | 'matrix'; explode?: boolean; /** * The media type the parameter's value is serialized in: the `content` * key its schema was read from, as written (`application/json; * charset=utf-8`). Present exactly when the parameter is declared with * `content` and the map is read (see `type`) — a schema-less `text/plain` * entry included; absent for a `schema` parameter, and for a `content` * map none of whose media types is read, whose string value is sent as * written (`contentTypes` keeps that map's media types). An emitter that * serializes parameters by `style` and `explode` must instead serialize * such a value in this media type: JSON-encode an `application/json` or * `+json` value, send a `text/plain` value as text. `oagen diff` compares * it by essence — an unread map by the first of its `contentTypes` — and * reports a change as a `param-content-type-changed`, breaking unless both * sides are read from a JSON media type. */ contentType?: string; /** * The media types the parameter's `content` map declares: its keys, in * document order and exactly as written. Present when the parameter is * declared with `content` and the map declares at least one media type, * whether or not one of them is read (`contentType` is the one that is), * as `Operation.requestBodyContentTypes` is for a request body; absent for * a `schema` parameter, a `schema` beside the map included. OpenAPI allows * the map one entry. For a map none of whose media types is read, this is * where the media type the document declares the value in is kept: the * value is typed as a string and sent as written, so an emitter has * nothing to encode. */ contentTypes?: string[]; /** * Validation keywords from the parameter's schema, read as a field's are * (`schemaConstraints`; #545 review): the schema's own conjoined with its * `allOf` members' and a nullable wrapper's with its branch's, level by * level, so a keyword written beside an `allOf` member that writes it too * reads as the field and the type read it (`pattern: '^a'` beside `allOf: * [{ pattern: 'z$' }]` is `{ pattern: '^a' }` on all three, the schema's * own winning as `combineConstraints` keeps it; #587 review); for a `$ref` * to a primitive or array component, or to an alias of an enum component, * every entry's conjoined from the component outward, since no model * carries them (the alias's own above the enum's; #560). When the schema * is a `$ref` to a model or enum, the target's keywords are merged * underneath the parameter's own — the per-value fallback `default` and * `example` use — so a parameter can be read on its own without chasing * the target. Absent when neither declares any. Equal to the limits * `type` carries (under its nullable wrapper) whenever it can carry them * — a JSON Pointer `$ref` deeper into a component included, once the * pointer is settled (see `Field.constraints`) — while a `$ref` to a * model or enum keeps the parameter's own here alone (see `Constraints`). */ constraints?: Constraints; } /** Type reference — the core type system of the IR */ type TypeRef = PrimitiveType | ArrayType | ModelRef | EnumRef | UnionType | NullableType | LiteralType | MapType; interface PrimitiveType { kind: 'primitive'; type: 'string' | 'integer' | 'number' | 'boolean' | 'unknown'; format?: string; /** * The validation keywords of the schema this primitive was built from — * `pattern`, `minLength`, `minimum`, … — read as a field's are and * present only when it declares any (see `Constraints`; #545): a field's * own string, an array's items, a union's variant, a map's values and a * `$ref` to a primitive component (the component's own) alike, so * `items: { type: 'string', pattern: '^tag_' }` is readable from `items`. */ constraints?: Constraints; } interface ArrayType { kind: 'array'; items: TypeRef; /** * The validation keywords of the array schema itself — `minItems`, * `maxItems`, `uniqueItems`, … — read as a field's are and present only * when it declares any (see `Constraints`; #545). The items' own keywords * are on `items`, so a nested array carries each level's where it sits: * `{ type: 'array', minItems: 1, items: { type: 'array', uniqueItems: * true, items: { type: 'string', pattern } } }` is `{ minItems: 1 }` * here, `{ uniqueItems: true }` on `items` and `{ pattern }` on its items. */ constraints?: Constraints; } interface ModelRef { kind: 'model'; name: string; } interface EnumRef { kind: 'enum'; name: string; values?: (string | number)[]; } interface LiteralType { kind: 'literal'; value: string | number | boolean | null; /** The validation keywords written beside the `const` or single-member `enum`, read as a field's are and present only when it declares any (see `Constraints`; #545). */ constraints?: Constraints; } interface UnionType { kind: 'union'; /** * The variants, in the document's order: a `oneOf`/`anyOf`'s non-null * variants, or — for an OAS 3.1 type list naming several types (`type: * ['object', 'string']`) — one per non-null type in the list's order, * each the schema read as that type alone: keeping the keywords that * apply to an instance of it (`properties` for the object, `items` for * an array, `format` and `pattern` for a string; `const`, `enum` and a * composition for every type) and left out when the schema's * `allOf`/`oneOf`/`anyOf` admits no instance of it (#616). `{ type: * ['object', 'string'], allOf: [{ $ref: Owner }] }` is `Owner | string` * when `Owner` declares `properties` and no `type`, and `Owner` alone — * no union — when `Owner` is `type: 'object'`, which no string * satisfies. Never one type twice: copies typed alike are one variant, * and a lone variant is the type itself. */ variants: TypeRef[]; /** * When set, the union is discriminated on `property`, and `mapping` names * the variant each value selects. Resolved from the same sources, in the * same order, as a named union's (`Model.discriminator`), from the same * reading of the variants (#568): the spec's own `discriminator.mapping`, * each target as the document spelled it with a leading * `#/components/schemas/` stripped — an inline union's values are not IR * model names, unlike a named union's — except an entry whose target is a * pointer variant's schema, settled with the variant to the model's IR * name as a named union's is (#539); else, under the keyword, each * variant's const on the property paired with the model it is referenced * by, `{}` when any variant pins none or is unnamed; else, for a `oneOf` * without the keyword, the first property the first variant pins whose * values tell every variant apart. A `$ref` variant is named by its * component and its const read from it — through the component's `allOf` * members, a `$ref` member followed to the component it names, and * through a `$ref` on the property to a component pinning one value * (`Cat: { allOf: [{ $ref: CatBase }, …] }` pins what `CatBase` pins; * `kind: { $ref: HamsterKind }` pins what `HamsterKind` does) — the * declaration read as the type builder reads it, at every hop: a `$ref` * to its component, a nullable wrapper to its one variant, an `allOf` * read as one member to that member, then the `const` or one-value * `enum:` written there, so `kind: { allOf: [{ const: 'cat' }] }`, * `kind: { allOf: [{ $ref: HamsterKind }], description }` and a `$ref` * to `RabbitKind: { allOf: [{ $ref: RabbitConst }] }` pin as `kind: { * const: … }` does, in OAS 3.0 and 3.1 alike (#607) — a * variant wrapping one model `$ref` through that reference, an inline * object variant by the model extracted for it, so `oneOf: [{ $ref: Cat }, * { $ref: Dog }]` carries `{ cat: "Cat", dog: "Dog" }` on a field as it * does as a component. * A request body's union carries only the spec's own mapping; a body * that is a `oneOf` of inline objects under the keyword, each pinning the * property by the same reading, is folded into one object instead. */ discriminator?: { property: string; mapping: Record; }; /** Which OAS composition keyword produced this union. Emitters can use this to * distinguish inheritance (allOf) from exclusive union (oneOf) from open union (anyOf). */ compositionKind?: 'allOf' | 'oneOf' | 'anyOf'; /** * The validation keywords of the union schema itself — written beside * its `oneOf`/`anyOf`, or on a type list's schema — read as a field's are * and present only when it declares any (see `Constraints`; #545). Each * `oneOf`/`anyOf` variant carries its own, so `anyOf: [{ type: 'string', * pattern: '^pet_' }, { type: 'string' }]` has `{ pattern: '^pet_' }` on * its first variant and nothing here, while `{ anyOf: [...], maxLength: * 10 }` has `{ maxLength: 10 }` here. A type list's variants carry none: * `{ type: ['string', 'integer'], maxLength: 20, minimum: 1 }` has both * here, to read for whichever type the value takes. */ constraints?: Constraints; } /** * A type that admits `null` beside `inner`. Carries no `constraints` of its * own: a nullable wrapper's validation keywords are the value's, conjoined * onto `inner` as a field's conjoin through the wrapper (see `Constraints`). */ interface NullableType { kind: 'nullable'; inner: TypeRef; } interface MapType { kind: 'map'; valueType: TypeRef; keyType?: TypeRef; /** * The validation keywords of the map's object schema itself — * `minProperties`, `maxProperties`, `dependentRequired` — read as a * field's are and present only when it declares any (see `Constraints`; * #545). The values' own keywords are on `valueType`. */ constraints?: Constraints; } /** * A generic type parameter on a model. * Example: `DirectoryUser>` * → `{ name: 'TCustomAttributes', default: { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } } }` */ interface TypeParam { name: string; /** Default type when the param is not specified. */ default?: TypeRef; } /** * Model definition (maps to an SDK model/data class). Every * `components/schemas` entry becomes one, except an enum (`Enum`) and an * alias of one, an array component and a primitive component. An alias of * an enum component — a bare `$ref` to it, a nullable `oneOf`/`anyOf` * around that `$ref`, or an `allOf` read as the reference, alone or beside * members that only annotate it (`PetKind: { allOf: [{ $ref: Kind }, { * description }] }`) — becomes no model and no enum (#560): a `$ref` to it * resolves to the enum (`{ kind: 'enum' }`, under `nullable` when the alias * or the enum admits null), what the alias declares is read by a field that * names it with a bare `$ref` (`Field`), and the enum keeps its own on the * `Enum`. An alias is only a chain that ends at a `$ref` to an enum * component: a component that declares its enum inside a lone `allOf` * member (`Kind: { allOf: [{ type: 'string', enum }], description }`) or * inside a nullable `oneOf`/`anyOf` wrapper (`Kind: { oneOf: [{ allOf: [{ * type: 'string', enum }] }, { type: 'null' }] }`, `Color: { oneOf: [{ * type: 'string', enum }, { type: 'null' }] }`; #606) is the enum `Kind` * or `Color` itself, nullable for the wrapper, never an alias and never a * model. An array component — a schema * that is an array and declares `items` (a nullable `oneOf`/`anyOf` around * one included), or an alias of one (a bare `$ref`, a nullable * `oneOf`/`anyOf` around a `$ref`, or an `allOf` of a `$ref` and limits) * — becomes no model at all: a `$ref` to it resolves to the array it * declares (`{ kind: 'array' }`, under `nullable` when the component admits * null), and what its items reference is extracted under `Item…`. * A primitive component — a `string`, `integer`, `number` or `boolean` * schema, a `const` of any value, a type list of such primitives * (`['string', 'integer']`) or a schema that declares no type at all (`{ * description: 'Any value.' }`, `{}`, and the same inside an `allOf` whose * members each declare none: `{ allOf: [{ description }] }`), nullable in * any spelling, or an alias of one — becomes no model either: a `$ref` to * it resolves to what it declares, as the same schema written inline is * typed — the primitive * (`{ kind: 'primitive' }` with its `format`), the literal (`{ kind: * 'literal' }`), the union of primitives (`{ kind: 'union' }`) or `unknown` * (`{ kind: 'primitive', type: 'unknown' }`), under `nullable` when the * component admits null (#512, #569). What either component and its * aliases declare beside the items or the type — text, link, flags, * limits, `default`, `x-*` keys — is read by a field that names it with a * bare `$ref` (`Field`). A component that is only a `$ref` to a component * that becomes a model — `CatAlias: { $ref: Cat }`, with or without * `description`, `deprecated`, `externalDocs`, limits or `x-*` keys beside * the `$ref`, which are the alias's own — is a model of its own carrying * `Cat`'s fields, `required` and discriminator, exactly as `CatAlias: { * allOf: [{ $ref: Cat }] }` is, through a chain of such aliases (nothing * else an alias writes beside its `$ref` — `properties`, `required`, an * `allOf`, a union, a `discriminator` — is read, at any hop, as nothing * but annotations is read beside any `$ref`; only the `allOf` spelling * composes them) and into a component that itself composes; a `$ref` to it resolves to the alias * (`{ kind: 'model', name: 'CatAlias' }`), never to `Cat`, at every site, * and as a union variant it pins what `Cat` pins (#618: it was a model with * no fields). A chain of bare `$ref`s that returns to itself names nothing: * each such component is a model with no fields, reported once. The inline * schemas the parser materializes — request bodies, * responses, union variants, nested objects, array items, map values — are * models too. */ interface Model { name: string; /** * The schema's own `description`; for a model built from an `allOf` — a * component's, or an inline merge — the wrapper layer's: the schema's * own, else the first `allOf` member's that declares no type (`allOf: * [{ $ref: Base }, { properties: { name } }, { description: 'An owner.' * }]`; #555 review). A typing member's text stays on that member, a * `$ref` member's on its component. */ description?: string; /** The schema's `externalDocs`, when it declares a usable one; for an `allOf` model, the wrapper layer's, as `description` is. */ externalDocs?: ExternalDocs; /** * Present, and `true`, when the schema this model was built from says * `deprecated: true` — a component, a discriminated-union variant, or an * inline request body, response or field object. Only that schema's own * top-level keyword counts, read as `Field.deprecated` is: a nullable * branch's flag is not read, nor an `allOf` member's that declares a type * (a `$ref` member's stays on the referenced model) — one that declares * none, `{ deprecated: true }` beside the members, is part of the wrapper * and deprecates the model (#555 review) — and a folded `Json` * model's flag does not deprecate the `` it collapses into. Absent * otherwise. An inline * schema that shares the name of a model the document declares has no * model of its own: a deprecated schema identical to a live component * keeps its flag on the `Field`, `Parameter`, `ResponseHeader` or envelope * field that wrote it, and a site with no node of its own carries none — a * request body or response, an array's items, a `oneOf` variant, a webhook * payload variant, an error or secondary body — so deprecating only the * items of `Pet.owners` beside a live component of their shape leaves no * trace in the IR, as it leaves none when two inline copies fold. An * inline schema named like a deprecated component shares nothing with it, * whatever its flag: it keeps a model of its own, qualified by its site * (`GetLegacyWidgetWidget` beside a deprecated `Widget`), which carries * the schema's flag, so deprecating the schema flips this flag on that * model and renames nothing (#441). */ deprecated?: boolean; fields: Field[]; /** * The components a composed component's `allOf` names, one `{ kind: * 'model' }` reference per `$ref` member, in document order, each once: * `Pet: { allOf: [{ $ref: Animal }], properties: { nickname } }` has * `bases: [Animal]`, `allOf: [{ $ref: Animal }, { $ref: Owned }]` has * `[Animal, Owned]`. Each model names only its direct bases: with * `Animal: { allOf: [{ $ref: Living }], … }`, `Animal.bases` is * `[Living]` and `Pet.bases` stays `[Animal]`, since `Animal` already * covers `Living`. A member names the component its reference resolves * to, as the inline merge records a property's origin * (`mergeAllOfMembers`): a bare alias (`Hop: { $ref: Animal }`) is read * as `allOf: [{ $ref: Animal }]`, a model of its own (#618), so it is the * base and `Animal` is its own base in turn, as an `allOf` component * (`Hop: { allOf: [{ $ref: Animal }] }`) is; a nullable alias (`Alias: { * oneOf: [{ $ref: Animal }, { type: 'null' }] }`) declares nothing of its * own, so the base is `Animal`. A `$ref` member * naming an enum, array or primitive component — which builds no model * and contributes nothing to the fields — is no base. A `$ref` member * whose component an earlier member's chain already read declares * nothing more but is a direct base all the same: `allOf: [{ $ref: * Animal }, { $ref: Living }]` over `Animal: { allOf: [{ $ref: Living }] * }` has `[Animal, Living]`, and `[Living, Animal]` the other way * round, the fields it carries naming the first member that declares * them; the same `$ref` twice is one base, a component naming * itself, or an alias of itself, is no base of its own, and two bases a * rename sends to one name (`Bar` beside a `BarJson` folded onto it) * are one, the first kept (`renameModelRefs`). A `…Json` * component folded onto its base carries its bases with its fields, * less one whose own chain reaches the folded model, which would close * a cycle (see `collapseJsonSuffixModels`); and the parser's last pass * (`settleBases`) settles both keys against the models as they end: no * model's chain of bases reaches itself — a base that does, in a cyclic * document or once a fold collapsed it onto a kept model of the same * shape, is dropped — and a base stays a base only while every field * it ends with is on the model either as the model's own declaration, * which overrides the base's, or as the same field, the base's * declaration and not another's (every key; the type as its final * shape, an inline model built under either model as it ends and an * inline enum by its values), so the model is its own fields plus its * bases' and an emitter writing `extends` or an intersection types * every field as `fields` does: two bases declaring one property * differently (`Tagged.tag: string` beside `Kinded.tag: enum [cat, * dog]`) keep at most the one whose declaration the model carries, the * other's fields the model's own, and a fold that loosens a base, or a * model nested under it, after the model took its fields drops that * base. A field carries `inheritedFrom` only while its base stays. A `$ref` member naming a named union — flattened into * the fields or dispatched, as the union's own model reads it — is a * base like any other model. Present exactly when at least one base is * named, on a model built from a component schema (a dispatcher * included); never on a model built from an inline `allOf` — a request * or response body, a field — nor on a dispatcher's variant models. * `fields` stays complete, the inherited fields included, in the order * the members are read, so an emitter that reads neither this key nor * `Field.inheritedFrom` sees the model it always saw; one that reads * them may write `Pet` as `Animal & { nickname?: string }` or `interface * Pet extends Animal` (see `Field.inheritedFrom`). Provenance, not * shape: two models that differ only here are one shape to the differ * and to the parser's fingerprints, and `collectModelTypeRefs` leaves * the references out, while `renameModelRefs` repoints them, * `validateModelRefs` checks them and reachability for emission * (`collectReferencedNames`) chases them, so the base of an emitted * model is emitted; `collectFieldDependencies` does not list them — an * emitter that writes `extends` imports the base itself. */ bases?: TypeRef[]; /** Generic type parameters. Empty/undefined for non-generic models. */ typeParams?: TypeParam[]; /** * Set when the model is a named union: a component schema that is itself a * `oneOf`/`anyOf` with no `properties` of its own. One TypeRef per non-null * variant, in document order, built exactly as an inline union's are: a * `$ref` variant is a `model`/`enum` ref, an inline object variant is a ref * to a model extracted for it (named from this model with the inline * variant rules, never this model's own name), a primitive stays a * primitive. A `type: 'null'` variant is dropped, as an inline union lifts * it into a `nullable` wrapper; a Model has no such wrapper. `fields` keeps * the optional merge of the inline variants' properties it always had, so * an emitter that does not read `variants` sees the same model as before. */ variants?: TypeRef[]; /** Which composition keyword produced `variants`. Present exactly when `variants` is. */ compositionKind?: 'oneOf' | 'anyOf'; /** * When set, this model is a discriminated union — over its `variants` (a * named `oneOf`/`anyOf` with a `discriminator:` keyword or a const-pinned * property shared by every variant, a `$ref` variant's read from its * component as `UnionType.discriminator` reads it) or over allOf+oneOf variants (where * `variants` is absent and the mapping alone names them: the union a * composed component carries, as an `allOf` member, beside the `allOf` * or beside the component's own `properties`, whose every variant pins * one property to a distinct const — a `$ref` variant's read from its * component — or that the document declares a `discriminator:` for, on * the union or on the component itself). Emitters should generate a * dispatcher (factory) instead of a regular dataclass. The `property` * field is the discriminator key (e.g. "event"), and `mapping` maps each * discriminator value to the concrete variant model name (an IR model * name, after `schemaNameTransform`): an inline variant's model, built * for it and named from the const it pins (`PetCat`), or a `$ref` * variant's component (`{ cat: "Cat", dog: "Dog" }`), which stands for * it (#398). The const is read as `UnionType.discriminator` reads one — * through a `$ref`, a nullable wrapper and an `allOf` read as one member, * at every hop — for the value and the variant's name alike, so `kind: * { allOf: [{ const: 'cat' }] }` dispatches to `PetCat` as `kind: { * const: 'cat' }` does (#607). */ discriminator?: { property: string; mapping: Record; }; /** * Validation keywords declared on the model's own schema — for an object * schema, `minProperties`, `maxProperties` and `dependentRequired`. Absent * when the schema declares none. */ constraints?: Constraints; /** * The `x-*` keys of the schema the model was built from (see * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`: a * component's own, or the inline schema's — a request body, a response, * a `oneOf` variant, an object nested in a field, array items, an * `allOf` wrapper's (a member's keys stay on that member, a `$ref` * member's on its component). A nullable `oneOf`/`anyOf` or single-member * `allOf` wrapper the parser collapses carries its keys onto the model * built from its branch, the wrapper's value winning for a key both * declare, as its link rides onto it. Present only when at least one key * remains. Not shape: an inline schema that differs from a model only * here shares that model, which keeps its own keys. */ extensions?: Extensions; } interface Field { name: string; /** * Optional domain-facing name override. When set, emitters derive the * domain-side identifier (in their own casing) from this instead of `name`, * while serialization still uses `name` for the wire key. Lets an SDK expose * a wire field under a friendlier name (e.g. `connection_type` → `type`) * without changing the API contract. Set via the `fieldHints` config and * honored by any emitter that reads it. */ domainName?: string; type: TypeRef; required: boolean; /** * The direct base — an entry of `Model.bases` — this field is taken from * unchanged, as a `{ kind: 'model' }` reference; absent when the model * declares the field itself, or when a declaration of its own — written * beside the `allOf` or in an inline member, before or after the `$ref` * — changes what the base declares, by any key: its type, its * `description`, a `nullable` or `deprecated` flip, or its `required` * (the model requiring a field the base leaves optional). A declaration * the merge sets aside — a later typing one, which the first typing * declaration outranks (`declareProperty`) — changes nothing, and the * field stays the base's. `Pet: { allOf: [{ $ref: Animal }], required: * [name], properties: { name: { type: 'string', enum: [rex, max] }, * nickname } }` over `Animal { name?, species? }` carries `name` and * `nickname` without it and `species` with `inheritedFrom: Animal`, so * an emitter can write `Pet` as `Animal & { name: PetName; nickname?: * string }`; `Pet: { allOf: [{ $ref: Animal }], required: [species] }` * carries `species` without it. A field a base inherits in turn names * the direct base: with `Animal: { allOf: [{ $ref: Living }] }`, * `Living`'s `born` is on `Pet` with `inheritedFrom: Animal`. A field * a base's flattened `oneOf`/`anyOf` variants declare is the model's own * (optional on both, with no origin), as a field the model's own * variants declare is. Unchanged means as the document declares it: the * field's `type` is still built under this model's name, so an inline * object `Animal.meta` declares is `AnimalMeta` on `Animal` and * `PetMeta` on `Pet` — the same shape — with `inheritedFrom: Animal`. * Only on a field of a model that carries `bases`. Provenance, not * shape: two fields that differ only here are one shape to the differ * and to the fingerprints; `renameModelRefs` repoints it and * `validateModelRefs` checks it. */ inheritedFrom?: TypeRef; /** * The field schema's own `description`; for a bare `$ref` to an array or * primitive component — which names no model to carry the component's * text — the nearest the reference passes on its way to the array or * primitive (an alias's own, else the component's), as `example` falls * back to it. A `$ref` to a model, named union or enum leaves the text on * it; a bare `$ref` to an alias of an enum component reads the nearest * alias's own — an `allOf` member of its that declares no type included — * and leaves the enum's on the enum (#560). Under a wrapper — a nullable * one, an `allOf` read as the reference * (`{ allOf: [{ $ref: PetId }, { description }] }`) — the field documents * itself: the wrapper's text or a member's written beside the `$ref`, * never the component's; the same holds for every annotation, flag, default * and key below, while `constraints` conjoin through a wrapper. An `allOf` * member that declares no type — `{ description }`, `{ deprecated: true }`, * `{ readOnly: true }`, `{ maxLength: 3 }`, `{ 'x-internal': true }` — is * part of the field's schema, whatever the other members: beside a `$ref` * (`{ allOf: [{ $ref: Kind }, { description }] }` is `Kind` with that * text on the field), beside the one member that types the schema * (`{ allOf: [{ type: 'string', enum: [...] }, { description }] }` is the * enum, read as `{ allOf: [{ type: 'string', enum: [...] }], description }` * is; #555) or beside a merge — the schema's own value first, then the * first such member's, for every keyword below. */ description?: string; /** * The field schema's own `externalDocs`, when it declares a usable one — * read like `description`: for a `$ref` with an `externalDocs` sibling * (legal in OAS 3.1), the sibling's link, while the referenced model keeps * its own; a bare `$ref` yields none, unless it names an array or * primitive component, or an alias of an enum component, whose link the * field then carries. Absent otherwise. Documentation, not shape: two * fields that differ only here are one shape. */ externalDocs?: ExternalDocs; /** * `true` when the field schema says `readOnly: true` — itself, or an * `allOf` member of its that declares no type (`allOf: [{ $ref: Kind }, * { readOnly: true }]`; #555) — or when a bare `$ref` names an array or * primitive component that says so, or an alias of it, or of an enum * component, on the way (see `description`). `writeOnly` is read the same * way. */ readOnly?: boolean; writeOnly?: boolean; /** * Present, and `true`, when the field schema says `deprecated: true` — a * keyword written beside a `$ref` included, and an `allOf` member that * declares no type (`allOf: [{ $ref: Kind }, { deprecated: true }]`; #555) * — or when a bare `$ref` names an array or primitive component that says * so, or an alias of it, or of an enum component (#560), on the way, since * no model carries that component's or alias's flag. The flag of a model, * named union or enum a `$ref` names stays on it. */ deprecated?: boolean; /** * The field schema's own `default`, an explicit `null` included; for a * bare `$ref` to an array or primitive component that declares none, or to * an alias of an enum component, the nearest the reference passes (see * `description`). */ default?: unknown; /** * A single illustrative value. The field schema's `example` when present, * otherwise the first entry of its `examples`; when the schema is a `$ref` * with neither, the same taken from the component it points at — for an * array or primitive component, from the nearest level the reference * passes on its way to the array or primitive (an alias's own, else the * component's), as `description` is read; for an alias of an enum * component, the aliases' own first, then the enum's. An explicit `null` * is kept. Absent when no level gives one. */ example?: unknown; /** * Every example value the schema gives, in document order, from the JSON * Schema `examples` list (OAS 3.1 deprecates `example` in its favour) — * on the field schema, else on the component its `$ref` points at, an * array or primitive component's read like `example`: the nearest * non-empty list the reference passes on its way to the array, primitive * or enum. Present only when the list has at least one entry. */ examples?: unknown[]; /** * Validation keywords declared on the field's schema, including any * written beside a `$ref` (OpenAPI 3.1 allows siblings). A `$ref` to a * model, named union or enum adds none, since the referenced node carries * its own limits; a `$ref` to an array or primitive component, which * names no model, conjoins the component's limits and its aliases' with * the field's own (`{ $ref: Tags, maxItems: 3 }` beside `Tags`'s * `minItems: 1, maxItems: 5` is `{ minItems: 1, maxItems: 3 }`), and one * to an alias of an enum component conjoins the aliases' own, the enum's * staying on the enum (#560) — bare * or under a wrapper the type builder reads through, since the wire * enforces them either way and nothing else carries them: `{ allOf: [{ * $ref: PetId }, { description }] }` beside `PetId`'s `pattern` carries * that `pattern`, as `{ allOf: [{ $ref: PetId }] }` and `oneOf: [{ $ref: * PetId }, { type: 'null' }]` do. A JSON Pointer `$ref` deeper into a * component (#539) conjoins the same way with the limits the schema it * lands on carries on its own type, once the pointer is settled * (`resolveSchemaPointers`; #545 review): `{ $ref: '#/components/schemas/ * Owner/properties/code', maxLength: 3 }` to `{ type: 'string', pattern: * '^own_', maxLength: 8 }` is `{ maxLength: 3, pattern: '^own_' }`, and * the bare pointer `{ maxLength: 8, pattern: '^own_' }`; a pointer to a * property typed as a model or enum adds none, as a `$ref` to a model * does. Absent when no level declares any. Equal to the limits `type` * carries (under its nullable wrapper) whenever it can carry them — a * `$ref` to a model, named union or enum keeps the field's own here * alone — while the limits of an array's items, a union's variants or a * map's values are on those types only (see `Constraints`; #545). */ constraints?: Constraints; /** * The field schema's own `x-*` keys (see `Extensions`), less * `x-enum-descriptions` / `x-enumDescriptions`, read like `constraints`: * keys written beside a `$ref` (legal in OAS 3.1) are the field's, a bare * `$ref` yields none — the referenced model, union or enum carries its * own — unless it names an array or primitive component, or an alias of * an enum component, whose keys and its aliases' the field then carries * under its own, the field's winning per key, as it carries that * component's `description`. A property * several `allOf` members always declare is typed by the first typing * declaration, keys included (a typeless one fills in what it leaves * unset); a property only variants declare carries exactly the keys * every declaration as written agrees on, value for value, whether or * not the declarations share one shape — in an inline `allOf` and under * a component (a bare `oneOf` component, a union member of a component * `allOf`) alike. Present only when at least one * key remains. Not shape: two fields that differ only here are one shape. */ extensions?: Extensions; } /** Enum definition */ interface Enum { name: string; /** * The enum schema's own `description`: a component enum's, as * `Model.description` is a component model's — the wrapper layer's over * the member's when the component declares its members inside an * `allOf` read as its one typing member (`Kind: { allOf: [{ type: * 'string', enum }], description }`), or the wrapper's over the branch's * when it declares them inside a nullable `oneOf`/`anyOf` wrapper * (`Kind: { oneOf: [{ allOf: [{ type: 'string', enum }, { description * }] }, { type: 'null' }] }`; #606), as its link, `deprecated`, * `default` and keys are read (`enumComponentDeclaration`) — or — for an * enum lifted * from an inline schema on a property, parameter, response header, * request or response body (primary, secondary-media-type, error or * fallback) or webhook parameter or payload, including array items, * `oneOf` variants and a `oneOf` of string consts collapsed into one enum * — the text of the schema that declares its members, read as its * `externalDocs` is: a nullable `oneOf`/`anyOf` or single-member `allOf` * wrapper the parser collapses gives its own text when it has content, * and the branch's own counts only when the wrapper has none. A * Parameter or Header Object's `description` is that parameter's or * header's, never the enum's. Present only when the text has * non-whitespace content, kept verbatim. When several inline schemas lift * to one name, the first lifted gives the text, as it gives the values and * the link, so the key is absent when that schema declared none even if a * later one does. Documentation, not shape: the differ does not report a * change to it, and two inline enums that differ only in it are one enum. */ description?: string; values: EnumValue[]; /** Spec-level default value (the value of `default:` on the schema). Optional. */ default?: string | number; /** * The enum schema's `externalDocs`, when it declares a usable one: a * component enum's own, or — for an enum lifted from an inline schema on a * property, parameter or response header — that schema's. A nullable * wrapper the parser collapses carries its link onto the enum, as it does * onto a model; when several inline schemas lift to one name, the first * lifted gives the link, as it gives the values. */ externalDocs?: ExternalDocs; /** Present, and `true`, when the component enum schema says `deprecated: true`; absent otherwise. */ deprecated?: boolean; /** * The `x-*` keys of the schema that declares the members (see * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`, which * the values' `description` is read from: a component enum's own, or — * for an enum lifted from an inline schema — that schema's, read as its * `description` and `externalDocs` are: a nullable `oneOf`/`anyOf` or * single-member `allOf` wrapper the parser collapses carries its keys * onto the branch, the wrapper's value winning for a key both declare. * The field the inline schema types carries the same keys when the enum * schema is the field's own schema; under such a collapsed wrapper the * field carries the wrapper's keys alone (see `Field.extensions`), and * the branch's stay on the enum. When several inline schemas lift to one * name, the first lifted gives the keys, as it gives the values. Present * only when at least one key remains. Not shape: two inline enums that * differ only here are one enum. */ extensions?: Extensions; } /** * One member of an enum. An enum schema is an `enum:` list or a * `oneOf`/`anyOf` whose every non-null variant is a string `const` schema * (the OAS 3.1 spelling that documents values one by one); both give one * `EnumValue` per member, in document order. */ interface EnumValue { /** UPPER_SNAKE_CASE form of `value`. */ name: string; /** The value as written; a number stays a number. */ value: string | number; /** * The value's own documentation: a `const` member's `description`, else * the entry for the value in the enum schema's `x-enum-descriptions` / * `x-enumDescriptions` extension. Present only when that text has * non-whitespace content; absent otherwise. */ description?: string; /** * Present, and `true`, when the value's `const` member says * `deprecated: true`; absent otherwise. An `enum:` list has no per-value * keyword, so its values never carry it. */ deprecated?: boolean; } /** * Exhaustive check helper for TypeRef switches. * If a new kind is added to TypeRef, any switch that doesn't handle it * will fail to compile because `never` won't accept the unhandled variant. * * Usage: * switch (ref.kind) { * case 'primitive': ... * case 'array': ... * // If you forget 'literal', TypeScript errors here: * default: assertNever(ref); * } */ declare function assertNever(x: never): never; /** * The validation keywords `ref` carries (see `Constraints`; #545): its * `constraints` for a `primitive`, `literal`, `array`, `map` or `union`, * `undefined` for a `model` or `enum` reference, which carries none, and * for a `nullable` wrapper, whose `inner` carries the value's. The one * read for every kind, so a reader need not know which kinds carry them. */ declare function typeRefConstraints(ref: TypeRef): Constraints | undefined; /** * Generic depth-first walker for TypeRef trees. * Handles recursion into array/nullable/union/map children and provides * an exhaustive `assertNever` check so callers don't need to repeat the * switch boilerplate. Supply callbacks only for the leaf kinds you care about. */ declare function walkTypeRef(ref: TypeRef, visitor: { model?: (ref: ModelRef) => void; enum?: (ref: EnumRef) => void; primitive?: (ref: PrimitiveType) => void; literal?: (ref: LiteralType) => void; }): void; /** * Generic depth-first mapper for TypeRef trees. * Like walkTypeRef but returns a transformed value instead of void. * Handles recursion into array/nullable/union/map children, passing * already-mapped child values to the parent callback. */ declare function mapTypeRef(ref: TypeRef, mapper: { primitive: (ref: PrimitiveType) => T; array: (ref: ArrayType, mappedItems: T) => T; model: (ref: ModelRef) => T; enum: (ref: EnumRef) => T; union: (ref: UnionType, mappedVariants: T[]) => T; nullable: (ref: NullableType, mappedInner: T) => T; literal: (ref: LiteralType) => T; map: (ref: MapType, mappedValue: T, mappedKey?: T) => T; }): T; /** * Every TypeRef a model owns: each field's type, then each union variant * (`Model.variants`). Every pass that walks a model's type refs (reachability, * service assignment, ref rewriting and validation, dependency collection, * inline-enum promotion, fingerprinting) goes through this so a type reached * only through a named union's variant is treated the way a field type is. * A model's `bases` and its fields' `inheritedFrom` name the models it is * built on, not types it owns — provenance, not shape (#591) — and are left * out, so the fingerprints and the differ read a model with and without * them as one shape; `renameModelRefs`, `validateModelRefs` and * reachability for emission (`collectReferencedNames`) reach them on their * own. */ declare function collectModelTypeRefs(model: Model): TypeRef[]; /** * Rename the models a model refers to: every `model` ref in its fields' types * and its union variants that `renames` maps and `admit` accepts is pointed * at the new name (`renameTypeRefModels`, so a union's mapping inside a field * follows its variant) — its `bases` and its fields' `inheritedFrom` with * them, so a base renamed or folded away is named by its new name, and two * bases the rename sends to one name (`Bar` beside a `BarJson` folded onto * it) are one base, the first kept, so `bases` names each once (#591, * Greptile) — and the model's own `discriminator.mapping` is * rewritten with it: without an `admit`, every target `renames` maps, by * name — whether it names a variant, a model outside the variants a * document's own mapping sends a value to, or a member an allOf+oneOf * dispatcher holds in the mapping alone — so a fold that removes a model * never leaves a dispatcher naming it; under an `admit`, only an entry a * moved variant owns (`mappingEntriesByVariant`), since a target has no * identity to admit. Each reference is looked up once, so a map `{ A → B, B → C }` * moves `A` to `B`, never on to `C`. The model's own `name` is left to the * caller. Every rename and fold site goes through this, so a dispatcher's * mapping can never keep naming a model that was renamed away while its * variants moved on. Returns whether any reference moved. */ declare function renameModelRefs(model: Model, renames: ReadonlyMap, admit?: (ref: ModelRef) => boolean): boolean; /** * Collect all model names referenced (directly or transitively) by a TypeRef. */ declare function collectModelRefs(ref: TypeRef): string[]; /** * Collect all enum names referenced by a TypeRef. */ declare function collectEnumRefs(ref: TypeRef): string[]; /** * Collect all TypeRef-referenced model and enum names from a model's fields * and, for a named union, its variants. * Returns { models, enums } sets for generating import statements. */ declare function collectFieldDependencies(model: Model): { models: Set; enums: Set; }; /** * Assign each model to the service that first references it. * Models referenced by multiple services are assigned to the first. * Models not referenced by any service are unassigned (absent from the map). * * @param hints - Optional pin overrides keyed by IR model name → IR service * name. Applied after the natural assignment loop. A hint only pins a model * present in THIS `models` slice; the target service is resolved by name * downstream, so a hint pointing at a service outside `services` still lands * the model in the right directory. Callers may pass a PARTIAL slice (e.g. * discriminated-union planning, per-service barrels, or a `--services`-scoped * run), so this function never rejects a hint — typo validation lives in * {@link validateModelHints}, which runs once against the full spec. */ declare function assignModelsToServices(models: Model[], services: Service[], hints?: Record): Map; /** * Validate model-placement hints against the FULL spec. Run once at the start of * generation — where the complete model/service universe is known — so typos in * `modelHints` fail loud even though {@link assignModelsToServices} is * intentionally lenient about the partial slices it may be handed. */ declare function validateModelHints(models: Model[], services: Service[], hints: Record): void; /** * Collect all model names referenced as request bodies across all services: * each operation's `requestBody`, and the body of every other media type it * declares (`collectRequestBodyTypes`). */ declare function collectRequestBodyModels(services: Service[]): Set; /** * Every response header an operation declares: the primary response's, each * alternate success entry's, and each error entry's. The primary list is the * same array as its `successResponses` entry when both exist, so it is yielded * once. Every pass that walks an operation's type refs (reachability, model * assignment, ref rewriting and validation, direction, compat filtering, enum * collection) goes through this so a type reached only through a header is * treated the way a body or parameter type is. */ declare function collectResponseHeaders(op: Operation): ResponseHeader[]; /** * The body type of every fallback response an operation declares: the * `default` response's, then each range response's in declaration order, * skipping entries that declare no body. Feeds `collectResponseBodyTypes`, * which every pass that walks an operation's type refs goes through (as it * goes through `collectResponseHeaders` for headers), so a model reached * only as the body of a `default` or `4XX` response is materialized, * assigned, renamed and validated like a primary response body. */ declare function collectFallbackResponseTypes(op: Operation): TypeRef[]; /** * Every type reference a webhook carries: its parameters' types, its * request body, the payload of every other media type it declares (each * `requestBodyContents` entry whose type is not `requestBody`'s own), and * — after its own — everything each of its `callbacks` carries, nested * callbacks included, since a `Callback` is a `Webhook` (#382). Every pass * that walks an operation's type refs (reachability, ref rewriting and * validation, the differ's direction index, inline-enum collection) walks a * webhook's through this, so a model reached only through a webhook or * callback payload or header is treated the way one reached through an * operation is, and a field added to `Webhook` later has one place to join. */ declare function collectWebhookTypeRefs(webhook: Webhook): TypeRef[]; /** * Every type reference an operation carries: its parameters' types in every * location (the query parameters the body owns included), its request body * and the body of every other request media type (`collectRequestBodyTypes`), * its primary response and every other success body, every error body, the * pagination iterator's item type and envelope fields, every response header * (`collectResponseHeaders`), every secondary, fallback and range body * (`collectResponseBodyTypes`), and — last — everything each of its * `callbacks` carries, through `collectWebhookTypeRefs`, nested callbacks * included (#382). The one list for a pass that reserves or * collects names across an operation's references — the enum names held * before the deferred schemas are named, the names a merge pass must mint * around, the names a webhook must step around — as `collectWebhookTypeRefs` * is for a webhook's, so a field added to `Operation` later has one place to * join and every reader gets the same list. When `successResponses` exists * the primary entry's `type` is the very reference `response` carries, so * that reference appears twice; a reader that only collects names is * unaffected. */ declare function collectOperationTypeRefs(op: Operation): TypeRef[]; /** * A header a response declares, typed like a parameter. `name` is kept exactly * as written in the spec (e.g. `Content-Disposition`); emitters apply their * own casing. Header names are case-insensitive (RFC 9110 §5.1), so one * response declares each header once: of two keys that differ in case * alone, the parser keeps the later (`foldHeaderName` in * `ir/parameter-key.ts` decides which keys are one header). */ interface ResponseHeader { name: string; /** * The header schema's type. The header's schema is resolved as a * parameter's is (see `Parameter.type`): the Header Object's `schema` * (resolved through `components/headers`) or, in its place, the schema of * the `content` entry read by the same media type rule. A header with * neither, a `text/plain` entry without a schema, or a map none of whose * media types is read — the last with a parser warning — is a string. */ type: TypeRef; required: boolean; /** The Header Object's own `description`; the schema's is never the header's. */ description?: string; /** * `true` when the Header Object says `deprecated: true`, or the schema * `type` is read from does — on its own keys, or on an `allOf` member of * it that declares no type and so only annotates it (`allOfWrapperLayer`; * #555), as a field reads the flag. Absent otherwise. */ deprecated?: boolean; /** * The header schema's `externalDocs`, when it declares a usable one — the * schema `type` is read from, whether the Header Object's `schema` or the * `content` entry's: its own, else the first `allOf` member's that * declares no type and so only annotates the schema (`allOfWrapperLayer`; * #605), so `allOf: [{ type: 'integer' }, { externalDocs }]` gives the * header the link `allOf: [{ type: 'integer' }], externalDocs` does, as it * gives a field, a parameter and the model built from the schema. A * Header Object has no `externalDocs` of its own. Absent otherwise. */ externalDocs?: ExternalDocs; } interface ErrorResponse { statusCode: number; type?: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** * Media types declared under `content`, in document order and as written. * `type` is by definition the JSON body (`application/json`, else the first * `+json` media type), so the list is present only when it says something * `type` does not: the error declares another media type, a JSON media type * other than plain `application/json` (`application/problem+json` alone, * `application/json; charset=utf-8`), or a JSON body `type` could not be * read from. An error that declares only `application/json` with a schema * keeps its shape. */ contentTypes?: string[]; /** * One entry per `contentTypes` entry, in the same order. The entry for the * media type `type` was read from carries the same TypeRef as `type`. * Present only when `contentTypes` is. */ contents?: ResponseContent[]; /** * The response's `description` as written in the document (e.g. "Not * found"). Present only when it has non-whitespace content; kept verbatim. */ description?: string; } /** * One entry of `Operation.successResponses`: a declared 2xx or 3xx response. * A 3xx entry's `type` is always `unknown`. A 2xx body that is itself an * inline enum is promoted to `spec.enums` as `Response`, and an array of * one as `Item`, the name an array body's items take; every entry of one * shape derives the same name, so a second body with other members is * qualified with its status code (`CheckPetKindResponse202`, * `CheckPetKindItem202`), while identical members share one enum. */ interface SuccessResponse { statusCode: number; type: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** * Media types declared under `content`, in document order and as written. * Present only when there is at least one. */ contentTypes?: string[]; /** * One entry per `contentTypes` entry, in the same order. The entry for the * media type `type` was read from carries that same TypeRef. Present only * when `contentTypes` is. */ contents?: ResponseContent[]; /** * The response's `description` as written in the document (e.g. "The pet, * with its owner."). Present only when it has non-whitespace content; kept * verbatim. */ description?: string; } /** * One media type a response declares under `content`, with the type its * schema resolves to. `contentType` is kept exactly as written in the spec, * parameters and all, so it can be sent back verbatim in an `Accept` header. */ interface ResponseContent { contentType: string; type: TypeRef; } /** * One media type a request body declares under `content`, with the type it * resolves to. `contentType` is kept exactly as written in the spec, * parameters and all, so it can be sent verbatim as a `Content-Type`. */ interface RequestBodyContent { contentType: string; type: TypeRef; } /** * A response body type other than `Operation.response`, with where it comes * from for diagnostics. */ interface ResponseBodyType { type: TypeRef; /** * The entry it belongs to: `contents.` for a secondary media * type, `defaultResponse` for the `default` response's body, * `rangeResponses.` (`rangeResponses.4XX`) for a range response's. */ source: string; } /** * Every response body type an operation declares besides `response`: the * bodies of its secondary media types (`collectAlternateResponseContents`, * fallback responses' included), then the fallback bodies of its `default` * and range responses (`collectFallbackResponseTypes`), and any body a later * field adds. The primary type of each alternate 2xx and error entry is not * included — walkers reach those through `successResponses[].type` and * `errors[].type` where they do today. Every pass that walks an operation's * type refs (reachability, model assignment, ref rewriting and validation, * direction, compat filtering, enum collection) calls this beside * `collectResponseHeaders`, so a new kind of body is reached everywhere by * extending this one function. */ declare function collectResponseBodyTypes(op: Operation): ResponseBodyType[]; /** * A request body type other than `Operation.requestBody`, with where it * comes from for diagnostics. */ interface RequestBodyType { type: TypeRef; /** The entry it belongs to: `requestBodyContents.`. */ source: string; } /** * Every request body type an operation declares besides `requestBody`: the * bodies of its other media types (`collectAlternateRequestBodyContents`). * The request-side twin of `collectResponseBodyTypes`: every pass that walks * an operation's type refs (reachability, model assignment, ref rewriting * and validation, direction, compat filtering, enum collection) calls this * beside it, so a body declared only for a secondary media type is reached * everywhere `requestBody` is, and a new kind of request body is reached * everywhere by extending this one function. */ declare function collectRequestBodyTypes(op: Operation): RequestBodyType[]; /** * Every request content entry whose type is reachable only through it: the * entries of `requestBodyContents` other than the one `requestBody` was read * from, which shares that very TypeRef and is already reached through * `requestBody`. Every entry when no media type was read as `requestBody`. * Feeds `collectRequestBodyTypes`, which the walkers call. */ declare function collectAlternateRequestBodyContents(op: Operation): RequestBodyContent[]; /** * The `default` response: the body and headers for every status the * operation does not list. See `Operation.defaultResponse`. */ interface DefaultResponse { /** * Response body type: the `application/json` body, else the first `+json` * one; absent when the response declares neither. */ type?: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** * Media types declared under `content`, in document order and as written, * exactly as on `SuccessResponse`. Present only when there is at least one. */ contentTypes?: string[]; /** * One entry per `contentTypes` entry, in the same order. The entry for the * media type `type` was read from carries that same TypeRef. Present only * when `contentTypes` is. */ contents?: ResponseContent[]; /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */ description?: string; } /** A Responses Object range key, uppercase as OpenAPI writes it (`4xx` is read as `4XX`). */ type StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX'; /** * A range response: the body and headers for every status in one hundred * (`4XX` → 400–499) that the operation does not list explicitly. See * `Operation.rangeResponses`. */ interface RangeResponse { range: StatusRange; /** * Response body type: the `application/json` body, else the first `+json` * one; absent when the response declares neither. */ type?: TypeRef; /** Declared response headers. Present only when the spec declares at least one. */ headers?: ResponseHeader[]; /** Media types declared under `content`, as on `DefaultResponse`. */ contentTypes?: string[]; /** One entry per `contentTypes` entry, as on `DefaultResponse`. */ contents?: ResponseContent[]; /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */ description?: string; } //#endregion //#region src/ir/operation-hints.d.ts /** Per-operation override keyed by "METHOD /path" (e.g. "POST /auth/token"). */ interface OperationHint { /** Override the algorithm-derived method name. */ name?: string; /** Remount this operation to a different service/namespace (PascalCase). */ mountOn?: string; /** Split a union-body operation into N typed wrapper methods. */ split?: SplitHint[]; /** Inject constant body defaults (e.g. { grant_type: 'password' }). */ defaults?: Record; /** Fields the SDK reads from client config at runtime (e.g. ['client_id']). */ inferFromClient?: string[]; /** * Marks this operation as a URL builder rather than a real HTTP call. Emitters * should generate a method that returns the constructed URL (typically as a * string) without performing any I/O. Used for OAuth-style redirect endpoints * such as /auth/authorize and /accounts/sessions/logout. */ urlBuilder?: boolean; /** * Explicit pagination for this operation, applied by the parser (through * `ParseOptions.operationHints`) rather than by `resolveOperations`. Same * shape as the spec's `x-pagination` Operation Object extension; a field set * here wins over the extension, which wins over name-based detection. */ pagination?: PaginationHint; } /** * Explicit pagination for one operation — the object a spec can carry as * `x-pagination` on an Operation Object and that `OperationHint.pagination` * accepts from config. Every field is optional and layers over the * lower-precedence sources (config hint > `x-pagination` > detection), so * `{ strategy: 'page' }` alone keeps the detected `param` and `limitParam`. * * `strategy: 'none'` turns pagination off for the operation; a list envelope * is then kept as a plain response model rather than unwrapped. Any other * strategy needs a `param`, from some source, that names one of the * operation's query parameters. An override that fails validation — unknown * strategy, missing or undeclared parameter, one parameter as both `param` * and `limitParam`, a `pageStart` under a strategy other than `page`, a * `dataPath` that does not reach an array, an `endOfIteration` whose path * does not resolve in the primary response to a field of its kind's type, * malformed field — is reported with an `[oagen] Warning:` and ignored, * leaving the detected metadata as is. */ interface PaginationHint { strategy?: PaginationStrategy | 'none'; /** Query parameter that selects the page (cursor, offset, or page number). */ param?: string; /** Query parameter that sets the page size; not the one `param` names. */ limitParam?: string; /** * First page number the API expects (`page` strategy only; set under * another strategy, it makes the override unusable). Defaults to the page * parameter's integer `default`, else its `minimum`, else 1. */ pageStart?: number; /** * Dotted path to the data array inside the response. Resolved against the * response, so the array's element type — not the wrapper — becomes * `itemType`. */ dataPath?: string; /** * Response field that ends the iteration. Its `path` must resolve in the * primary response to a field whose type fits its `kind` — a boolean for * `hasMore`, an integer or number for `totalPages` and `totalCount` — or * the override is unusable. */ endOfIteration?: PaginationEndOfIteration; } interface SplitHint { /** Wrapper method name (snake_case). */ name: string; /** The discriminated union variant model name (e.g. 'PasswordSessionAuthenticateRequest'). */ targetVariant: string; /** Constant body fields injected by the wrapper. */ defaults?: Record; /** Fields the SDK reads from client config at runtime. */ inferFromClient?: string[]; /** Only these body fields are exposed as method params. If omitted, all non-default/non-inferred fields are exposed. */ exposedParams?: string[]; /** * Subset of exposedParams that should be emitted as optional even when the * variant model would otherwise mark them required (or when the variant has * no addressable model, as happens for inline oneOf branches). */ optionalParams?: string[]; } interface ResolvedOperation { /** The original IR operation (preserves description, params, types, etc.). */ operation: Operation; /** The original IR service that owns this operation. */ service: Service; /** Resolved snake_case method name (emitters convert to their convention). */ methodName: string; /** Resolved target service/namespace (PascalCase). */ mountOn: string; /** For split operations: one wrapper per union variant. */ wrappers?: ResolvedWrapper[]; /** Constant defaults injected into query/body at runtime (from operation-level hint). */ defaults: Record; /** Fields the SDK reads from client config at runtime (from operation-level hint). */ inferFromClient: string[]; /** Marks this operation as a URL builder; emitters should not generate an HTTP call. */ urlBuilder: boolean; } interface ResolvedWrapper { /** Wrapper method name (snake_case). */ name: string; /** The discriminated union variant model name. */ targetVariant: string; /** Constant body defaults injected by the wrapper. */ defaults: Record; /** Fields read from client config at runtime. */ inferFromClient: string[]; /** Body fields exposed as method params. */ exposedParams: string[]; /** Optional body fields (not required in the variant). */ optionalParams: string[]; /** Response model name (if any). */ responseModelName: string | null; } /** * Derive a snake_case method name from an operation's HTTP method and path. * * Rules: * 1. Strip path-param segments (`{id}`, `{slug}`, etc.); a custom method * written after a colon (`{id}:verify`, `factors:enroll`) is read as its * segment followed by the verb (see pathSegments), so it is named like * `{id}/verify` and `factors/enroll`, and a segment kept whole for its * several colons is a literal (see isParameterSegment), even one braces * open and close (`{id}:a:b{ext}`) * 2. If the terminal segment is an action verb, use it as the verb * 3. Otherwise, use the CRUD verb for the HTTP method * 4. For GET on a collection (no trailing {id}), use "list"; with {id}, use "get" * 5. For POST on a resource path, if only one path param, use "create" singular * 6. Singularize the resource noun for single-resource operations */ declare function deriveMethodName(op: Operation, _service: Service): string; /** * Resolve a service name to its mount target. * * Rule keys are either exact service names or trailing-`*` prefix patterns * (e.g. `UserManagement*`). Precedence: * * 1. An exact key always wins. * 2. Otherwise the wildcard with the longest prefix wins, so * `UserManagementOrganizationMembership*` beats `UserManagement*`. * * Matching is plain string comparison (`startsWith`) — `*` is only recognised * as the final character and no regex is ever built from rule keys. * * @param name - The IR service name to resolve. * @param mounts - Exact-name or trailing-`*` pattern → target service mappings. * @returns The mount target, or `name` unchanged when no rule matches. */ declare function resolveMountTarget(name: string, mounts: Record): string; /** * Where a method name comes from when no `name` hint sets it: `path` derives * it from the HTTP method and path (`deriveMethodName`); `operationId` takes * the operation's own name when the document declares an `operationId` * (`Operation.name`, as the parser spelled it, in snake_case — see * {@link snakeCaseOperationName} for where the word boundaries are read) and * derives it from the path only for a path-named operation. */ type OperationNaming = 'path' | 'operationId'; /** * The settings {@link resolveOperations} resolves a spec's operations with — * the config's `operationHints`, `mountRules` and `operationNaming` — which * together decide the class (`mountOn`) and the method (`methodName`) that * `generate` writes each operation as. Every command that reads the SDK * `generate` writes resolves with the same settings: `compat-extract` matches * the SDK's callables by the names they resolve to, and `verify`'s compat * scope and staleness check read the classes and methods they resolve to * (see `specDerivedNames`, `specDerivedMethodPaths` and `detectStaleSymbols` * in `compat`). Under `mountRules: { Pets: 'Animals' }` and * `operationHints: { 'GET /pets': { name: 'list_all' } }`, `GET /pets` and * `GET /pets/{id}` tagged `Pets` resolve to `Animals.list_all` and * `Animals.get_pet`; with no settings, to `Pets.list_pets` and `Pets.get_pet`. */ interface OperationResolution { operationHints?: Record; mountRules?: Record; operationNaming?: OperationNaming; } /** * Resolve all operations in the spec, applying hints and mount rules. * * @param spec - The parsed API spec * @param hints - Per-operation overrides keyed by "METHOD /path" * @param mountRules - Service name → target service mappings; keys may be * exact names or trailing-`*` prefix patterns (see {@link resolveMountTarget}) * @param operationNaming - Where an unhinted method name comes from; `path` * unless the consumer asks for `operationId` (see {@link OperationNaming}) * @returns Resolved operations ready for emitter consumption */ declare function resolveOperations(spec: ApiSpec, hints?: Record, mountRules?: Record, operationNaming?: OperationNaming): ResolvedOperation[]; /** One pair of distinct paths that resolved to the same `mountOn.methodName`. */ interface ResolvedMethodCollision { /** The shared `Service.method_name` key both paths resolved to. */ key: string; first: { httpMethod: string; path: string; }; second: { httpMethod: string; path: string; }; } /** * Find every pair of distinct paths that resolve to the same SDK method name. * * Emitters already refuse to generate on a collision, but they only run inside * the per-language build matrix — so a spec addition that collides fails every * matrix job minutes in, with no cheap way to catch it first. Surfacing the same * check from `oagen resolve` turns that into a seconds-long precheck. * * Returns every collision rather than throwing on the first, so a spec that * introduces several is fixed in one pass instead of one CI round-trip each. * * Callers that generate a subset of services must filter to the operations they * will actually emit before calling this: a collision between two out-of-scope * paths is not that run's problem. */ declare function findResolvedMethodCollisions(resolved: ResolvedOperation[]): ResolvedMethodCollision[]; //#endregion export { TypeParam as $, ApiEnum as $t, ModelRef as A, mergePolicy as An, LoggingPolicy as At, RangeResponse as B, AdditiveChangeCategory as Bt, Extensions as C, CompatVisibility as Cn, walkTypeRef as Ct, LiteralType as D, ALL_LANGUAGE_IDS as Dn, ErrorPolicy as Dt, HttpMethod as E, apiSurfaceToSnapshot as En, DeepPartial as Et, PaginationStrategy as F, TelemetryPolicy as Ft, ResponseHeader as G, CompatConfig as Gt, RequestBodyType as H, CompatApproval as Ht, Parameter as I, TimeoutPolicy as It, ServerEntry as J, SoftRiskChangeCategory as Jt, SecurityRequirement as K, CompatFailLevel as Kt, ParameterGroup as L, UserAgentPolicy as Lt, Operation as M, RequestGuardPolicy as Mt, PaginationEndOfIteration as N, RetryPolicy as Nt, MapType as O, CompatPolicyHints as On, IdempotencyPolicy as Ot, PaginationMeta as P, SdkBehavior as Pt, SuccessResponse as Q, ApiClass as Qt, ParameterGroupVariant as R, defaultSdkBehavior as Rt, ErrorResponse as S, CompatTypeRef as Sn, validateModelHints as St, Field as T, ParameterSensitivity as Tn, BackoffStrategy as Tt, ResponseBodyType as U, CompatChangeCategory as Ut, RequestBodyContent as V, BreakingChangeCategory as Vt, ResponseContent as W, CompatChangeSeverity as Wt, Service as X, severityMeetsThreshold as Xt, ServerVariable as Y, defaultSeverityForCategory as Yt, StatusRange as Z, Addition as Zt, Constraints as _, CompatSnapshot as _n, collectResponseHeaders as _t, ResolvedMethodCollision as a, ApiSurface as an, assignModelsToServices as at, EnumRef as b, CompatSymbol as bn, renameModelRefs as bt, SplitHint as c, Extractor as cn, collectEnumRefs as ct, resolveMountTarget as d, OverlayLookup as dn, collectModelRefs as dt, ApiField as en, TypeRef as et, resolveOperations as f, Violation as fn, collectModelTypeRefs as ft, Callback as g, CompatPassingStyle as gn, collectResponseBodyTypes as gt, AuthScheme as h, CompatParameter as hn, collectRequestBodyTypes as ht, PaginationHint as i, ApiProperty as in, assertNever as it, NullableType as j, PaginationPolicy as jt, Model as k, getDefaultPolicy as kn, LogEvent as kt, deriveMethodName as l, LanguageHints as ln, collectFallbackResponseTypes as lt, ArrayType as m, ViolationSeverity as mn, collectRequestBodyModels as mt, OperationNaming as n, ApiMethod as nn, Webhook as nt, ResolvedOperation as o, ApiTypeAlias as on, callbackContext as ot, ApiSpec as p, ViolationCategory as pn, collectOperationTypeRefs as pt, SecurityRequirementSet as q, CompatProvenance as qt, OperationResolution as r, ApiParam as rn, WebhookResponse as rt, ResolvedWrapper as s, DiffResult as sn, collectAlternateRequestBodyContents as st, OperationHint as t, ApiInterface as tn, UnionType as tt, findResolvedMethodCollisions as u, MethodOverlay as un, collectFieldDependencies as ut, DefaultResponse as v, CompatSourceKind as vn, collectWebhookTypeRefs as vt, ExternalDocs as w, LanguageId as wn, AiAgentEnvVar as wt, EnumValue as x, CompatSymbolKind as xn, typeRefConstraints as xt, Enum as y, CompatStability as yn, mapTypeRef as yt, PrimitiveType as z, mergeSdkBehavior as zt }; //# sourceMappingURL=operation-hints-DzxFffcr.d.mts.map