Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
changeKind: feature
packages:
- "@typespec/openapi3"
---

Add `component-name-strategy` to control namespace qualification and segment separators for OpenAPI schema and reusable parameter keys. Existing defaults are unchanged.

```yaml
options:
"@typespec/openapi3":
component-name-strategy: name-only
```

Use `name-only` to omit namespaces, or configure `{ kind: fqn, separator: "_" }` to change segment separators. Characters within identifiers and friendly names remain unchanged. Collisions after namespace changes are errors.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: internal
packages:
- "@typespec/openapi"
---

Share duplicate schema and parameter component key diagnostics while preserving existing parameter error messages.
14 changes: 4 additions & 10 deletions packages/openapi/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,19 @@ export function getOpenAPITypeName(
* @param type Type with the name to check
* @param name Name to check
* @param existing Existing map of name
* @param messageId - Whether to report a duplicate type name or parameter key.
*/
export function checkDuplicateTypeName(
program: Program,
type: Type,
name: string,
existing: Record<string, unknown> | undefined,
messageId: "default" | "parameter" = "default",
) {
if (existing && existing[name]) {
reportDiagnostic(program, {
code: "duplicate-type-name",
messageId,
format: {
value: name,
},
Expand All @@ -124,16 +127,7 @@ export function getParameterKey(
key += `.${property.name}`;
}

if (existingParams[key]) {
reportDiagnostic(program, {
code: "duplicate-type-name",
messageId: "parameter",
format: {
value: key,
},
target: property,
});
}
checkDuplicateTypeName(program, property, key, existingParams, "parameter");

return key;
}
Expand Down
19 changes: 19 additions & 0 deletions packages/openapi3/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,25 @@ See https://github.com/OAI/OpenAPI-Specification/discussions/4622 for discussion
| `kind` | `"parent-container" \| "fqn" \| "explicit-only"` | `"parent-container"` | Determines how to generate operation IDs when `@operationId` is not used.<br />Avaliable options are:<br /> - `parent-container`: Uses the parent namespace and operation name to generate the ID.<br /> - `fqn`: Uses the fully qualified name of the operation to generate the ID.<br /> - `explicit-only`: Only use explicitly defined operation IDs. |
| `separator` | `string` | | Separator used to join segment in the operation name. |

### `component-name-strategy`

**Type:** `"fqn" | "name-only" | object { kind, separator }`

**Options:**

- `"fqn" | "name-only"` (default: `"fqn"`)

Naming strategy for schema and reusable parameter component keys.
`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.
Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged.

- `object { kind, separator }`

| Name | Type | Default | Description |
| ----------- | ---------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `kind` | `"fqn" \| "name-only"` | `"fqn"` | Naming strategy for schema and reusable parameter component keys.<br />`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.<br />Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged. |
| `separator` | `string` | `"."` | Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names. |

### `enum-strategy`

**Type:** `"default" | "annotated"`
Expand Down
31 changes: 31 additions & 0 deletions packages/openapi3/src/component-naming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { Program, Type, TypeNameOptions } from "@typespec/compiler";
import { getFriendlyName, getTypeName, isStdNamespace } from "@typespec/compiler";
import type { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";

export function getComponentTypeName(
program: Program,
type: Type,
typeNameOptions: TypeNameOptions,
options: ResolvedOpenAPI3EmitterOptions,
): string {
const strategy = options.componentNameStrategy;
const friendlyName = getFriendlyName(program, type);
const name = friendlyName ?? getTypeName(type, { ...typeNameOptions, nameOnly: true });
let namespace = "namespace" in type ? type.namespace : undefined;
if (
friendlyName !== undefined ||
strategy?.kind === "name-only" ||
("expression" in type && type.expression) ||
(namespace && isStdNamespace(namespace))
) {
return name;
}

const segments = [name];
while (namespace && namespace.name !== "") {
if (typeNameOptions.namespaceFilter && !typeNameOptions.namespaceFilter(namespace)) break;
segments.unshift(namespace.name);
namespace = namespace.namespace;
}
return segments.join(strategy?.separator ?? ".");
}
49 changes: 49 additions & 0 deletions packages/openapi3/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type OpenAPIVersion = "3.0.0" | "3.1.0" | "3.2.0";
export type ExperimentalParameterExamplesStrategy = "data" | "serialized";
/** Enum representation: a single `enum` schema or annotated `const` alternatives for OpenAPI 3.1 and later. */
export type EnumStrategy = "default" | "annotated";
/** Namespace qualification for schema and reusable parameter component keys. */
export type ComponentNameStrategy = "fqn" | "name-only";
/** User-supplied emitter configuration; omitted settings are normalized by `resolveOptions`. */
export interface OpenAPI3EmitterOptions {
/**
Expand Down Expand Up @@ -116,6 +118,22 @@ export interface OpenAPI3EmitterOptions {
separator?: string;
};

/**
* Naming strategy for schema and reusable parameter component keys.
* `fqn` preserves current service-relative namespace qualification; `name-only` omits namespaces.
* Friendly names override namespace qualification. Separators join namespace and parameter-property
* segments, not punctuation within identifiers or friendly names.
* @default fqn
*/
"component-name-strategy"?:
| ComponentNameStrategy
| {
/** Namespace qualification strategy. */
kind: ComponentNameStrategy;
/** Separator between namespace and parameter-property segments; defaults to `"."`. May be empty. */
separator?: string;
};

/**
* How to emit TypeSpec enums.
*
Expand Down Expand Up @@ -150,6 +168,17 @@ const operationIdStrategySchema = {
].join("\n"),
} as const;

const componentNameStrategySchema = {
type: "string",
enum: ["fqn", "name-only"],
default: "fqn",
description: [
"Naming strategy for schema and reusable parameter component keys.",
"`fqn` preserves service-relative namespace qualification; `name-only` omits namespaces.",
"Friendly names override namespace qualification. Operation IDs and HTTP names are unchanged.",
].join("\n"),
} as const;

const EmitterOptionsSchema: JSONSchemaType<OpenAPI3EmitterOptions> = {
type: "object",
additionalProperties: false,
Expand Down Expand Up @@ -293,6 +322,26 @@ const EmitterOptionsSchema: JSONSchemaType<OpenAPI3EmitterOptions> = {
},
],
} as any,
"component-name-strategy": {
oneOf: [
componentNameStrategySchema,
{
type: "object",
additionalProperties: false,
properties: {
kind: componentNameStrategySchema,
separator: {
type: "string",
nullable: true,
default: ".",
description:
"Separator between namespace and parameter-property segments. May be empty. Does not replace punctuation within identifiers or friendly names.",
},
Comment on lines +333 to +339
},
required: ["kind"],
},
],
} as any,
"enum-strategy": {
type: "string",
enum: ["default", "annotated"],
Expand Down
34 changes: 28 additions & 6 deletions packages/openapi3/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,21 +77,23 @@ import {
} from "@typespec/http";
import { getStreamMetadata } from "@typespec/http/experimental";
import {
checkDuplicateTypeName,
getExtensions,
getExternalDocs,
getOpenAPITypeName,
getParameterKey,
getTagsMetadata,
isReadonlyProperty,
shouldInline,
} from "@typespec/openapi";
import { stringify } from "yaml";
import { getComponentTypeName } from "./component-naming.js";
import { getRef } from "./decorators.js";
import type { OperationExamples } from "./examples.js";
import { getExampleOrExamples, resolveOperationExamples } from "./examples.js";
import type { JsonSchemaModule } from "./json-schema.js";
import { resolveJsonSchemaModule } from "./json-schema.js";
import type {
ComponentNameStrategy,
EnumStrategy,
FileType,
OpenAPI3EmitterOptions,
Expand Down Expand Up @@ -247,6 +249,7 @@ export function resolveOptions(
}

const specDir = openapiVersions.length > 1 ? "{openapi-version}" : "";
const componentNameStrategy = resolvedOptions["component-name-strategy"] ?? "fqn";
return {
fileTypes,
newLine: resolvedOptions["new-line"],
Expand All @@ -258,6 +261,14 @@ export function resolveOptions(
sealObjectSchemas: resolvedOptions["seal-object-schemas"],
parameterExamplesStrategy: resolvedOptions["experimental-parameter-examples"],
operationIdStrategy: resolveOperationIdStrategy(resolvedOptions["operation-id-strategy"]),
componentNameStrategy: {
kind:
typeof componentNameStrategy === "string"
? componentNameStrategy
: componentNameStrategy.kind,
separator:
typeof componentNameStrategy === "string" ? "." : (componentNameStrategy.separator ?? "."),
},
enumStrategy,
};
}
Expand Down Expand Up @@ -291,6 +302,13 @@ function resolveOperationIdDefaultStrategySeparator(strategy: OperationIdStrateg

/** Normalized emitter settings returned by `resolveOptions`, before document-specific path interpolation. */
export interface ResolvedOpenAPI3EmitterOptions {
/** Component qualification; defaults to service-relative `"fqn"` with `"."` separators. */
componentNameStrategy?: {
/** Whether to include service-relative namespaces. */
kind: ComponentNameStrategy;
/** Separator between namespace and parameter-property segments. */
separator: string;
};
Comment on lines +305 to +311
/** Formats requested for each document; inferred from the output extension or defaulted to YAML when absent. */
fileTypes: FileType[];
/** Resolved output path template; includes an OpenAPI-version directory when multiple specification versions are requested. */
Expand Down Expand Up @@ -1421,7 +1439,7 @@ function createOAPIEmitter(

const name =
"name" in body.type && body.type.name !== ""
? getOpenAPITypeName(program, body.type, typeNameOptions)
? getComponentTypeName(program, body.type, typeNameOptions, options)
: undefined;
if (name) {
root.components!.schemas![name] = schema;
Expand Down Expand Up @@ -1806,14 +1824,18 @@ function createOAPIEmitter(

function emitParameters() {
for (const [property, param] of params) {
const key = getParameterKey(
const parent = property.model!;
const name = getComponentTypeName(program, parent, typeNameOptions, options);
const separator = options.componentNameStrategy?.separator ?? ".";
const key = parent.properties.size > 1 ? name + separator + property.name : name;
const validKey = ensureValidComponentFixedFieldKey(program, property, key);
checkDuplicateTypeName(
program,
property,
param,
validKey,
root.components!.parameters!,
typeNameOptions,
"parameter",
);
const validKey = ensureValidComponentFixedFieldKey(program, property, key);
root.components!.parameters![validKey] = { ...param };
for (const key of Object.keys(param)) {
delete param[key];
Expand Down
41 changes: 34 additions & 7 deletions packages/openapi3/src/schema-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ import {
checkDuplicateTypeName,
getExtensions,
getExternalDocs,
getOpenAPITypeName,
isReadonlyProperty,
shouldInline,
} from "@typespec/openapi";
import { attachExtensions } from "./attach-extensions.js";
import { getComponentTypeName } from "./component-naming.js";
import { getOneOf, getRef } from "./decorators.js";
import type { JsonSchemaModule } from "./json-schema.js";
import type { OpenAPI3EmitterOptions } from "./lib.js";
Expand Down Expand Up @@ -258,7 +258,7 @@ export class OpenAPI3SchemaEmitterBase<
);
}

const baseName = getOpenAPITypeName(program, model, this.#typeNameOptions());
const baseName = getComponentTypeName(program, model, this.#typeNameOptions(), this._options);
const isMultipart = this.getContentType().startsWith("multipart/");
const name = isMultipart ? baseName + "MultiPart" : baseName;

Expand Down Expand Up @@ -308,7 +308,14 @@ export class OpenAPI3SchemaEmitterBase<
}

modelInstantiation(model: Model, name: string | undefined): EmitterOutput<Record<string, any>> {
name = name ?? getOpenAPITypeName(this.emitter.getProgram(), model, this.#typeNameOptions());
name =
name ??
getComponentTypeName(
this.emitter.getProgram(),
model,
this.#typeNameOptions(),
this._options,
);
if (!name) {
return this.modelLiteral(model);
}
Expand All @@ -330,7 +337,12 @@ export class OpenAPI3SchemaEmitterBase<
items: this.emitter.emitTypeReference(elementType),
});

const name = getOpenAPITypeName(this.emitter.getProgram(), array, this.#typeNameOptions());
const name = getComponentTypeName(
this.emitter.getProgram(),
array,
this.#typeNameOptions(),
this._options,
);
return this.#createDeclaration(array, name, this.applyConstraints(array, schema as any));
}

Expand Down Expand Up @@ -542,7 +554,12 @@ export class OpenAPI3SchemaEmitterBase<
}

enumDeclaration(en: Enum, name: string): EmitterOutput<object> {
const baseName = getOpenAPITypeName(this.emitter.getProgram(), en, this.#typeNameOptions());
const baseName = getComponentTypeName(
this.emitter.getProgram(),
en,
this.#typeNameOptions(),
this._options,
);

return this.#createDeclaration(en, baseName, new ObjectBuilder(this.enumSchema(en)));
}
Expand Down Expand Up @@ -570,7 +587,12 @@ export class OpenAPI3SchemaEmitterBase<

unionDeclaration(union: Union, name: string): EmitterOutput<object> {
const schema = this.unionSchema(union);
const baseName = getOpenAPITypeName(this.emitter.getProgram(), union, this.#typeNameOptions());
const baseName = getComponentTypeName(
this.emitter.getProgram(),
union,
this.#typeNameOptions(),
this._options,
);
return this.#createDeclaration(union, baseName, schema);
}

Expand Down Expand Up @@ -835,7 +857,12 @@ export class OpenAPI3SchemaEmitterBase<
const program = this.emitter.getProgram();
const shouldInline = isStdType(program, scalar) || isTypeRefType(program, scalar);
const schema = this.#getSchemaForScalar(scalar);
const baseName = getOpenAPITypeName(this.emitter.getProgram(), scalar, this.#typeNameOptions());
const baseName = getComponentTypeName(
this.emitter.getProgram(),
scalar,
this.#typeNameOptions(),
this._options,
);

// Built-in and compile-time scalars do not need declarations.
return shouldInline
Expand Down
Loading
Loading