Skip to content

Commit d20dd31

Browse files
committed
fix(openapi3): warn about a missing server variable default instead of picking one
Keep the empty default when a server variable with enum values has no default, and report missing-server-variable-default only for OpenAPI 3.1.0 and later, which require the default to be one of the enum values.
1 parent 207198d commit d20dd31

5 files changed

Lines changed: 44 additions & 121 deletions

File tree

‎.chronus/changes/fix-openapi3-server-variable-enum-default-2026-9-19-11-21-11.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ packages:
44
- "@typespec/openapi3"
55
---
66

7-
Server variables that have an `enum` but no default now use the first `enum` value as their `default` instead of an empty string, since OpenAPI 3.1 and later require the default to be one of the `enum` values. A server variable typed as the service's versions enum uses the version of each emitted document instead. A new `missing-server-variable-default` warning is reported when that first value is used for a variable with more than one possible value.
7+
Report a new `missing-server-variable-default` warning when a server variable that has an `enum` has no default and the document is emitted for OpenAPI 3.1.0 or later, since those versions require the default to be one of the `enum` values. The emitted `default` stays an empty string.

‎packages/openapi3/src/diagnostics/missing-server-variable-default.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
This diagnostic is issued when a variable in the `@server` decorator can take more than one value (an enum or a union of string literals) but has no default.
2-
OpenAPI requires the `default` of a server variable to be one of its `enum` values, so the emitter uses the first value. That value might not be the one you intended.
1+
This diagnostic is issued when a variable in the `@server` decorator has a fixed set of values (an enum, a union of string literals or a string literal) but no default, and the document is emitted for OpenAPI 3.1.0 or later.
2+
Those versions require the `default` of a server variable to be one of its `enum` values. The emitter does not pick one for you, so the variable keeps an empty `default` and the document is not valid.
33

44
To fix this issue, set a default on the server parameter.
55

66
### Example
77

88
```typespec
99
@server("https://{region}.example.com", "Regional endpoint", {
10-
region: "westus" | "eastus", // No default, so "westus" is used
10+
region: "westus" | "eastus", // No default
1111
})
1212
```
1313

14-
Set a default to choose the value:
14+
Set a default:
1515

1616
```typespec
1717
@server("https://{region}.example.com", "Regional endpoint", {

‎packages/openapi3/src/lib.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ export const $lib = createTypeSpecLibrary({
341341
severity: "warning",
342342
docs: fileRef.fromPackageRoot("src/diagnostics/missing-server-variable-default.md"),
343343
messages: {
344-
default: paramMessage`Server variable '${"propName"}' has no default, so '${"value"}', the first of its values, is used. Set a default on the parameter to choose a different one.`,
344+
default: paramMessage`Server variable '${"propName"}' has no default, but OpenAPI ${"openapiVersion"} requires its default to be one of its enum values. Set a default on the parameter.`,
345345
},
346346
},
347347
"invalid-format": {

‎packages/openapi3/src/openapi.ts‎

Lines changed: 13 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,6 @@ import {
137137
isBytesKeptRaw,
138138
isSharedHttpOperation,
139139
} from "./util.js";
140-
import type { VersioningModule } from "./versioning-module.js";
141140
import { resolveVersioningModule } from "./versioning-module.js";
142141
import type { VisibilityUsageTracker } from "./visibility-usage.js";
143142
import { resolveVisibilityUsage } from "./visibility-usage.js";
@@ -348,7 +347,6 @@ function createOAPIEmitter(
348347
let visibilityUsage: VisibilityUsageTracker;
349348
let sseModule: SSEModule | undefined;
350349
let jsonSchemaModule: JsonSchemaModule | undefined;
351-
let versioningModule: VersioningModule | undefined;
352350

353351
// Map model properties that represent shared parameters to their parameter
354352
// definition that will go in #/components/parameters. Inlined parameters do not go in
@@ -362,13 +360,10 @@ function createOAPIEmitter(
362360
// De-dupe the per-endpoint tags that will be added into the #/tags
363361
let tagsUsedInOperations: Set<string>;
364362

365-
// Values already warned about for a server parameter with no default, keyed by its declaration.
363+
// Server parameters already warned about for a missing default, keyed by their declaration.
366364
// Servers are resolved once per document and each version of a versioned service gets its own
367365
// copy of the parameter, so without this the same warning would be reported for every version.
368-
const serverVariablesWarnedForDefault = new Map<
369-
ModelProperty["node"] | ModelProperty,
370-
Set<string>
371-
>();
366+
const serverVariablesWarnedForDefault = new Set<ModelProperty["node"] | ModelProperty>();
372367

373368
const typeNameOptions: TypeNameOptions = {
374369
// shorten type names by removing TypeSpec and service namespace
@@ -510,7 +505,7 @@ function createOAPIEmitter(
510505

511506
const servers = getServers(program, service.type);
512507
if (servers) {
513-
root.servers = resolveServers(servers, version);
508+
root.servers = resolveServers(servers);
514509
}
515510

516511
attachExtensions(program, service.type, root);
@@ -557,34 +552,22 @@ function createOAPIEmitter(
557552
return isValid;
558553
}
559554

560-
/** Whether `type` is the enum passed to `@versioned` on the current service. */
561-
function isServiceVersionsEnum(type: Type): boolean {
562-
const versionMap = versioningModule?.getVersion(program, currentService.type);
563-
return versionMap?.getVersions().some((v) => v.enumMember.enum === type) ?? false;
564-
}
565-
566-
function reportMissingServerVariableDefault(prop: ModelProperty, value: string) {
567-
// Template instances share a declaration but can have different values, so only skip a
568-
// warning that was already reported for the same declaration and value.
555+
function reportMissingServerVariableDefault(prop: ModelProperty) {
569556
const key = prop.node ?? prop;
570-
let warnedValues = serverVariablesWarnedForDefault.get(key);
571-
if (warnedValues === undefined) {
572-
warnedValues = new Set();
573-
serverVariablesWarnedForDefault.set(key, warnedValues);
574-
} else if (warnedValues.has(value)) {
557+
if (serverVariablesWarnedForDefault.has(key)) {
575558
return;
576559
}
577-
warnedValues.add(value);
560+
serverVariablesWarnedForDefault.add(key);
578561
diagnostics.add(
579562
createDiagnostic({
580563
code: "missing-server-variable-default",
581-
format: { propName: prop.name, value },
564+
format: { propName: prop.name, openapiVersion: specVersion },
582565
target: prop,
583566
}),
584567
);
585568
}
586569

587-
function resolveServers(servers: HttpServer[], version?: string): OpenAPI3Server[] {
570+
function resolveServers(servers: HttpServer[]): OpenAPI3Server[] {
588571
return servers.map((server) => {
589572
const variables: Record<string, OpenAPI3ServerVariable> = {};
590573
for (const [name, prop] of server.parameters) {
@@ -606,22 +589,10 @@ function createOAPIEmitter(
606589
} else if (prop.type.kind === "String") {
607590
variable.enum = [prop.type.value];
608591
}
609-
// OpenAPI requires `default` to be one of the `enum` values. Use the version being
610-
// emitted for the versions enum, and the first value otherwise.
611-
if (!prop.defaultValue && variable.enum?.length) {
612-
if (
613-
version !== undefined &&
614-
variable.enum.includes(version) &&
615-
isServiceVersionsEnum(prop.type)
616-
) {
617-
variable.default = version;
618-
} else {
619-
variable.default = variable.enum[0];
620-
// With more than one value the first one is only a guess, so tell the author.
621-
if (variable.enum.length > 1) {
622-
reportMissingServerVariableDefault(prop, variable.default);
623-
}
624-
}
592+
// OpenAPI 3.1 and later require `default` to be one of the `enum` values (3.0 only says
593+
// it should be). Picking one could choose the wrong value, so ask the author to set it.
594+
if (!prop.defaultValue && variable.enum?.length && specVersion !== "3.0.0") {
595+
reportMissingServerVariableDefault(prop);
625596
}
626597
attachExtensions(program, prop, variable);
627598
variables[name] = variable;
@@ -635,7 +606,7 @@ function createOAPIEmitter(
635606
}
636607

637608
async function getOpenAPI(): Promise<OpenAPI3ServiceRecord[]> {
638-
versioningModule = await resolveVersioningModule();
609+
const versioningModule = await resolveVersioningModule();
639610
const serviceRecords: OpenAPI3ServiceRecord[] = [];
640611
const services = listServices(program);
641612
if (services.length === 0) {

‎packages/openapi3/test/servers.test.ts‎

Lines changed: 25 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
import { expectDiagnostics } from "@typespec/compiler/testing";
22
import { deepStrictEqual } from "assert";
33
import { it } from "vitest";
4-
import {
5-
emitOpenApiWithDiagnostics,
6-
openApiForVersions,
7-
TesterWithVersioning,
8-
} from "./test-host.js";
4+
import { emitOpenApiWithDiagnostics, TesterWithVersioning } from "./test-host.js";
95
import { supportedVersions, worksFor } from "./works-for.js";
106

117
worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVersion }) => {
12-
const missingDefaultWarning = (name: string, value: string) => ({
13-
code: "@typespec/openapi3/missing-server-variable-default",
14-
severity: "warning" as const,
15-
message: `Server variable '${name}' has no default, so '${value}', the first of its values, is used. Set a default on the parameter to choose a different one.`,
16-
});
8+
// OpenAPI 3.0 only says that a server variable default should be one of its enum values.
9+
const missingDefaultWarnings = (name: string) =>
10+
specVersion === "3.0.0"
11+
? []
12+
: [
13+
{
14+
code: "@typespec/openapi3/missing-server-variable-default",
15+
severity: "warning" as const,
16+
message: `Server variable '${name}' has no default, but OpenAPI ${specVersion} requires its default to be one of its enum values. Set a default on the parameter.`,
17+
},
18+
];
1719

1820
it("set a basic server(url)", async () => {
1921
const res = await openApiFor(
@@ -99,32 +101,8 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
99101
`,
100102
{ "openapi-versions": [specVersion] },
101103
);
102-
expectDiagnostics(diagnostics, missingDefaultWarning("region", "westus"));
103-
deepStrictEqual(res.servers?.[0].variables?.region, {
104-
default: "westus",
105-
enum: ["westus", "eastus"],
106-
});
107-
});
108-
109-
it("keeps an explicit default for an enum whose members are encoded as strings", async () => {
110-
const res = await openApiFor(
111-
`
112-
@service(#{title: "My service"})
113-
@server("https://{region}.example.com", "Regional account endpoint", {region?: Region = Region.eastUs})
114-
namespace MyService {}
115-
116-
enum Region {
117-
@encodedName("application/json", "westus")
118-
westUs: 1,
119-
@encodedName("application/json", "eastus")
120-
eastUs: 2,
121-
}
122-
`,
123-
);
124-
deepStrictEqual(res.servers[0].variables.region, {
125-
default: "eastus",
126-
enum: ["westus", "eastus"],
127-
});
104+
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
105+
deepStrictEqual(res.servers?.[0].variables?.region?.enum, ["westus", "eastus"]);
128106
});
129107

130108
it("emit diagnostic when a numeric enum member is left unencoded", async () => {
@@ -260,13 +238,13 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
260238
`,
261239
{ "openapi-versions": [specVersion] },
262240
);
263-
expectDiagnostics(diagnostics, missingDefaultWarning("region", "westus"));
241+
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
264242
deepStrictEqual(res.servers, [
265243
{
266244
description: "Regional account endpoint",
267245
url: "https://{region}.example.com",
268246
variables: {
269-
region: { default: "westus", enum: ["westus", "eastus"] },
247+
region: { default: "", enum: ["westus", "eastus"] },
270248
},
271249
},
272250
]);
@@ -289,7 +267,7 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
289267
});
290268

291269
it("set a server with string literal", async () => {
292-
const res = await openApiFor(
270+
const [res, diagnostics] = await emitOpenApiWithDiagnostics(
293271
`
294272
enum Region { }
295273
@service(#{title: "My service"})
@@ -298,13 +276,15 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
298276
})
299277
namespace MyService {}
300278
`,
279+
{ "openapi-versions": [specVersion] },
301280
);
281+
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
302282
deepStrictEqual(res.servers, [
303283
{
304284
description: "Regional account endpoint",
305285
url: "https://{region}.example.com",
306286
variables: {
307-
region: { default: "westus", enum: ["westus"] },
287+
region: { default: "", enum: ["westus"] },
308288
},
309289
},
310290
]);
@@ -322,13 +302,13 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
322302
`,
323303
{ "openapi-versions": [specVersion] },
324304
);
325-
expectDiagnostics(diagnostics, missingDefaultWarning("region", "westus"));
305+
expectDiagnostics(diagnostics, missingDefaultWarnings("region"));
326306
deepStrictEqual(res.servers, [
327307
{
328308
description: "Regional account endpoint",
329309
url: "https://{region}.example.com",
330310
variables: {
331-
region: { default: "westus", enum: ["westus", "eastus"] },
311+
region: { default: "", enum: ["westus", "eastus"] },
332312
},
333313
},
334314
]);
@@ -349,44 +329,17 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
349329
});
350330
});
351331

352-
it("set a server with the versions enum to the version of each document", async () => {
353-
const documents = await openApiForVersions(
354-
`
355-
@versioned(Versions)
356-
@service(#{title: "My service"})
357-
@server("{endpoint}/{apiVersion}", "Versioned endpoint", {
358-
endpoint: url,
359-
apiVersion: Versions,
360-
})
361-
namespace MyService {
362-
enum Versions { v1: "2024-01-01", v2: "2025-01-01" }
363-
}
364-
`,
365-
["2024-01-01", "2025-01-01"],
366-
{ "openapi-versions": [specVersion] },
367-
);
368-
for (const [version, document] of Object.entries(documents)) {
369-
deepStrictEqual(document.servers?.[0].variables, {
370-
endpoint: { default: "" },
371-
apiVersion: { default: version, enum: ["2024-01-01", "2025-01-01"] },
372-
});
373-
}
374-
});
375-
376332
it("warns once for a server variable without a default in a versioned service", async () => {
377333
const [{ outputs }, diagnostics] = await TesterWithVersioning.compileAndDiagnose(
378334
`
379335
@versioned(Versions)
380336
@service(#{title: "My service"})
381-
@server("{endpoint}/{release}/{apiVersion}", "Versioned endpoint", {
337+
@server("{endpoint}/{apiVersion}", "Versioned endpoint", {
382338
endpoint: url,
383-
release: Release,
384339
apiVersion: Versions,
385340
})
386341
namespace MyService {
387342
enum Versions { v1: "2024-01-01", v2: "2025-01-01" }
388-
// Same values as Versions, but not the versions enum, so it keeps the first value.
389-
enum Release { previous: "2024-01-01", latest: "2025-01-01" }
390343
}
391344
`,
392345
{
@@ -400,13 +353,12 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version: specVers
400353
},
401354
},
402355
);
403-
expectDiagnostics(diagnostics, missingDefaultWarning("release", "2024-01-01"));
356+
expectDiagnostics(diagnostics, missingDefaultWarnings("apiVersion"));
404357
for (const version of ["2024-01-01", "2025-01-01"]) {
405358
const document = JSON.parse(outputs[`${version}.openapi.json`]);
406359
deepStrictEqual(document.servers[0].variables, {
407360
endpoint: { default: "" },
408-
release: { default: "2024-01-01", enum: ["2024-01-01", "2025-01-01"] },
409-
apiVersion: { default: version, enum: ["2024-01-01", "2025-01-01"] },
361+
apiVersion: { default: "", enum: ["2024-01-01", "2025-01-01"] },
410362
});
411363
}
412364
});

0 commit comments

Comments
 (0)