Skip to content
Merged
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,7 @@
---
changeKind: feature
packages:
- "@azure-tools/typespec-client-generator-core"
---

`@clientOption`'s `value` can now reference a TypeSpec model, in addition to `string`, `boolean`, and `number` literal values. The referenced model (including customizations such as `@alternateType`) is preserved and resolved so scoped emitters can access it via `getClientOptions`.
20 changes: 14 additions & 6 deletions packages/typespec-client-generator-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -877,7 +877,7 @@ See supported client options for each language emitter here https://azure.github
warning if no scope is provided (since options are typically language-specific).

```typespec
@Azure.ClientGenerator.Core.clientOption(name: valueof string, value: valueof unknown, scope?: valueof string)
@Azure.ClientGenerator.Core.clientOption(name: valueof string, value: unknown | valueof unknown, scope?: valueof string)
```

##### Target
Expand All @@ -887,11 +887,11 @@ The type you want to apply the option to.

##### Parameters

| Name | Type | Description |
| ----- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | `valueof string` | The name of the option (e.g., "enableFeatureFoo"). |
| value | `valueof unknown` | The value of the option. Can be any type; emitters will cast as needed. |
| scope | `valueof string` | Specifies the target language emitters to which the decorator applies. Every use must provide an explicit scope; omitting it produces an additional warning.<br /><br />**Supported language identifiers:** `csharp`, `python`, `java`, `javascript`, `go`, and other language emitter names (derived from the emitter package name, e.g., `@azure-tools/typespec-csharp` → `csharp`).<br /><br />**Valid patterns:**<br />- Single language: `"python"`<br />- Multiple languages (comma-separated): `"python, java"`<br />- Negation to exclude languages: `"!csharp"` or `"!(java, python)"` |
| Name | Type | Description |
| ----- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | `valueof string` | The name of the option (e.g., "enableFeatureFoo"). |
| value | `unknown` \| `valueof unknown` | The value of the option. Can be a literal value (string, boolean, number, etc.) or a<br />reference to a TypeSpec model, in which case the referenced model (including its own decorators,<br />such as `@alternateType`) is preserved so the scoped emitter can resolve it. Emitters will cast as needed. |
| scope | `valueof string` | Specifies the target language emitters to which the decorator applies. Every use must provide an explicit scope; omitting it produces an additional warning.<br /><br />**Supported language identifiers:** `csharp`, `python`, `java`, `javascript`, `go`, and other language emitter names (derived from the emitter package name, e.g., `@azure-tools/typespec-csharp` → `csharp`).<br /><br />**Valid patterns:**<br />- Single language: `"python"`<br />- Multiple languages (comma-separated): `"python, java"`<br />- Negation to exclude languages: `"!csharp"` or `"!(java, python)"` |

##### Examples

Expand All @@ -905,6 +905,14 @@ model MyModel {
}
```

###### Apply an experimental option that references a model

```typespec
#suppress "@azure-tools/typespec-client-generator-core/client-option" "preview feature for csharp"
@clientOption("composes", OpenAICreateResponseOptions, "csharp")
model FoundryCreateResponseOptions {}
```

#### `@convenientAPI`

Whether you want to generate an operation as a convenient method.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1089,7 +1089,9 @@ export type ClientDocDecorator = (
*
* @param target The type you want to apply the option to.
* @param name The name of the option (e.g., "enableFeatureFoo").
* @param value The value of the option. Can be any type; emitters will cast as needed.
* @param value The value of the option. Can be a literal value (string, boolean, number, etc.) or a
* reference to a TypeSpec model, in which case the referenced model (including its own decorators,
* such as `@alternateType`) is preserved so the scoped emitter can resolve it. Emitters will cast as needed.
* @param scope Specifies the target language emitters to which the decorator applies. Every use must provide an explicit scope; omitting it produces an additional warning.
*
* **Supported language identifiers:** `csharp`, `python`, `java`, `javascript`, `go`, and other language emitter names (derived from the emitter package name, e.g., `@azure-tools/typespec-csharp` → `csharp`).
Expand All @@ -1106,12 +1108,18 @@ export type ClientDocDecorator = (
* prop: string;
* }
* ```
* @example Apply an experimental option that references a model
* ```typespec
* #suppress "@azure-tools/typespec-client-generator-core/client-option" "preview feature for csharp"
* @clientOption("composes", OpenAICreateResponseOptions, "csharp")
* model FoundryCreateResponseOptions {}
* ```
*/
export type ClientOptionDecorator = (
context: DecoratorContext,
target: Type,
name: string,
value: unknown,
value: Type | unknown,
scope?: string,
) => DecoratorValidatorCallbacks | void;

Expand Down
13 changes: 11 additions & 2 deletions packages/typespec-client-generator-core/lib/decorators.tsp
Original file line number Diff line number Diff line change
Expand Up @@ -1178,7 +1178,9 @@ extern dec clientDoc(
*
* @param target The type you want to apply the option to.
* @param name The name of the option (e.g., "enableFeatureFoo").
* @param value The value of the option. Can be any type; emitters will cast as needed.
* @param value The value of the option. Can be a literal value (string, boolean, number, etc.) or a
* reference to a TypeSpec model, in which case the referenced model (including its own decorators,
* such as `@alternateType`) is preserved so the scoped emitter can resolve it. Emitters will cast as needed.
* @param scope Specifies the target language emitters to which the decorator applies. Every use must provide an explicit scope; omitting it produces an additional warning.
*
* **Supported language identifiers:** `csharp`, `python`, `java`, `javascript`, `go`, and other language emitter names (derived from the emitter package name, e.g., `@azure-tools/typespec-csharp` → `csharp`).
Expand All @@ -1196,10 +1198,17 @@ extern dec clientDoc(
* prop: string;
* }
* ```
*
* @example Apply an experimental option that references a model
* ```typespec
* #suppress "@azure-tools/typespec-client-generator-core/client-option" "preview feature for csharp"
* @clientOption("composes", OpenAICreateResponseOptions, "csharp")
* model FoundryCreateResponseOptions {}
* ```
*/
extern dec clientOption(
target: unknown,
name: valueof string,
value: valueof unknown,
value: unknown | (valueof unknown),
scope?: valueof string
);
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ function getDecoratorArgValue(
): [any, readonly Diagnostic[]] {
const diagnostics = createDiagnosticCollector();
if (typeof arg === "object" && arg !== null && "kind" in arg) {
if (arg.kind === "EnumMember") {
if (arg.kind === "EnumMember" || arg.kind === "Model") {
return diagnostics.wrap(diagnostics.pipe(getClientTypeWithDiagnostics(context, arg as any)));
}
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,63 @@ describe("@clientOption with getClientOptions getter", () => {
strictEqual(typeof numberValue, "number");
});

it("should support a model reference as the value", async () => {
const { program } = await SimpleTesterWithService.compile(`
model ComposedOptions {
a: string;
}

#suppress "@azure-tools/typespec-client-generator-core/client-option"
@clientOption("composes", ComposedOptions, "csharp")
Comment thread
tadelesh marked this conversation as resolved.
@test
model Test {
id: string;
}

op getTest(): Test;
`);

const context = await createSdkContextForTester(program, {
emitterName: "@azure-tools/typespec-csharp",
});

const sdkModel = context.sdkPackage.models.find((m) => m.name === "Test");
ok(sdkModel, "SDK model should exist");

const value = getClientOptions(sdkModel, "composes") as { kind?: string; name?: string };
strictEqual(value?.kind, "model");
strictEqual(value?.name, "ComposedOptions");
});

it("should preserve customizations, such as @alternateType, on a model reference value", async () => {
const { program } = await SimpleTesterWithService.compile(`
@alternateType(string, "csharp")
model AlternateOptions {
a: string;
}

#suppress "@azure-tools/typespec-client-generator-core/client-option"
@clientOption("composes", AlternateOptions, "csharp")
@test
model Test {
id: string;
}

op getTest(): Test;
`);

const context = await createSdkContextForTester(program, {
emitterName: "@azure-tools/typespec-csharp",
});

const sdkModel = context.sdkPackage.models.find((m) => m.name === "Test");
ok(sdkModel, "SDK model should exist");

const value = getClientOptions(sdkModel, "composes") as { kind?: string };
strictEqual(value?.kind, "string");
// @alternateType(string) replaces the referenced model with the builtin `string` type
});

it("should return client option value for operation", async () => {
const { program } = await SimpleTesterWithService.compile(`
#suppress "@azure-tools/typespec-client-generator-core/client-option"
Expand Down
91 changes: 33 additions & 58 deletions packages/typespec-go/src/codegen/core/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,25 +136,17 @@ export function generateModels(
if (needsJSONPopulateAsString) {
serdeImports.add("reflect");
serdeImports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore");
serdeTextBody +=
"func populateAsString(m map[string]any, k string, v any, fn func() string) {\n";
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(
indent,
{
condition: "v == nil",
body: (indent) => `${indent.get()}return\n`,
},
[
{
condition: "azcore.IsNullValue(v)",
body: (indent) => `${indent.get()}m[k] = nil\n`,
},
{
condition: "!reflect.ValueOf(v).IsNil()",
body: (indent) => `${indent.get()}m[k] = fn()\n`,
},
],
)}\n`;
serdeTextBody += "func populateAsString(m map[string]any, k string, v any, fn func() string) {\n";
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: "v == nil",
body: (indent) => `${indent.get()}return\n`,
}, [{
condition: "azcore.IsNullValue(v)",
body: (indent) => `${indent.get()}m[k] = nil\n`,
}, {
condition: "!reflect.ValueOf(v).IsNil()",
body: (indent) => `${indent.get()}m[k] = fn()\n`,
}])}\n`;
serdeTextBody += "}\n\n";
}
if (needsJSONPopulateTime) {
Expand Down Expand Up @@ -219,8 +211,7 @@ export function generateModels(
}
if (needsJSONUnpopulateFromString) {
serdeImports.add("fmt");
serdeTextBody +=
"func unpopulateFromString(data json.RawMessage, fn string, f func(s string) error) error {\n";
serdeTextBody += "func unpopulateFromString(data json.RawMessage, fn string, f func(s string) error) error {\n";
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: `data == nil || string(data) == "null"`,
body: (indent) => `${indent.get()}return nil\n`,
Expand All @@ -233,25 +224,22 @@ export function generateModels(
})}\n`;
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: "err != nil",
body: (indent) =>
`${indent.get()}return fmt.Errorf("struct field %s: %s", fn, err.Error())\n`,
body: (indent) => `${indent.get()}return fmt.Errorf("struct field %s: %s", fn, err.Error())\n`,
})}\n`;
serdeTextBody += `${indent.get()}return nil\n`;
serdeTextBody += "}\n\n";
}
if (needsJSONUnpopulateStringArray) {
serdeImports.add("strings");
serdeTextBody +=
"func unpopulateStringArray[T ~string](data json.RawMessage, fn string, v *[]T, d string) error {\n";
serdeTextBody += "func unpopulateStringArray[T ~string](data json.RawMessage, fn string, v *[]T, d string) error {\n";
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: `data == nil || string(data) == "null"`,
body: (indent) => `${indent.get()}return nil\n`,
})}\n`;
serdeTextBody += `${indent.get()}var encodedValue string\n`;
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: "err := json.Unmarshal(data, &encodedValue); err != nil",
body: (indent) =>
`${indent.get()}return fmt.Errorf("struct field %s: %s", fn, err.Error())\n`,
body: (indent) => `${indent.get()}return fmt.Errorf("struct field %s: %s", fn, err.Error())\n`,
})}\n`;
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: `encodedValue == ""`,
Expand All @@ -263,13 +251,9 @@ export function generateModels(
})}\n`;
serdeTextBody += `${indent.get()}values := strings.Split(encodedValue, d)\n`;
serdeTextBody += `${indent.get()}result := make([]T, len(values))\n`;
serdeTextBody += `${indent.get()}${helpers.buildForBlock(
indent,
"i := range values",
(indent) => {
return `${indent.get()}result[i] = T(values[i])\n`;
},
)}`;
serdeTextBody += `${indent.get()}${helpers.buildForBlock(indent, "i := range values", (indent) => {
return `${indent.get()}result[i] = T(values[i])\n`;
})}`;
serdeTextBody += `${indent.get()}*v = result\n`;
serdeTextBody += `${indent.get()}return nil\n`;
serdeTextBody += "}\n\n";
Expand Down Expand Up @@ -305,32 +289,23 @@ export function generateModels(
if (needsJSONPopulateStringArray) {
serdeImports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore");
serdeImports.add("strings");
serdeTextBody +=
"func populateStringArray[T ~string](m map[string]any, k string, v []T, d string) {";
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(
indent,
serdeTextBody += "func populateStringArray[T ~string](m map[string]any, k string, v []T, d string) {";
serdeTextBody += `${indent.get()}${helpers.buildIfBlock(indent, {
condition: "azcore.IsNullValue(v)",
body: (indent) => `${indent.get()}m[k] = nil\n`,
}, [
{
condition: "azcore.IsNullValue(v)",
body: (indent) => `${indent.get()}m[k] = nil\n`,
},
[
{
condition: "v != nil",
body: (indent) => {
let controlBlock = `${indent.get()}encodedValue := make([]string, len(v))\n`;
controlBlock += `${indent.get()}${helpers.buildForBlock(
indent,
"i := range v",
(indent) => {
return `${indent.get()}encodedValue[i] = string(v[i])\n`;
},
)}`;
controlBlock += `${indent.get()}m[k] = strings.Join(encodedValue, d)\n`;
return controlBlock;
},
condition: "v != nil",
body: (indent) => {
let controlBlock = `${indent.get()}encodedValue := make([]string, len(v))\n`;
controlBlock += `${indent.get()}${helpers.buildForBlock(indent, "i := range v", (indent) => {
return `${indent.get()}encodedValue[i] = string(v[i])\n`;
})}`;
controlBlock += `${indent.get()}m[k] = strings.Join(encodedValue, d)\n`;
return controlBlock;
},
],
)}\n`;
}
])}\n`;
serdeTextBody += "}\n\n";
}
if (needsJSONUnpopulateTime || needsJSONPopulateTime) {
Expand Down
Loading
Loading