diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.js b/packages/typespec-ts/test/commands/cadl-ranch-list.js index 6d4e9de934..eae788b9d0 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.js +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.js @@ -274,6 +274,10 @@ export const rlcTsps = [ { outputPath: "azure/core/model", inputPath: "azure/core/model" + }, + { + outputPath: "azure/resource-manager/models/common-types/managed-identity", + inputPath: "azure/resource-manager/models/common-types/managed-identity" } ]; @@ -530,6 +534,10 @@ export const modularTsps = [ { outputPath: "resiliency/srv-driven-main", inputPath: "resiliency/srv-driven/main.tsp" + }, + { + outputPath: "azure/resource-manager/models/common-types/managed-identity", + inputPath: "azure/resource-manager/models/common-types/managed-identity" } ]; diff --git a/packages/typespec-ts/test/integration/azureArmManagedIdentity.spec.ts b/packages/typespec-ts/test/integration/azureArmManagedIdentity.spec.ts new file mode 100644 index 0000000000..675efd8c12 --- /dev/null +++ b/packages/typespec-ts/test/integration/azureArmManagedIdentity.spec.ts @@ -0,0 +1,128 @@ +import { assert } from "chai"; +import AzureArmModelsCommonTypesManagedIdentityClientFactory, { + AzureArmModelsCommonTypesManagedIdentityClient +} from "./generated/azure/resource-manager/models/common-types/managed-identity/src/index.js"; +describe("Azure Arm Resources Rest Client", () => { + let client: AzureArmModelsCommonTypesManagedIdentityClient; + + beforeEach(() => { + client = AzureArmModelsCommonTypesManagedIdentityClientFactory({ + endpoint: "http://localhost:3000", + allowInsecureConnection: true + }); + }); + const SUBSCRIPTION_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const PRINCIPAL_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const TENANT_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const CLIENT_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const LOCATION_REGION_EXPECTED = "eastus"; + const RESOURCE_GROUP_EXPECTED = "test-rg"; + const IDENTITY_TYPE_SYSTEM_ASSIGNED_EXPECTED = "SystemAssigned"; + const IDENTITY_TYPE_SYSTEM_USER_ASSIGNED_EXPECTED = + "SystemAssigned,UserAssigned"; + const validSystemAssignedManagedIdentityResource = { + id: `/subscriptions/${SUBSCRIPTION_ID_EXPECTED}/resourceGroups/${RESOURCE_GROUP_EXPECTED}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/identity`, + location: `${LOCATION_REGION_EXPECTED}`, + tags: { + tagKey1: "tagValue1" + }, + identity: { + type: `${IDENTITY_TYPE_SYSTEM_ASSIGNED_EXPECTED}`, + principalId: `${PRINCIPAL_ID_EXPECTED}`, + tenantId: `${TENANT_ID_EXPECTED}` + }, + properties: { + provisioningState: "Succeeded" + } + }; + + const validUserAssignedAndSystemAssignedManagedIdentityResource = { + id: `/subscriptions/${SUBSCRIPTION_ID_EXPECTED}/resourceGroups/${RESOURCE_GROUP_EXPECTED}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/identity`, + location: `${LOCATION_REGION_EXPECTED}`, + tags: { + tagKey1: "tagValue1" + }, + identity: { + type: `${IDENTITY_TYPE_SYSTEM_USER_ASSIGNED_EXPECTED}`, + userAssignedIdentities: { + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": + { + principalId: `${PRINCIPAL_ID_EXPECTED}`, + clientId: `${CLIENT_ID_EXPECTED}` + } + }, + principalId: `${PRINCIPAL_ID_EXPECTED}`, + tenantId: `${TENANT_ID_EXPECTED}` + }, + properties: { + provisioningState: "Succeeded" + } + }; + + const createExpectedIdentity = { + type: `${IDENTITY_TYPE_SYSTEM_ASSIGNED_EXPECTED}` + }; + + const updateExpectedIdentity = { + type: `${IDENTITY_TYPE_SYSTEM_USER_ASSIGNED_EXPECTED}`, + userAssignedIdentities: { + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": + {} + } + }; + + // managed identity tracked resource + it("should get models commonTypes managedIdentityTrackedResources", async () => { + const result = await client + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + SUBSCRIPTION_ID_EXPECTED, + RESOURCE_GROUP_EXPECTED, + "identity" + ) + .get(); + assert.strictEqual(result.status, "200"); + assert.deepEqual(result.body, validSystemAssignedManagedIdentityResource); + }); + + it("should put models commonTypes managedIdentityTrackedResources", async () => { + const result = await client + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + SUBSCRIPTION_ID_EXPECTED, + RESOURCE_GROUP_EXPECTED, + "identity" + ) + .put({ + body: { + identity: createExpectedIdentity, + location: LOCATION_REGION_EXPECTED, + tags: { tagKey1: "tagValue1" } + } + }); + assert.strictEqual(result.status, "200"); + assert.deepEqual(result.body, validSystemAssignedManagedIdentityResource); + }); + + it("should patch models commonTypes managedIdentityTrackedResources", async () => { + const result = await client + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + SUBSCRIPTION_ID_EXPECTED, + RESOURCE_GROUP_EXPECTED, + "identity" + ) + .patch({ + body: { + identity: updateExpectedIdentity, + location: LOCATION_REGION_EXPECTED, + tags: { tagKey1: "tagValue1" } + } + }); + assert.strictEqual(result.status, "200"); + assert.deepEqual( + result.body, + validUserAssignedAndSystemAssignedManagedIdentityResource + ); + }); +}); diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/.eslintrc.json b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/.eslintrc.json new file mode 100644 index 0000000000..8793fba07e --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/.eslintrc.json @@ -0,0 +1,14 @@ +{ + "plugins": ["@azure/azure-sdk"], + "extends": ["plugin:@azure/azure-sdk/azure-sdk-base"], + "rules": { + "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-apiextractor-json-types": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "tsdoc/syntax": "warn", + "@azure/azure-sdk/ts-package-json-module": "off", + "@azure/azure-sdk/ts-package-json-files-required": "off", + "@azure/azure-sdk/ts-package-json-main-is-cjs": "off" + } +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/LICENSE b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/LICENSE new file mode 100644 index 0000000000..7d59347409 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/README.md b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/README.md new file mode 100644 index 0000000000..4673b4ed7a --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/README.md @@ -0,0 +1,57 @@ +# AzureArmModelsCommonTypesManagedIdentity REST client library for JavaScript + +Arm Managed Identity Provider management API. + +**If you are not familiar with our REST client, please spend 5 minutes to take a look at our [REST client docs](https://github.com/Azure/azure-sdk-for-js/blob/main/documentation/rest-clients.md) to use this library, the REST client provides a light-weighted & developer friendly way to call azure rest api + +Key links: + +- [Package (NPM)](https://www.npmjs.com/package/@azure/arm-managedIdentity) +- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-managedIdentity) + +## Getting started + +### Currently supported environments + +- LTS versions of Node.js + +### Prerequisites + +- You must have an [Azure subscription](https://azure.microsoft.com/free/) to use this package. + +### Install the `@azure/arm-managedIdentity` package + +Install the AzureArmModelsCommonTypesManagedIdentity REST client REST client library for JavaScript with `npm`: + +```bash +npm install @azure/arm-managedIdentity +``` + +### Create and authenticate a `AzureArmModelsCommonTypesManagedIdentityClient` + +To use an [Azure Active Directory (AAD) token credential](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token), +provide an instance of the desired credential type obtained from the +[@azure/identity](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) library. + +To authenticate with AAD, you must first `npm` install [`@azure/identity`](https://www.npmjs.com/package/@azure/identity) + +After setup, you can choose which type of [credential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#credentials) from `@azure/identity` to use. +As an example, [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential) +can be used to authenticate the client. + +Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: +AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET + +## Troubleshooting + +### Logging + +Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: + +```javascript +const { setLogLevel } = require("@azure/logger"); + +setLogLevel("info"); +``` + +For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/api-extractor.json b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/api-extractor.json new file mode 100644 index 0000000000..229071c648 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/api-extractor.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "./dist/esm/index.d.ts", + "docModel": { "enabled": true }, + "apiReport": { "enabled": true, "reportFolder": "./review" }, + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./types/arm-managedIdentity.d.ts" + }, + "messages": { + "tsdocMessageReporting": { "default": { "logLevel": "none" } }, + "extractorMessageReporting": { + "ae-missing-release-tag": { "logLevel": "none" }, + "ae-unresolved-link": { "logLevel": "none" } + } + } +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/package.json b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/package.json new file mode 100644 index 0000000000..8320df6474 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/package.json @@ -0,0 +1,52 @@ +{ + "name": "@azure/arm-managedIdentity", + "version": "1.0.0", + "description": "AzureArm models CommonTypes ManagedIdentity Test Service", + "engines": { + "node": ">=18.0.0" + }, + "sideEffects": false, + "autoPublish": false, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts" + }, + "dialects": ["esm", "commonjs"], + "esmDialects": ["browser", "react-native"], + "selfLink": false + }, + "type": "module", + "keywords": ["node", "azure", "cloud", "typescript", "browser", "isomorphic"], + "author": "Microsoft Corporation", + "license": "MIT", + "files": ["dist", "README.md", "LICENSE", "review/*", "CHANGELOG.md"], + "dependencies": { + "@azure-rest/core-client": "^2.1.0", + "@azure/core-auth": "^1.6.0", + "@azure/core-rest-pipeline": "^1.5.0", + "@azure/logger": "^1.0.0", + "tslib": "^2.6.2" + }, + "devDependencies": { + "dotenv": "^16.0.0", + "@microsoft/api-extractor": "^7.40.3", + "@types/node": "^18.0.0", + "eslint": "^8.55.0", + "prettier": "^3.2.5", + "rimraf": "^5.0.5", + "mkdirp": "^3.0.1", + "typescript": "~5.5.3", + "tshy": "1.11.1" + }, + "scripts": { + "clean": "rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "extract-api": "rimraf review && mkdirp ./review && api-extractor run --local", + "pack": "npm pack 2>&1", + "lint": "eslint package.json api-extractor.json src --ext .ts", + "lint:fix": "eslint package.json api-extractor.json src --ext .ts --fix --fix-type [problem,suggestion]", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\" \"samples-dev/**/*.ts\"", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\" \"samples-dev/**/*.ts\"", + "build": "npm run clean && tshy && npm run extract-api" + } +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/rollup.config.js b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/rollup.config.js new file mode 100644 index 0000000000..61251d7a8d --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/rollup.config.js @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import nodeResolve from "@rollup/plugin-node-resolve"; +import cjs from "@rollup/plugin-commonjs"; +import sourcemaps from "rollup-plugin-sourcemaps"; +import multiEntry from "@rollup/plugin-multi-entry"; +import json from "@rollup/plugin-json"; + +import nodeBuiltins from "builtin-modules"; + +// #region Warning Handler + +/** + * A function that can determine whether a rollup warning should be ignored. If + * the function returns `true`, then the warning will not be displayed. + */ + +function ignoreNiseSinonEval(warning) { + return ( + warning.code === "EVAL" && + warning.id && + (warning.id.includes("node_modules/nise") || + warning.id.includes("node_modules/sinon")) === true + ); +} + +function ignoreChaiCircularDependency(warning) { + return ( + warning.code === "CIRCULAR_DEPENDENCY" && + warning.importer && + warning.importer.includes("node_modules/chai") === true + ); +} + +const warningInhibitors = [ignoreChaiCircularDependency, ignoreNiseSinonEval]; + +/** + * Construct a warning handler for the shared rollup configuration + * that ignores certain warnings that are not relevant to testing. + */ +function makeOnWarnForTesting() { + return (warning, warn) => { + // If every inhibitor returns false (i.e. no inhibitors), then show the warning + if (warningInhibitors.every((inhib) => !inhib(warning))) { + warn(warning); + } + }; +} + +// #endregion + +function makeBrowserTestConfig() { + const config = { + input: { + include: ["dist-esm/test/**/*.spec.js"], + exclude: ["dist-esm/test/**/node/**"], + }, + output: { + file: `dist-test/index.browser.js`, + format: "umd", + sourcemap: true, + }, + preserveSymlinks: false, + plugins: [ + multiEntry({ exports: false }), + nodeResolve({ + mainFields: ["module", "browser"], + }), + cjs(), + json(), + sourcemaps(), + //viz({ filename: "dist-test/browser-stats.html", sourcemap: true }) + ], + onwarn: makeOnWarnForTesting(), + // Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0, + // rollup started respecting the "sideEffects" field in package.json. Since + // our package.json sets "sideEffects=false", this also applies to test + // code, which causes all tests to be removed by tree-shaking. + treeshake: false, + }; + + return config; +} + +const defaultConfigurationOptions = { + disableBrowserBundle: false, +}; + +export function makeConfig(pkg, options) { + options = { + ...defaultConfigurationOptions, + ...(options || {}), + }; + + const baseConfig = { + // Use the package's module field if it has one + input: pkg["module"] || "dist-esm/src/index.js", + external: [ + ...nodeBuiltins, + ...Object.keys(pkg.dependencies), + ...Object.keys(pkg.devDependencies), + ], + output: { file: "dist/index.js", format: "cjs", sourcemap: true }, + preserveSymlinks: false, + plugins: [sourcemaps(), nodeResolve()], + }; + + const config = [baseConfig]; + + if (!options.disableBrowserBundle) { + config.push(makeBrowserTestConfig()); + } + + return config; +} + +export default makeConfig(require("./package.json")); diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/createWithSystemAssignedSample.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/createWithSystemAssignedSample.ts new file mode 100644 index 0000000000..2a9e5b9120 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/createWithSystemAssignedSample.ts @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import createAzureArmModelsCommonTypesManagedIdentityClient from "@azure/arm-managedIdentity"; +import * as dotenv from "dotenv"; + +dotenv.config(); + +/** + * This sample demonstrates how to call operation CreateWithSystemAssigned + * + * @summary call operation CreateWithSystemAssigned + */ +async function createWithSystemAssignedSample() { + const client = createAzureArmModelsCommonTypesManagedIdentityClient(); + const subscriptionId = "{Your subscriptionId}"; + const resourceGroupName = "{Your resourceGroupName}"; + const managedIdentityTrackedResourceName = + "{Your managedIdentityTrackedResourceName}"; + const result = await client + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + ) + .put({ + body: { + tags: { key: "{Your tags}" }, + location: "{Your location}", + properties: {}, + identity: { type: "None", userAssignedIdentities: { key: {} } }, + }, + }); + console.log(result); +} + +async function main() { + createWithSystemAssignedSample(); +} + +main().catch(console.error); diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/getSample.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/getSample.ts new file mode 100644 index 0000000000..d50f1b1b76 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/getSample.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import createAzureArmModelsCommonTypesManagedIdentityClient from "@azure/arm-managedIdentity"; +import * as dotenv from "dotenv"; + +dotenv.config(); + +/** + * This sample demonstrates how to call operation Get + * + * @summary call operation Get + */ +async function getSample() { + const client = createAzureArmModelsCommonTypesManagedIdentityClient(); + const subscriptionId = "{Your subscriptionId}"; + const resourceGroupName = "{Your resourceGroupName}"; + const managedIdentityTrackedResourceName = + "{Your managedIdentityTrackedResourceName}"; + const result = await client + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + ) + .get(); + console.log(result); +} + +async function main() { + getSample(); +} + +main().catch(console.error); diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/updateWithUserAssignedAndSystemAssignedSample.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/updateWithUserAssignedAndSystemAssignedSample.ts new file mode 100644 index 0000000000..19f4b8f568 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/samples-dev/updateWithUserAssignedAndSystemAssignedSample.ts @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import createAzureArmModelsCommonTypesManagedIdentityClient from "@azure/arm-managedIdentity"; +import * as dotenv from "dotenv"; + +dotenv.config(); + +/** + * This sample demonstrates how to call operation UpdateWithUserAssignedAndSystemAssigned + * + * @summary call operation UpdateWithUserAssignedAndSystemAssigned + */ +async function updateWithUserAssignedAndSystemAssignedSample() { + const client = createAzureArmModelsCommonTypesManagedIdentityClient(); + const subscriptionId = "{Your subscriptionId}"; + const resourceGroupName = "{Your resourceGroupName}"; + const managedIdentityTrackedResourceName = + "{Your managedIdentityTrackedResourceName}"; + const result = await client + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + ) + .patch({ + body: { + tags: { key: "{Your tags}" }, + location: "{Your location}", + properties: {}, + identity: { type: "None", userAssignedIdentities: { key: {} } }, + }, + }); + console.log(result); +} + +async function main() { + updateWithUserAssignedAndSystemAssignedSample(); +} + +main().catch(console.error); diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/azureArmModelsCommonTypesManagedIdentity.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/azureArmModelsCommonTypesManagedIdentity.ts new file mode 100644 index 0000000000..69432bb289 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/azureArmModelsCommonTypesManagedIdentity.ts @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "./logger.js"; +import { AzureArmModelsCommonTypesManagedIdentityClient } from "./clientDefinitions.js"; + +/** The optional parameters for the client */ +export interface AzureArmModelsCommonTypesManagedIdentityClientOptions + extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + +/** + * Initialize a new instance of `AzureArmModelsCommonTypesManagedIdentityClient` + * @param options - the parameter for all optional parameters + */ +export default function createClient({ + apiVersion = "2023-12-01-preview", + ...options +}: AzureArmModelsCommonTypesManagedIdentityClientOptions = {}): AzureArmModelsCommonTypesManagedIdentityClient { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? `https://management.azure.com`; + const userAgentInfo = `azsdk-js-arm-managedIdentity-rest/1.0.0`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + const client = getClient( + endpointUrl, + options, + ) as AzureArmModelsCommonTypesManagedIdentityClient; + + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/clientDefinitions.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/clientDefinitions.ts new file mode 100644 index 0000000000..62ccd5a6b1 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/clientDefinitions.ts @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + GetParameters, + CreateWithSystemAssignedParameters, + UpdateWithUserAssignedAndSystemAssignedParameters, +} from "./parameters.js"; +import { + Get200Response, + GetDefaultResponse, + CreateWithSystemAssigned200Response, + CreateWithSystemAssigned201Response, + CreateWithSystemAssignedDefaultResponse, + UpdateWithUserAssignedAndSystemAssigned200Response, + UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface Get { + /** Get a ManagedIdentityTrackedResource */ + get( + options?: GetParameters, + ): StreamableMethod; + /** Create a ManagedIdentityTrackedResource */ + put( + options: CreateWithSystemAssignedParameters, + ): StreamableMethod< + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse + >; + /** Update a ManagedIdentityTrackedResource */ + patch( + options: UpdateWithUserAssignedAndSystemAssignedParameters, + ): StreamableMethod< + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse + >; +} + +export interface Routes { + /** Resource for '/subscriptions/\{subscriptionId\}/resourceGroups/\{resourceGroupName\}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/\{managedIdentityTrackedResourceName\}' has methods for the following verbs: get, put, patch */ + ( + path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + ): Get; +} + +export type AzureArmModelsCommonTypesManagedIdentityClient = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.ts new file mode 100644 index 0000000000..63122e5da2 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import AzureArmModelsCommonTypesManagedIdentity from "./azureArmModelsCommonTypesManagedIdentity.js"; + +export * from "./azureArmModelsCommonTypesManagedIdentity.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./isUnexpected.js"; +export * from "./models.js"; +export * from "./outputModels.js"; + +export default AzureArmModelsCommonTypesManagedIdentity; diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/isUnexpected.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/isUnexpected.ts new file mode 100644 index 0000000000..032d6276c7 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/isUnexpected.ts @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + Get200Response, + GetDefaultResponse, + CreateWithSystemAssigned200Response, + CreateWithSystemAssigned201Response, + CreateWithSystemAssignedDefaultResponse, + UpdateWithUserAssignedAndSystemAssigned200Response, + UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +} from "./responses.js"; + +const responseMap: Record = { + "GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}": + ["200"], + "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}": + ["200", "201"], + "PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}": + ["200"], +}; + +export function isUnexpected( + response: Get200Response | GetDefaultResponse, +): response is GetDefaultResponse; +export function isUnexpected( + response: + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse, +): response is CreateWithSystemAssignedDefaultResponse; +export function isUnexpected( + response: + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +): response is UpdateWithUserAssignedAndSystemAssignedDefaultResponse; +export function isUnexpected( + response: + | Get200Response + | GetDefaultResponse + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +): response is + | GetDefaultResponse + | CreateWithSystemAssignedDefaultResponse + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse { + const lroOriginal = response.headers["x-ms-original-url"]; + const url = new URL(lroOriginal ?? response.request.url); + const method = response.request.method; + let pathDetails = responseMap[`${method} ${url.pathname}`]; + if (!pathDetails) { + pathDetails = getParametrizedPathSuccess(method, url.pathname); + } + return !pathDetails.includes(response.status); +} + +function getParametrizedPathSuccess(method: string, path: string): string[] { + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: string[] = []; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(responseMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}`, + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/logger.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/logger.ts new file mode 100644 index 0000000000..f5ddcfd9e5 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("arm-managedIdentity"); diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/models.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/models.ts new file mode 100644 index 0000000000..45de9752b0 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/models.ts @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** Concrete tracked resource types can be created by aliasing this type using a specific property type. */ +export interface ManagedIdentityTrackedResource extends TrackedResource { + /** The resource-specific properties for this resource. */ + properties?: ManagedIdentityTrackedResourceProperties; + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentity; +} + +/** Managed Identity Arm Resource Properties. */ +export interface ManagedIdentityTrackedResourceProperties {} + +/** Managed service identity (system assigned and/or user assigned identities) */ +export interface ManagedServiceIdentity { + /** + * The type of managed identity assigned to this resource. + * + * Possible values: "None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned" + */ + type: ManagedServiceIdentityType; + /** The identities assigned to this resource by the user. */ + userAssignedIdentities?: Record; +} + +/** User assigned identity properties */ +export interface UserAssignedIdentity {} + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResource extends Resource { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface Resource {} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemData { + /** The identity that created the resource. */ + createdBy?: string; + /** + * The type of identity that created the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date | string; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** + * The type of identity that last modified the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + lastModifiedByType?: CreatedByType; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: Date | string; +} + +/** The resource model definition for an Azure Resource Manager resource with an etag. */ +export interface AzureEntityResource extends Resource {} + +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ +export interface ProxyResource extends Resource {} + +/** The base extension resource. */ +export interface ExtensionResource extends Resource {} + +/** A private link resource. */ +export interface PrivateLinkResource extends Resource { + /** Resource properties. */ + properties?: PrivateLinkResourceProperties; +} + +/** Properties of a private link resource. */ +export interface PrivateLinkResourceProperties { + /** The private link resource private link DNS zone name. */ + requiredZoneNames?: string[]; +} + +/** The private endpoint connection resource */ +export interface PrivateEndpointConnection extends Resource { + /** The private endpoint connection properties */ + properties?: PrivateEndpointConnectionProperties; +} + +/** Properties of the private endpoint connection. */ +export interface PrivateEndpointConnectionProperties { + /** The private endpoint resource. */ + privateEndpoint?: PrivateEndpoint; + /** A collection of information about the state of the connection between service consumer and provider. */ + privateLinkServiceConnectionState: PrivateLinkServiceConnectionState; +} + +/** The Private Endpoint resource. */ +export interface PrivateEndpoint {} + +/** A collection of information about the state of the connection between service consumer and provider. */ +export interface PrivateLinkServiceConnectionState { + /** + * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + * + * Possible values: "Pending", "Approved", "Rejected" + */ + status?: PrivateEndpointServiceConnectionStatus; + /** The reason for approval/rejection of the connection. */ + description?: string; + /** A message indicating if changes on the service provider require any updates on the consumer. */ + actionsRequired?: string; +} + +/** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ +export interface ResourceModelWithAllowedPropertySet extends TrackedResource { + /** + * The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. + * If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. + */ + managedBy?: string; + /** + * Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. + * If supported, the resource provider must validate and persist this value. + */ + kind?: string; + /** + * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. + * Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), + * If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + */ + eTag?: string; + identity?: Identity; + sku?: Sku; + plan?: Plan; +} + +/** Identity for the resource. */ +export interface Identity { + /** The identity type. */ + type?: ResourceIdentityType; +} + +/** The resource model definition representing SKU */ +export interface Sku { + /** The name of the SKU. Ex - P3. It is typically a letter+number code */ + name: string; + /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ + tier?: SkuTier; + /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ + size?: string; + /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ + family?: string; + /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ + capacity?: number; +} + +/** Plan for the resource. */ +export interface Plan { + /** A user defined name of the 3rd Party Artifact that is being procured. */ + name: string; + /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ + publisher: string; + /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ + product: string; + /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ + promotionCode?: string; + /** The version of the desired product/artifact. */ + version?: string; +} + +/** Alias for ManagedServiceIdentityType */ +export type ManagedServiceIdentityType = string; +/** Alias for CreatedByType */ +export type CreatedByType = string; +/** Alias for PrivateEndpointServiceConnectionStatus */ +export type PrivateEndpointServiceConnectionStatus = string; +/** Alias for PrivateEndpointConnectionProvisioningState */ +export type PrivateEndpointConnectionProvisioningState = string; +/** Alias for ResourceIdentityType */ +export type ResourceIdentityType = "SystemAssigned"; +/** Alias for SkuTier */ +export type SkuTier = "Free" | "Basic" | "Standard" | "Premium"; diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/outputModels.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/outputModels.ts new file mode 100644 index 0000000000..0a8e5aaf75 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/outputModels.ts @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** Concrete tracked resource types can be created by aliasing this type using a specific property type. */ +export interface ManagedIdentityTrackedResourceOutput + extends TrackedResourceOutput { + /** The resource-specific properties for this resource. */ + properties?: ManagedIdentityTrackedResourcePropertiesOutput; + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentityOutput; +} + +/** Managed Identity Arm Resource Properties. */ +export interface ManagedIdentityTrackedResourcePropertiesOutput { + /** The status of the last operation. */ + readonly provisioningState: string; +} + +/** Managed service identity (system assigned and/or user assigned identities) */ +export interface ManagedServiceIdentityOutput { + /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly principalId?: string; + /** The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly tenantId?: string; + /** + * The type of managed identity assigned to this resource. + * + * Possible values: "None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned" + */ + type: ManagedServiceIdentityTypeOutput; + /** The identities assigned to this resource by the user. */ + userAssignedIdentities?: Record; +} + +/** User assigned identity properties */ +export interface UserAssignedIdentityOutput { + /** The principal ID of the assigned identity. */ + readonly principalId?: string; + /** The client ID of the assigned identity. */ + readonly clientId?: string; +} + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResourceOutput extends ResourceOutput { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface ResourceOutput { + /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ + readonly id?: string; + /** The name of the resource */ + readonly name?: string; + /** The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" */ + readonly type?: string; + /** Azure Resource Manager metadata containing createdBy and modifiedBy information. */ + readonly systemData?: SystemDataOutput; +} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemDataOutput { + /** The identity that created the resource. */ + createdBy?: string; + /** + * The type of identity that created the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + createdByType?: CreatedByTypeOutput; + /** The timestamp of resource creation (UTC). */ + createdAt?: string; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** + * The type of identity that last modified the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + lastModifiedByType?: CreatedByTypeOutput; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: string; +} + +/** The resource model definition for an Azure Resource Manager resource with an etag. */ +export interface AzureEntityResourceOutput extends ResourceOutput { + /** Resource Etag. */ + readonly etag?: string; +} + +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ +export interface ProxyResourceOutput extends ResourceOutput {} + +/** The base extension resource. */ +export interface ExtensionResourceOutput extends ResourceOutput {} + +/** A private link resource. */ +export interface PrivateLinkResourceOutput extends ResourceOutput { + /** Resource properties. */ + properties?: PrivateLinkResourcePropertiesOutput; +} + +/** Properties of a private link resource. */ +export interface PrivateLinkResourcePropertiesOutput { + /** The private link resource group id. */ + readonly groupId?: string; + /** The private link resource required member names. */ + readonly requiredMembers?: string[]; + /** The private link resource private link DNS zone name. */ + requiredZoneNames?: string[]; +} + +/** The private endpoint connection resource */ +export interface PrivateEndpointConnectionOutput extends ResourceOutput { + /** The private endpoint connection properties */ + properties?: PrivateEndpointConnectionPropertiesOutput; +} + +/** Properties of the private endpoint connection. */ +export interface PrivateEndpointConnectionPropertiesOutput { + /** The private endpoint resource. */ + privateEndpoint?: PrivateEndpointOutput; + /** A collection of information about the state of the connection between service consumer and provider. */ + privateLinkServiceConnectionState: PrivateLinkServiceConnectionStateOutput; + /** + * The provisioning state of the private endpoint connection resource. + * + * Possible values: "Succeeded", "Creating", "Deleting", "Failed" + */ + readonly provisioningState?: PrivateEndpointConnectionProvisioningStateOutput; +} + +/** The Private Endpoint resource. */ +export interface PrivateEndpointOutput { + /** The resource identifier for private endpoint */ + readonly id?: string; +} + +/** A collection of information about the state of the connection between service consumer and provider. */ +export interface PrivateLinkServiceConnectionStateOutput { + /** + * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + * + * Possible values: "Pending", "Approved", "Rejected" + */ + status?: PrivateEndpointServiceConnectionStatusOutput; + /** The reason for approval/rejection of the connection. */ + description?: string; + /** A message indicating if changes on the service provider require any updates on the consumer. */ + actionsRequired?: string; +} + +/** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ +export interface ResourceModelWithAllowedPropertySetOutput + extends TrackedResourceOutput { + /** + * The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. + * If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. + */ + managedBy?: string; + /** + * Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. + * If supported, the resource provider must validate and persist this value. + */ + kind?: string; + /** + * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. + * Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), + * If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + */ + eTag?: string; + identity?: IdentityOutput; + sku?: SkuOutput; + plan?: PlanOutput; +} + +/** Identity for the resource. */ +export interface IdentityOutput { + /** The principal ID of resource identity. The value must be an UUID. */ + readonly principalId?: string; + /** The tenant ID of resource. The value must be an UUID. */ + readonly tenantId?: string; + /** The identity type. */ + type?: ResourceIdentityTypeOutput; +} + +/** The resource model definition representing SKU */ +export interface SkuOutput { + /** The name of the SKU. Ex - P3. It is typically a letter+number code */ + name: string; + /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ + tier?: SkuTierOutput; + /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ + size?: string; + /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ + family?: string; + /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ + capacity?: number; +} + +/** Plan for the resource. */ +export interface PlanOutput { + /** A user defined name of the 3rd Party Artifact that is being procured. */ + name: string; + /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ + publisher: string; + /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ + product: string; + /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ + promotionCode?: string; + /** The version of the desired product/artifact. */ + version?: string; +} + +/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. */ +export interface ErrorResponseOutput { + /** The error object. */ + error?: ErrorDetailOutput; +} + +/** The error detail. */ +export interface ErrorDetailOutput { + /** The error code. */ + readonly code?: string; + /** The error message. */ + readonly message?: string; + /** The error target. */ + readonly target?: string; + /** The error details. */ + readonly details?: Array; + /** The error additional info. */ + readonly additionalInfo?: Array; +} + +/** The resource management error additional info. */ +export interface ErrorAdditionalInfoOutput { + /** The additional info type. */ + readonly type?: string; + /** The additional info. */ + readonly info?: Record; +} + +/** Alias for ManagedServiceIdentityTypeOutput */ +export type ManagedServiceIdentityTypeOutput = string; +/** Alias for CreatedByTypeOutput */ +export type CreatedByTypeOutput = string; +/** Alias for PrivateEndpointServiceConnectionStatusOutput */ +export type PrivateEndpointServiceConnectionStatusOutput = string; +/** Alias for PrivateEndpointConnectionProvisioningStateOutput */ +export type PrivateEndpointConnectionProvisioningStateOutput = string; +/** Alias for ResourceIdentityTypeOutput */ +export type ResourceIdentityTypeOutput = "SystemAssigned"; +/** Alias for SkuTierOutput */ +export type SkuTierOutput = "Free" | "Basic" | "Standard" | "Premium"; diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/parameters.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/parameters.ts new file mode 100644 index 0000000000..cc6d20544a --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/parameters.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RequestParameters } from "@azure-rest/core-client"; +import { ManagedIdentityTrackedResource } from "./models.js"; + +export type GetParameters = RequestParameters; + +export interface CreateWithSystemAssignedBodyParam { + /** Resource create parameters. */ + body: ManagedIdentityTrackedResource; +} + +export type CreateWithSystemAssignedParameters = + CreateWithSystemAssignedBodyParam & RequestParameters; + +export interface UpdateWithUserAssignedAndSystemAssignedBodyParam { + /** The resource properties to be updated. */ + body: ManagedIdentityTrackedResource; +} + +export type UpdateWithUserAssignedAndSystemAssignedParameters = + UpdateWithUserAssignedAndSystemAssignedBodyParam & RequestParameters; diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/responses.ts b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/responses.ts new file mode 100644 index 0000000000..23feb26f57 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/src/responses.ts @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + ManagedIdentityTrackedResourceOutput, + ErrorResponseOutput, +} from "./outputModels.js"; + +/** Azure operation completed successfully. */ +export interface Get200Response extends HttpResponse { + status: "200"; + body: ManagedIdentityTrackedResourceOutput; +} + +export interface GetDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponseOutput; +} + +/** Resource 'ManagedIdentityTrackedResource' update operation succeeded */ +export interface CreateWithSystemAssigned200Response extends HttpResponse { + status: "200"; + body: ManagedIdentityTrackedResourceOutput; +} + +/** Resource 'ManagedIdentityTrackedResource' create operation succeeded */ +export interface CreateWithSystemAssigned201Response extends HttpResponse { + status: "201"; + body: ManagedIdentityTrackedResourceOutput; +} + +export interface CreateWithSystemAssignedDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponseOutput; +} + +/** Azure operation completed successfully. */ +export interface UpdateWithUserAssignedAndSystemAssigned200Response + extends HttpResponse { + status: "200"; + body: ManagedIdentityTrackedResourceOutput; +} + +export interface UpdateWithUserAssignedAndSystemAssignedDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponseOutput; +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/tsconfig.json b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/tsconfig.json new file mode 100644 index 0000000000..cae69d15d4 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2017", + "module": "NodeNext", + "lib": [], + "declaration": true, + "declarationMap": true, + "inlineSources": true, + "sourceMap": true, + "importHelpers": true, + "strict": true, + "alwaysStrict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "NodeNext", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "paths": { "@azure/arm-managedIdentity": ["./src/index"] } + }, + "include": ["./src/**/*.ts", "samples-dev/**/*.ts"] +} diff --git a/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/tspconfig.yaml b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/tspconfig.yaml new file mode 100644 index 0000000000..b3af5d9c63 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/azure/resource-manager/models/common-types/managed-identity/tspconfig.yaml @@ -0,0 +1,16 @@ +emit: + - "@azure-tools/typespec-ts" +options: + "@azure-tools/typespec-ts": + "emitter-output-dir": "{project-root}" + generateMetadata: true + generateTest: false + addCredentials: false + azureSdkForJs: false + isTypeSpecTest: true + generateSample: true + title: Azure Arm models CommonTypes ManagedIdentity + packageDetails: + name: "@azure/arm-managedIdentity" + description: "AzureArm models CommonTypes ManagedIdentity Test Service" + version: "1.0.0" diff --git a/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts b/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts new file mode 100644 index 0000000000..d70eddfacd --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts @@ -0,0 +1,180 @@ +import { assert } from "chai"; +import { ManagedIdentityClient } from "./generated/azure/resource-manager/models/common-types/managed-identity/src/index.js"; +describe("Azure Arm Resources Rest Client", () => { + let client: ManagedIdentityClient; + + beforeEach(() => { + client = new ManagedIdentityClient({ + endpoint: "http://localhost:3002", + allowInsecureConnection: true + }); + }); + const SUBSCRIPTION_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const PRINCIPAL_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const TENANT_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const CLIENT_ID_EXPECTED = "00000000-0000-0000-0000-000000000000"; + const LOCATION_REGION_EXPECTED = "eastus"; + const RESOURCE_GROUP_EXPECTED = "test-rg"; + const IDENTITY_TYPE_SYSTEM_ASSIGNED_EXPECTED = "SystemAssigned"; + const IDENTITY_TYPE_SYSTEM_USER_ASSIGNED_EXPECTED = + "SystemAssigned,UserAssigned"; + const validSystemAssignedManagedIdentityResource = { + id: `/subscriptions/${SUBSCRIPTION_ID_EXPECTED}/resourceGroups/${RESOURCE_GROUP_EXPECTED}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/identity`, + location: `${LOCATION_REGION_EXPECTED}`, + tags: { + tagKey1: "tagValue1" + }, + identity: { + type: `${IDENTITY_TYPE_SYSTEM_ASSIGNED_EXPECTED}`, + principalId: `${PRINCIPAL_ID_EXPECTED}`, + tenantId: `${TENANT_ID_EXPECTED}` + }, + properties: { + provisioningState: "Succeeded" + } + }; + + const validUserAssignedAndSystemAssignedManagedIdentityResource = { + id: `/subscriptions/${SUBSCRIPTION_ID_EXPECTED}/resourceGroups/${RESOURCE_GROUP_EXPECTED}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/identity`, + location: `${LOCATION_REGION_EXPECTED}`, + tags: { + tagKey1: "tagValue1" + }, + identity: { + type: `${IDENTITY_TYPE_SYSTEM_USER_ASSIGNED_EXPECTED}`, + userAssignedIdentities: { + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": + { + principalId: `${PRINCIPAL_ID_EXPECTED}`, + clientId: `${CLIENT_ID_EXPECTED}` + } + }, + principalId: `${PRINCIPAL_ID_EXPECTED}`, + tenantId: `${TENANT_ID_EXPECTED}` + }, + properties: { + provisioningState: "Succeeded" + } + }; + + const createExpectedIdentity = { + type: `${IDENTITY_TYPE_SYSTEM_ASSIGNED_EXPECTED}` + }; + + const updateExpectedIdentity = { + type: `${IDENTITY_TYPE_SYSTEM_USER_ASSIGNED_EXPECTED}`, + userAssignedIdentities: { + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": + {} + } + }; + + // managed identity tracked resource + it("should get models commonTypes managedIdentityTrackedResources", async () => { + const result = await client.get( + SUBSCRIPTION_ID_EXPECTED, + RESOURCE_GROUP_EXPECTED, + "identity" + ); + assert.strictEqual( + result.id, + validSystemAssignedManagedIdentityResource.id + ); + assert.strictEqual( + result.location, + validSystemAssignedManagedIdentityResource.location + ); + assert.strictEqual( + result.identity?.type, + validSystemAssignedManagedIdentityResource.identity?.type + ); + assert.strictEqual( + result.identity?.principalId, + validSystemAssignedManagedIdentityResource.identity.principalId + ); + assert.strictEqual( + result.identity?.tenantId, + validSystemAssignedManagedIdentityResource.identity.tenantId + ); + assert.deepEqual( + result.tags, + validSystemAssignedManagedIdentityResource.tags + ); + assert.deepEqual( + result.properties, + validSystemAssignedManagedIdentityResource.properties + ); + }); + + it("should put models commonTypes managedIdentityTrackedResources", async () => { + const result = await client.createWithSystemAssigned( + SUBSCRIPTION_ID_EXPECTED, + RESOURCE_GROUP_EXPECTED, + "identity", + { + location: LOCATION_REGION_EXPECTED, + identity: createExpectedIdentity + } + ); + assert.strictEqual( + result.id, + validSystemAssignedManagedIdentityResource.id + ); + assert.strictEqual( + result.location, + validSystemAssignedManagedIdentityResource.location + ); + assert.strictEqual( + result.identity?.type, + validSystemAssignedManagedIdentityResource.identity?.type + ); + assert.strictEqual( + result.identity?.principalId, + validSystemAssignedManagedIdentityResource.identity.principalId + ); + assert.strictEqual( + result.identity?.tenantId, + validSystemAssignedManagedIdentityResource.identity.tenantId + ); + assert.deepEqual( + result.tags, + validSystemAssignedManagedIdentityResource.tags + ); + assert.deepEqual( + result.properties, + validSystemAssignedManagedIdentityResource.properties + ); + }); + + it("should patch models commonTypes managedIdentityTrackedResources", async () => { + const result = await client.updateWithUserAssignedAndSystemAssigned( + SUBSCRIPTION_ID_EXPECTED, + RESOURCE_GROUP_EXPECTED, + "identity", + { + location: LOCATION_REGION_EXPECTED, + identity: updateExpectedIdentity + } + ); + assert.strictEqual( + result.id, + validUserAssignedAndSystemAssignedManagedIdentityResource.id + ); + assert.strictEqual( + result.location, + validUserAssignedAndSystemAssignedManagedIdentityResource.location + ); + assert.deepEqual( + result.identity, + validUserAssignedAndSystemAssignedManagedIdentityResource.identity + ); + assert.deepEqual( + result.tags, + validUserAssignedAndSystemAssignedManagedIdentityResource.tags + ); + assert.deepEqual( + result.properties, + validUserAssignedAndSystemAssignedManagedIdentityResource.properties + ); + }); +}); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/.eslintrc.json b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/.eslintrc.json new file mode 100644 index 0000000000..8793fba07e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/.eslintrc.json @@ -0,0 +1,14 @@ +{ + "plugins": ["@azure/azure-sdk"], + "extends": ["plugin:@azure/azure-sdk/azure-sdk-base"], + "rules": { + "@azure/azure-sdk/ts-modules-only-named": "warn", + "@azure/azure-sdk/ts-apiextractor-json-types": "warn", + "@azure/azure-sdk/ts-package-json-types": "warn", + "@azure/azure-sdk/ts-package-json-engine-is-present": "warn", + "tsdoc/syntax": "warn", + "@azure/azure-sdk/ts-package-json-module": "off", + "@azure/azure-sdk/ts-package-json-files-required": "off", + "@azure/azure-sdk/ts-package-json-main-is-cjs": "off" + } +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/LICENSE b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/LICENSE new file mode 100644 index 0000000000..7d59347409 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/README.md b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/README.md new file mode 100644 index 0000000000..f49c331f94 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/README.md @@ -0,0 +1,60 @@ +# Azure ManagedIdentity client library for JavaScript + +This package contains an isomorphic SDK (runs both in Node.js and in browsers) for Azure ManagedIdentity client. + +Arm Managed Identity Provider management API. + +[Package (NPM)](https://www.npmjs.com/package/@azure/arm-managedIdentity) | +[API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-managedIdentity) | + +## Getting started + +### Currently supported environments + +- [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) +- Latest versions of Safari, Chrome, Edge and Firefox. + +See our [support policy](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) for more details. + +### Prerequisites + +- An [Azure subscription][azure_sub]. + + + + +### JavaScript Bundle +To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our [bundling documentation](https://aka.ms/AzureSDKBundling). + +## Key concepts + +### ManagedIdentityClient + +`ManagedIdentityClient` is the primary interface for developers using the Azure ManagedIdentity client library. Explore the methods on this client object to understand the different features of the Azure ManagedIdentity service that you can access. + +## Troubleshooting + +### Logging + +Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`: + +```javascript +const { setLogLevel } = require("@azure/logger"); +setLogLevel("info"); +``` + +For more detailed instructions on how to enable logs, you can look at the [@azure/logger package docs](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger). + + +## Contributing + +If you'd like to contribute to this library, please read the [contributing guide](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) to learn more about how to build and test the code. + +## Related projects + +- [Microsoft Azure SDK for JavaScript](https://github.com/Azure/azure-sdk-for-js) + +[azure_sub]: https://azure.microsoft.com/free/ +[azure_portal]: https://portal.azure.com +[azure_identity]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity +[defaultazurecredential]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity#defaultazurecredential diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/api-extractor.json b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/api-extractor.json new file mode 100644 index 0000000000..229071c648 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/api-extractor.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "mainEntryPointFilePath": "./dist/esm/index.d.ts", + "docModel": { "enabled": true }, + "apiReport": { "enabled": true, "reportFolder": "./review" }, + "dtsRollup": { + "enabled": true, + "untrimmedFilePath": "", + "publicTrimmedFilePath": "./types/arm-managedIdentity.d.ts" + }, + "messages": { + "tsdocMessageReporting": { "default": { "logLevel": "none" } }, + "extractorMessageReporting": { + "ae-missing-release-tag": { "logLevel": "none" }, + "ae-unresolved-link": { "logLevel": "none" } + } + } +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/package.json b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/package.json new file mode 100644 index 0000000000..30cd1b3e35 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/package.json @@ -0,0 +1,54 @@ +{ + "name": "@azure/arm-managedIdentity", + "version": "1.0.0", + "description": "Azure Arm ManagedIdentity Test Service", + "engines": { + "node": ">=18.0.0" + }, + "sideEffects": false, + "autoPublish": false, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/index.ts", + "./api": "./src/api/index.ts", + "./models": "./src/models/index.ts" + }, + "dialects": ["esm", "commonjs"], + "esmDialects": ["browser", "react-native"], + "selfLink": false + }, + "type": "module", + "keywords": ["node", "azure", "cloud", "typescript", "browser", "isomorphic"], + "author": "Microsoft Corporation", + "license": "MIT", + "files": ["dist", "README.md", "LICENSE", "review/*", "CHANGELOG.md"], + "dependencies": { + "@azure-rest/core-client": "^2.1.0", + "@azure/core-auth": "^1.6.0", + "@azure/core-rest-pipeline": "^1.5.0", + "@azure/logger": "^1.0.0", + "tslib": "^2.6.2" + }, + "devDependencies": { + "dotenv": "^16.0.0", + "@microsoft/api-extractor": "^7.40.3", + "@types/node": "^18.0.0", + "eslint": "^8.55.0", + "prettier": "^3.2.5", + "rimraf": "^5.0.5", + "mkdirp": "^3.0.1", + "typescript": "~5.5.3", + "tshy": "1.11.1" + }, + "scripts": { + "clean": "rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "extract-api": "rimraf review && mkdirp ./review && api-extractor run --local", + "pack": "npm pack 2>&1", + "lint": "eslint package.json api-extractor.json src --ext .ts", + "lint:fix": "eslint package.json api-extractor.json src --ext .ts --fix --fix-type [problem,suggestion]", + "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\" \"samples-dev/**/*.ts\"", + "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"*.{js,json}\" \"test/**/*.ts\" \"samples-dev/**/*.ts\"", + "build": "npm run clean && tshy && npm run extract-api" + } +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/rollup.config.js b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/rollup.config.js new file mode 100644 index 0000000000..61251d7a8d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/rollup.config.js @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import nodeResolve from "@rollup/plugin-node-resolve"; +import cjs from "@rollup/plugin-commonjs"; +import sourcemaps from "rollup-plugin-sourcemaps"; +import multiEntry from "@rollup/plugin-multi-entry"; +import json from "@rollup/plugin-json"; + +import nodeBuiltins from "builtin-modules"; + +// #region Warning Handler + +/** + * A function that can determine whether a rollup warning should be ignored. If + * the function returns `true`, then the warning will not be displayed. + */ + +function ignoreNiseSinonEval(warning) { + return ( + warning.code === "EVAL" && + warning.id && + (warning.id.includes("node_modules/nise") || + warning.id.includes("node_modules/sinon")) === true + ); +} + +function ignoreChaiCircularDependency(warning) { + return ( + warning.code === "CIRCULAR_DEPENDENCY" && + warning.importer && + warning.importer.includes("node_modules/chai") === true + ); +} + +const warningInhibitors = [ignoreChaiCircularDependency, ignoreNiseSinonEval]; + +/** + * Construct a warning handler for the shared rollup configuration + * that ignores certain warnings that are not relevant to testing. + */ +function makeOnWarnForTesting() { + return (warning, warn) => { + // If every inhibitor returns false (i.e. no inhibitors), then show the warning + if (warningInhibitors.every((inhib) => !inhib(warning))) { + warn(warning); + } + }; +} + +// #endregion + +function makeBrowserTestConfig() { + const config = { + input: { + include: ["dist-esm/test/**/*.spec.js"], + exclude: ["dist-esm/test/**/node/**"], + }, + output: { + file: `dist-test/index.browser.js`, + format: "umd", + sourcemap: true, + }, + preserveSymlinks: false, + plugins: [ + multiEntry({ exports: false }), + nodeResolve({ + mainFields: ["module", "browser"], + }), + cjs(), + json(), + sourcemaps(), + //viz({ filename: "dist-test/browser-stats.html", sourcemap: true }) + ], + onwarn: makeOnWarnForTesting(), + // Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0, + // rollup started respecting the "sideEffects" field in package.json. Since + // our package.json sets "sideEffects=false", this also applies to test + // code, which causes all tests to be removed by tree-shaking. + treeshake: false, + }; + + return config; +} + +const defaultConfigurationOptions = { + disableBrowserBundle: false, +}; + +export function makeConfig(pkg, options) { + options = { + ...defaultConfigurationOptions, + ...(options || {}), + }; + + const baseConfig = { + // Use the package's module field if it has one + input: pkg["module"] || "dist-esm/src/index.js", + external: [ + ...nodeBuiltins, + ...Object.keys(pkg.dependencies), + ...Object.keys(pkg.devDependencies), + ], + output: { file: "dist/index.js", format: "cjs", sourcemap: true }, + preserveSymlinks: false, + plugins: [sourcemaps(), nodeResolve()], + }; + + const config = [baseConfig]; + + if (!options.disableBrowserBundle) { + config.push(makeBrowserTestConfig()); + } + + return config; +} + +export default makeConfig(require("./package.json")); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/index.ts new file mode 100644 index 0000000000..7f14c275a5 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/index.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + createManagedIdentity, + ManagedIdentityClientOptionalParams, + ManagedIdentityContext, +} from "./managedIdentityContext.js"; +export { + get, + createWithSystemAssigned, + updateWithUserAssignedAndSystemAssigned, +} from "./operations.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/managedIdentityContext.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/managedIdentityContext.ts new file mode 100644 index 0000000000..6d5f1e3e4c --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/managedIdentityContext.ts @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { ManagedIdentityContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +/** Optional parameters for the client. */ +export interface ManagedIdentityClientOptionalParams extends ClientOptions { + /** The API version to use for this operation. */ + apiVersion?: string; +} + +export { ManagedIdentityContext } from "../rest/index.js"; + +/** Arm Managed Identity Provider management API. */ +export function createManagedIdentity( + options: ManagedIdentityClientOptionalParams = {}, +): ManagedIdentityContext { + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api` + : "azsdk-js-api"; + + const clientContext = getClient({ + ...options, + userAgentOptions: { userAgentPrefix }, + }); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/operations.ts new file mode 100644 index 0000000000..dfae8d22a4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/api/operations.ts @@ -0,0 +1,321 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + managedIdentityTrackedResourcePropertiesSerializer, + managedServiceIdentitySerializer, + ManagedIdentityTrackedResource, +} from "../models/models.js"; +import { + CreateWithSystemAssigned200Response, + CreateWithSystemAssigned201Response, + CreateWithSystemAssignedDefaultResponse, + Get200Response, + GetDefaultResponse, + isUnexpected, + ManagedIdentityContext as Client, + UpdateWithUserAssignedAndSystemAssigned200Response, + UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, + createRestError, +} from "@azure-rest/core-client"; +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { + GetOptionalParams, + CreateWithSystemAssignedOptionalParams, + UpdateWithUserAssignedAndSystemAssignedOptionalParams, +} from "../models/options.js"; + +export function _getSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + options: GetOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + ) + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _getDeserialize( + result: Get200Response | GetDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + tags: result.body["tags"], + location: result.body["location"], + id: result.body["id"], + name: result.body["name"], + type: result.body["type"], + systemData: !result.body.systemData + ? undefined + : { + createdBy: result.body.systemData?.["createdBy"], + createdByType: result.body.systemData?.["createdByType"], + createdAt: + result.body.systemData?.["createdAt"] !== undefined + ? new Date(result.body.systemData?.["createdAt"]) + : undefined, + lastModifiedBy: result.body.systemData?.["lastModifiedBy"], + lastModifiedByType: result.body.systemData?.["lastModifiedByType"], + lastModifiedAt: + result.body.systemData?.["lastModifiedAt"] !== undefined + ? new Date(result.body.systemData?.["lastModifiedAt"]) + : undefined, + }, + properties: !result.body.properties + ? undefined + : { provisioningState: result.body.properties?.["provisioningState"] }, + identity: !result.body.identity + ? undefined + : { + principalId: result.body.identity?.["principalId"], + tenantId: result.body.identity?.["tenantId"], + type: result.body.identity?.["type"], + userAssignedIdentities: + result.body.identity?.["userAssignedIdentities"], + }, + }; +} + +/** Get a ManagedIdentityTrackedResource */ +export async function get( + context: Client, + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + options: GetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend( + context, + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + options, + ); + return _getDeserialize(result); +} + +export function _createWithSystemAssignedSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + resource: ManagedIdentityTrackedResource, + options: CreateWithSystemAssignedOptionalParams = { requestOptions: {} }, +): StreamableMethod< + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse +> { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + ) + .put({ + ...operationOptionsToRequestParameters(options), + body: { + tags: !resource.tags + ? resource.tags + : (serializeRecord(resource.tags as any) as any), + location: resource["location"], + properties: !resource.properties + ? resource.properties + : managedIdentityTrackedResourcePropertiesSerializer( + resource.properties, + ), + identity: !resource.identity + ? resource.identity + : managedServiceIdentitySerializer(resource.identity), + }, + }); +} + +export async function _createWithSystemAssignedDeserialize( + result: + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + tags: result.body["tags"], + location: result.body["location"], + id: result.body["id"], + name: result.body["name"], + type: result.body["type"], + systemData: !result.body.systemData + ? undefined + : { + createdBy: result.body.systemData?.["createdBy"], + createdByType: result.body.systemData?.["createdByType"], + createdAt: + result.body.systemData?.["createdAt"] !== undefined + ? new Date(result.body.systemData?.["createdAt"]) + : undefined, + lastModifiedBy: result.body.systemData?.["lastModifiedBy"], + lastModifiedByType: result.body.systemData?.["lastModifiedByType"], + lastModifiedAt: + result.body.systemData?.["lastModifiedAt"] !== undefined + ? new Date(result.body.systemData?.["lastModifiedAt"]) + : undefined, + }, + properties: !result.body.properties + ? undefined + : { provisioningState: result.body.properties?.["provisioningState"] }, + identity: !result.body.identity + ? undefined + : { + principalId: result.body.identity?.["principalId"], + tenantId: result.body.identity?.["tenantId"], + type: result.body.identity?.["type"], + userAssignedIdentities: + result.body.identity?.["userAssignedIdentities"], + }, + }; +} + +/** Create a ManagedIdentityTrackedResource */ +export async function createWithSystemAssigned( + context: Client, + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + resource: ManagedIdentityTrackedResource, + options: CreateWithSystemAssignedOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createWithSystemAssignedSend( + context, + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + resource, + options, + ); + return _createWithSystemAssignedDeserialize(result); +} + +export function _updateWithUserAssignedAndSystemAssignedSend( + context: Client, + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + properties: ManagedIdentityTrackedResource, + options: UpdateWithUserAssignedAndSystemAssignedOptionalParams = { + requestOptions: {}, + }, +): StreamableMethod< + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse +> { + return context + .path( + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + ) + .patch({ + ...operationOptionsToRequestParameters(options), + body: { + tags: !properties.tags + ? properties.tags + : (serializeRecord(properties.tags as any) as any), + location: properties["location"], + properties: !properties.properties + ? properties.properties + : managedIdentityTrackedResourcePropertiesSerializer( + properties.properties, + ), + identity: !properties.identity + ? properties.identity + : managedServiceIdentitySerializer(properties.identity), + }, + }); +} + +export async function _updateWithUserAssignedAndSystemAssignedDeserialize( + result: + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + tags: result.body["tags"], + location: result.body["location"], + id: result.body["id"], + name: result.body["name"], + type: result.body["type"], + systemData: !result.body.systemData + ? undefined + : { + createdBy: result.body.systemData?.["createdBy"], + createdByType: result.body.systemData?.["createdByType"], + createdAt: + result.body.systemData?.["createdAt"] !== undefined + ? new Date(result.body.systemData?.["createdAt"]) + : undefined, + lastModifiedBy: result.body.systemData?.["lastModifiedBy"], + lastModifiedByType: result.body.systemData?.["lastModifiedByType"], + lastModifiedAt: + result.body.systemData?.["lastModifiedAt"] !== undefined + ? new Date(result.body.systemData?.["lastModifiedAt"]) + : undefined, + }, + properties: !result.body.properties + ? undefined + : { provisioningState: result.body.properties?.["provisioningState"] }, + identity: !result.body.identity + ? undefined + : { + principalId: result.body.identity?.["principalId"], + tenantId: result.body.identity?.["tenantId"], + type: result.body.identity?.["type"], + userAssignedIdentities: + result.body.identity?.["userAssignedIdentities"], + }, + }; +} + +/** Update a ManagedIdentityTrackedResource */ +export async function updateWithUserAssignedAndSystemAssigned( + context: Client, + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + properties: ManagedIdentityTrackedResource, + options: UpdateWithUserAssignedAndSystemAssignedOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _updateWithUserAssignedAndSystemAssignedSend( + context, + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + properties, + options, + ); + return _updateWithUserAssignedAndSystemAssignedDeserialize(result); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/helpers/serializerHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/helpers/serializerHelpers.ts new file mode 100644 index 0000000000..332381cdb6 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/helpers/serializerHelpers.ts @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export function serializeRecord< + T extends string | number | boolean | Date | null, + R, +>(item: Record): Record; +export function serializeRecord( + item: Record, + serializer: (item: T) => R, +): Record; +export function serializeRecord( + item: Record, + serializer?: (item: T) => R, +): Record { + return Object.keys(item).reduce( + (acc, key) => { + if (isSupportedRecordType(item[key])) { + acc[key] = item[key] as any; + } else if (serializer) { + const value = item[key]; + if (value !== undefined) { + acc[key] = serializer(value); + } + } else { + console.warn(`Don't know how to serialize ${item[key]}`); + acc[key] = item[key] as any; + } + return acc; + }, + {} as Record, + ); +} + +function isSupportedRecordType(t: any) { + return ( + ["number", "string", "boolean", "null"].includes(typeof t) || + t instanceof Date + ); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.ts new file mode 100644 index 0000000000..8cf73519b1 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/index.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + ManagedIdentityClient, + ManagedIdentityClientOptionalParams, +} from "./managedIdentityClient.js"; +export { + Resource, + SystemData, + KnownCreatedByType, + CreatedByType, + TrackedResource, + ManagedIdentityTrackedResource, + ManagedIdentityTrackedResourceProperties, + ManagedServiceIdentity, + KnownManagedServiceIdentityType, + ManagedServiceIdentityType, + UserAssignedIdentity, + ErrorResponse, + ErrorDetail, + ErrorAdditionalInfo, + Versions, + GetOptionalParams, + CreateWithSystemAssignedOptionalParams, + UpdateWithUserAssignedAndSystemAssignedOptionalParams, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/logger.ts new file mode 100644 index 0000000000..f5ddcfd9e5 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("arm-managedIdentity"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/managedIdentityClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/managedIdentityClient.ts new file mode 100644 index 0000000000..ccda4a292d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/managedIdentityClient.ts @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Pipeline } from "@azure/core-rest-pipeline"; +import { ManagedIdentityTrackedResource } from "./models/models.js"; +import { + GetOptionalParams, + CreateWithSystemAssignedOptionalParams, + UpdateWithUserAssignedAndSystemAssignedOptionalParams, +} from "./models/options.js"; +import { + createManagedIdentity, + ManagedIdentityClientOptionalParams, + ManagedIdentityContext, + get, + createWithSystemAssigned, + updateWithUserAssignedAndSystemAssigned, +} from "./api/index.js"; + +export { ManagedIdentityClientOptionalParams } from "./api/managedIdentityContext.js"; + +export class ManagedIdentityClient { + private _client: ManagedIdentityContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + /** Arm Managed Identity Provider management API. */ + constructor(options: ManagedIdentityClientOptionalParams = {}) { + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : "azsdk-js-client"; + + this._client = createManagedIdentity({ + ...options, + userAgentOptions: { userAgentPrefix }, + }); + this.pipeline = this._client.pipeline; + } + + /** Get a ManagedIdentityTrackedResource */ + get( + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + options: GetOptionalParams = { requestOptions: {} }, + ): Promise { + return get( + this._client, + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + options, + ); + } + + /** Create a ManagedIdentityTrackedResource */ + createWithSystemAssigned( + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + resource: ManagedIdentityTrackedResource, + options: CreateWithSystemAssignedOptionalParams = { requestOptions: {} }, + ): Promise { + return createWithSystemAssigned( + this._client, + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + resource, + options, + ); + } + + /** Update a ManagedIdentityTrackedResource */ + updateWithUserAssignedAndSystemAssigned( + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + properties: ManagedIdentityTrackedResource, + options: UpdateWithUserAssignedAndSystemAssignedOptionalParams = { + requestOptions: {}, + }, + ): Promise { + return updateWithUserAssignedAndSystemAssigned( + this._client, + subscriptionId, + resourceGroupName, + managedIdentityTrackedResourceName, + properties, + options, + ); + } +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/index.ts new file mode 100644 index 0000000000..94a83be472 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/index.ts @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { + Resource, + SystemData, + KnownCreatedByType, + CreatedByType, + TrackedResource, + ManagedIdentityTrackedResource, + ManagedIdentityTrackedResourceProperties, + ManagedServiceIdentity, + KnownManagedServiceIdentityType, + ManagedServiceIdentityType, + UserAssignedIdentity, + ErrorResponse, + ErrorDetail, + ErrorAdditionalInfo, + Versions, +} from "./models.js"; +export { + GetOptionalParams, + CreateWithSystemAssignedOptionalParams, + UpdateWithUserAssignedAndSystemAssignedOptionalParams, +} from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/models.ts new file mode 100644 index 0000000000..b3f3465cc4 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/models.ts @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { serializeRecord } from "../helpers/serializerHelpers.js"; +import { + TrackedResource as TrackedResourceRest, + ManagedIdentityTrackedResource as ManagedIdentityTrackedResourceRest, + ManagedServiceIdentity as ManagedServiceIdentityRest, +} from "../rest/index.js"; + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface Resource { + /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ + readonly id?: string; + /** The name of the resource */ + readonly name?: string; + /** The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" */ + readonly type?: string; + /** Azure Resource Manager metadata containing createdBy and modifiedBy information. */ + readonly systemData?: SystemData; +} + +export function resourceSerializer(item: Resource) { + return item as any; +} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemData { + /** The identity that created the resource. */ + createdBy?: string; + /** The type of identity that created the resource. */ + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** The type of identity that last modified the resource. */ + lastModifiedByType?: CreatedByType; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: Date; +} + +/** Known values of {@link CreatedByType} that the service accepts. */ +export enum KnownCreatedByType { + /** User */ + User = "User", + /** Application */ + Application = "Application", + /** ManagedIdentity */ + ManagedIdentity = "ManagedIdentity", + /** Key */ + Key = "Key", +} + +/** + * The kind of entity that created the resource. \ + * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **User** \ + * **Application** \ + * **ManagedIdentity** \ + * **Key** + */ +export type CreatedByType = string; + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResource extends Resource { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +export function trackedResourceSerializer( + item: TrackedResource, +): TrackedResourceRest { + return { + tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), + location: item["location"], + }; +} + +/** Concrete tracked resource types can be created by aliasing this type using a specific property type. */ +export interface ManagedIdentityTrackedResource extends TrackedResource { + /** The resource-specific properties for this resource. */ + properties?: ManagedIdentityTrackedResourceProperties; + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentity; +} + +export function managedIdentityTrackedResourceSerializer( + item: ManagedIdentityTrackedResource, +): ManagedIdentityTrackedResourceRest { + return { + tags: !item.tags ? item.tags : (serializeRecord(item.tags as any) as any), + location: item["location"], + properties: !item.properties + ? item.properties + : managedIdentityTrackedResourcePropertiesSerializer(item.properties), + identity: !item.identity + ? item.identity + : managedServiceIdentitySerializer(item.identity), + }; +} + +/** Managed Identity Arm Resource Properties. */ +export interface ManagedIdentityTrackedResourceProperties { + /** The status of the last operation. */ + readonly provisioningState: string; +} + +export function managedIdentityTrackedResourcePropertiesSerializer( + item: ManagedIdentityTrackedResourceProperties, +) { + return item as any; +} + +/** Managed service identity (system assigned and/or user assigned identities) */ +export interface ManagedServiceIdentity { + /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly principalId?: string; + /** The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly tenantId?: string; + /** The type of managed identity assigned to this resource. */ + type: ManagedServiceIdentityType; + /** The identities assigned to this resource by the user. */ + userAssignedIdentities?: Record; +} + +export function managedServiceIdentitySerializer( + item: ManagedServiceIdentity, +): ManagedServiceIdentityRest { + return { + type: item["type"], + userAssignedIdentities: !item.userAssignedIdentities + ? item.userAssignedIdentities + : (serializeRecord( + item.userAssignedIdentities as any, + userAssignedIdentitySerializer, + ) as any), + }; +} + +/** Known values of {@link ManagedServiceIdentityType} that the service accepts. */ +export enum KnownManagedServiceIdentityType { + /** None */ + None = "None", + /** SystemAssigned */ + SystemAssigned = "SystemAssigned", + /** UserAssigned */ + UserAssigned = "UserAssigned", + /** SystemAssigned,UserAssigned */ + "SystemAssigned,UserAssigned" = "SystemAssigned,UserAssigned", +} + +/** + * Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). \ + * {@link KnownManagedServiceIdentityType} can be used interchangeably with ManagedServiceIdentityType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **None** \ + * **SystemAssigned** \ + * **UserAssigned** \ + * **SystemAssigned,UserAssigned** + */ +export type ManagedServiceIdentityType = string; + +/** User assigned identity properties */ +export interface UserAssignedIdentity { + /** The principal ID of the assigned identity. */ + readonly principalId?: string; + /** The client ID of the assigned identity. */ + readonly clientId?: string; +} + +export function userAssignedIdentitySerializer(item: UserAssignedIdentity) { + return item as any; +} + +/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. */ +export interface ErrorResponse { + /** The error object. */ + error?: ErrorDetail; +} + +/** The error detail. */ +export interface ErrorDetail { + /** The error code. */ + readonly code?: string; + /** The error message. */ + readonly message?: string; + /** The error target. */ + readonly target?: string; + /** The error details. */ + readonly details?: ErrorDetail[]; + /** The error additional info. */ + readonly additionalInfo?: ErrorAdditionalInfo[]; +} + +/** The resource management error additional info. */ +export interface ErrorAdditionalInfo { + /** The additional info type. */ + readonly type?: string; + /** The additional info. */ + readonly info?: Record; +} + +/** Azure API versions. */ +export type Versions = "2023-12-01-preview"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/options.ts new file mode 100644 index 0000000000..e712349865 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/models/options.ts @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +/** Optional parameters. */ +export interface GetOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface CreateWithSystemAssignedOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface UpdateWithUserAssignedAndSystemAssignedOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..33953f089d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/clientDefinitions.ts @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + GetParameters, + CreateWithSystemAssignedParameters, + UpdateWithUserAssignedAndSystemAssignedParameters, +} from "./parameters.js"; +import { + Get200Response, + GetDefaultResponse, + CreateWithSystemAssigned200Response, + CreateWithSystemAssigned201Response, + CreateWithSystemAssignedDefaultResponse, + UpdateWithUserAssignedAndSystemAssigned200Response, + UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +} from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface Get { + /** Get a ManagedIdentityTrackedResource */ + get( + options?: GetParameters, + ): StreamableMethod; + /** Create a ManagedIdentityTrackedResource */ + put( + options: CreateWithSystemAssignedParameters, + ): StreamableMethod< + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse + >; + /** Update a ManagedIdentityTrackedResource */ + patch( + options: UpdateWithUserAssignedAndSystemAssignedParameters, + ): StreamableMethod< + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse + >; +} + +export interface Routes { + /** Resource for '/subscriptions/\{subscriptionId\}/resourceGroups/\{resourceGroupName\}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/\{managedIdentityTrackedResourceName\}' has methods for the following verbs: get, put, patch */ + ( + path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}", + subscriptionId: string, + resourceGroupName: string, + managedIdentityTrackedResourceName: string, + ): Get; +} + +export type ManagedIdentityContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/index.ts new file mode 100644 index 0000000000..93925a1158 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/index.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import ManagedIdentityClient from "./managedIdentityClient.js"; + +export * from "./managedIdentityClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./isUnexpected.js"; +export * from "./models.js"; +export * from "./outputModels.js"; + +export default ManagedIdentityClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/isUnexpected.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/isUnexpected.ts new file mode 100644 index 0000000000..032d6276c7 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/isUnexpected.ts @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + Get200Response, + GetDefaultResponse, + CreateWithSystemAssigned200Response, + CreateWithSystemAssigned201Response, + CreateWithSystemAssignedDefaultResponse, + UpdateWithUserAssignedAndSystemAssigned200Response, + UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +} from "./responses.js"; + +const responseMap: Record = { + "GET /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}": + ["200"], + "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}": + ["200", "201"], + "PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Models.CommonTypes.ManagedIdentity/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}": + ["200"], +}; + +export function isUnexpected( + response: Get200Response | GetDefaultResponse, +): response is GetDefaultResponse; +export function isUnexpected( + response: + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse, +): response is CreateWithSystemAssignedDefaultResponse; +export function isUnexpected( + response: + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +): response is UpdateWithUserAssignedAndSystemAssignedDefaultResponse; +export function isUnexpected( + response: + | Get200Response + | GetDefaultResponse + | CreateWithSystemAssigned200Response + | CreateWithSystemAssigned201Response + | CreateWithSystemAssignedDefaultResponse + | UpdateWithUserAssignedAndSystemAssigned200Response + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse, +): response is + | GetDefaultResponse + | CreateWithSystemAssignedDefaultResponse + | UpdateWithUserAssignedAndSystemAssignedDefaultResponse { + const lroOriginal = response.headers["x-ms-original-url"]; + const url = new URL(lroOriginal ?? response.request.url); + const method = response.request.method; + let pathDetails = responseMap[`${method} ${url.pathname}`]; + if (!pathDetails) { + pathDetails = getParametrizedPathSuccess(method, url.pathname); + } + return !pathDetails.includes(response.status); +} + +function getParametrizedPathSuccess(method: string, path: string): string[] { + const pathParts = path.split("/"); + + // Traverse list to match the longest candidate + // matchedLen: the length of candidate path + // matchedValue: the matched status code array + let matchedLen = -1, + matchedValue: string[] = []; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(responseMap)) { + // Extracting the path from the map key which is in format + // GET /path/foo + if (!key.startsWith(method)) { + continue; + } + const candidatePath = getPathFromMapKey(key); + // Get each part of the url path + const candidateParts = candidatePath.split("/"); + + // track if we have found a match to return the values found. + let found = true; + for ( + let i = candidateParts.length - 1, j = pathParts.length - 1; + i >= 1 && j >= 1; + i--, j-- + ) { + if ( + candidateParts[i]?.startsWith("{") && + candidateParts[i]?.indexOf("}") !== -1 + ) { + const start = candidateParts[i]!.indexOf("}") + 1, + end = candidateParts[i]?.length; + // If the current part of the candidate is a "template" part + // Try to use the suffix of pattern to match the path + // {guid} ==> $ + // {guid}:export ==> :export$ + const isMatched = new RegExp( + `${candidateParts[i]?.slice(start, end)}`, + ).test(pathParts[j] || ""); + + if (!isMatched) { + found = false; + break; + } + continue; + } + + // If the candidate part is not a template and + // the parts don't match mark the candidate as not found + // to move on with the next candidate path. + if (candidateParts[i] !== pathParts[j]) { + found = false; + break; + } + } + + // We finished evaluating the current candidate parts + // Update the matched value if and only if we found the longer pattern + if (found && candidatePath.length > matchedLen) { + matchedLen = candidatePath.length; + matchedValue = value; + } + } + + return matchedValue; +} + +function getPathFromMapKey(mapKey: string): string { + const pathStart = mapKey.indexOf("/"); + return mapKey.slice(pathStart); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/managedIdentityClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/managedIdentityClient.ts new file mode 100644 index 0000000000..6366bb3a6d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/managedIdentityClient.ts @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { ManagedIdentityContext } from "./clientDefinitions.js"; + +/** The optional parameters for the client */ +export interface ManagedIdentityContextOptions extends ClientOptions { + /** The api version option of the client */ + apiVersion?: string; +} + +/** + * Initialize a new instance of `ManagedIdentityContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient({ + apiVersion = "2023-12-01-preview", + ...options +}: ManagedIdentityContextOptions = {}): ManagedIdentityContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? `https://management.azure.com`; + const userAgentInfo = `azsdk-js-arm-managedIdentity/1.0.0`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + const client = getClient(endpointUrl, options) as ManagedIdentityContext; + + client.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + client.pipeline.addPolicy({ + name: "ClientApiVersionPolicy", + sendRequest: (req, next) => { + // Use the apiVersion defined in request url directly + // Append one if there is no apiVersion and we have one at client options + const url = new URL(req.url); + if (!url.searchParams.get("api-version") && apiVersion) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/models.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/models.ts new file mode 100644 index 0000000000..45de9752b0 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/models.ts @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** Concrete tracked resource types can be created by aliasing this type using a specific property type. */ +export interface ManagedIdentityTrackedResource extends TrackedResource { + /** The resource-specific properties for this resource. */ + properties?: ManagedIdentityTrackedResourceProperties; + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentity; +} + +/** Managed Identity Arm Resource Properties. */ +export interface ManagedIdentityTrackedResourceProperties {} + +/** Managed service identity (system assigned and/or user assigned identities) */ +export interface ManagedServiceIdentity { + /** + * The type of managed identity assigned to this resource. + * + * Possible values: "None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned" + */ + type: ManagedServiceIdentityType; + /** The identities assigned to this resource by the user. */ + userAssignedIdentities?: Record; +} + +/** User assigned identity properties */ +export interface UserAssignedIdentity {} + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResource extends Resource { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface Resource {} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemData { + /** The identity that created the resource. */ + createdBy?: string; + /** + * The type of identity that created the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + createdByType?: CreatedByType; + /** The timestamp of resource creation (UTC). */ + createdAt?: Date | string; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** + * The type of identity that last modified the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + lastModifiedByType?: CreatedByType; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: Date | string; +} + +/** The resource model definition for an Azure Resource Manager resource with an etag. */ +export interface AzureEntityResource extends Resource {} + +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ +export interface ProxyResource extends Resource {} + +/** The base extension resource. */ +export interface ExtensionResource extends Resource {} + +/** A private link resource. */ +export interface PrivateLinkResource extends Resource { + /** Resource properties. */ + properties?: PrivateLinkResourceProperties; +} + +/** Properties of a private link resource. */ +export interface PrivateLinkResourceProperties { + /** The private link resource private link DNS zone name. */ + requiredZoneNames?: string[]; +} + +/** The private endpoint connection resource */ +export interface PrivateEndpointConnection extends Resource { + /** The private endpoint connection properties */ + properties?: PrivateEndpointConnectionProperties; +} + +/** Properties of the private endpoint connection. */ +export interface PrivateEndpointConnectionProperties { + /** The private endpoint resource. */ + privateEndpoint?: PrivateEndpoint; + /** A collection of information about the state of the connection between service consumer and provider. */ + privateLinkServiceConnectionState: PrivateLinkServiceConnectionState; +} + +/** The Private Endpoint resource. */ +export interface PrivateEndpoint {} + +/** A collection of information about the state of the connection between service consumer and provider. */ +export interface PrivateLinkServiceConnectionState { + /** + * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + * + * Possible values: "Pending", "Approved", "Rejected" + */ + status?: PrivateEndpointServiceConnectionStatus; + /** The reason for approval/rejection of the connection. */ + description?: string; + /** A message indicating if changes on the service provider require any updates on the consumer. */ + actionsRequired?: string; +} + +/** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ +export interface ResourceModelWithAllowedPropertySet extends TrackedResource { + /** + * The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. + * If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. + */ + managedBy?: string; + /** + * Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. + * If supported, the resource provider must validate and persist this value. + */ + kind?: string; + /** + * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. + * Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), + * If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + */ + eTag?: string; + identity?: Identity; + sku?: Sku; + plan?: Plan; +} + +/** Identity for the resource. */ +export interface Identity { + /** The identity type. */ + type?: ResourceIdentityType; +} + +/** The resource model definition representing SKU */ +export interface Sku { + /** The name of the SKU. Ex - P3. It is typically a letter+number code */ + name: string; + /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ + tier?: SkuTier; + /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ + size?: string; + /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ + family?: string; + /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ + capacity?: number; +} + +/** Plan for the resource. */ +export interface Plan { + /** A user defined name of the 3rd Party Artifact that is being procured. */ + name: string; + /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ + publisher: string; + /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ + product: string; + /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ + promotionCode?: string; + /** The version of the desired product/artifact. */ + version?: string; +} + +/** Alias for ManagedServiceIdentityType */ +export type ManagedServiceIdentityType = string; +/** Alias for CreatedByType */ +export type CreatedByType = string; +/** Alias for PrivateEndpointServiceConnectionStatus */ +export type PrivateEndpointServiceConnectionStatus = string; +/** Alias for PrivateEndpointConnectionProvisioningState */ +export type PrivateEndpointConnectionProvisioningState = string; +/** Alias for ResourceIdentityType */ +export type ResourceIdentityType = "SystemAssigned"; +/** Alias for SkuTier */ +export type SkuTier = "Free" | "Basic" | "Standard" | "Premium"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/outputModels.ts new file mode 100644 index 0000000000..0a8e5aaf75 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/outputModels.ts @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** Concrete tracked resource types can be created by aliasing this type using a specific property type. */ +export interface ManagedIdentityTrackedResourceOutput + extends TrackedResourceOutput { + /** The resource-specific properties for this resource. */ + properties?: ManagedIdentityTrackedResourcePropertiesOutput; + /** The managed service identities assigned to this resource. */ + identity?: ManagedServiceIdentityOutput; +} + +/** Managed Identity Arm Resource Properties. */ +export interface ManagedIdentityTrackedResourcePropertiesOutput { + /** The status of the last operation. */ + readonly provisioningState: string; +} + +/** Managed service identity (system assigned and/or user assigned identities) */ +export interface ManagedServiceIdentityOutput { + /** The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly principalId?: string; + /** The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. */ + readonly tenantId?: string; + /** + * The type of managed identity assigned to this resource. + * + * Possible values: "None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned" + */ + type: ManagedServiceIdentityTypeOutput; + /** The identities assigned to this resource by the user. */ + userAssignedIdentities?: Record; +} + +/** User assigned identity properties */ +export interface UserAssignedIdentityOutput { + /** The principal ID of the assigned identity. */ + readonly principalId?: string; + /** The client ID of the assigned identity. */ + readonly clientId?: string; +} + +/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */ +export interface TrackedResourceOutput extends ResourceOutput { + /** Resource tags. */ + tags?: Record; + /** The geo-location where the resource lives */ + location: string; +} + +/** Common fields that are returned in the response for all Azure Resource Manager resources */ +export interface ResourceOutput { + /** Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} */ + readonly id?: string; + /** The name of the resource */ + readonly name?: string; + /** The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" */ + readonly type?: string; + /** Azure Resource Manager metadata containing createdBy and modifiedBy information. */ + readonly systemData?: SystemDataOutput; +} + +/** Metadata pertaining to creation and last modification of the resource. */ +export interface SystemDataOutput { + /** The identity that created the resource. */ + createdBy?: string; + /** + * The type of identity that created the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + createdByType?: CreatedByTypeOutput; + /** The timestamp of resource creation (UTC). */ + createdAt?: string; + /** The identity that last modified the resource. */ + lastModifiedBy?: string; + /** + * The type of identity that last modified the resource. + * + * Possible values: "User", "Application", "ManagedIdentity", "Key" + */ + lastModifiedByType?: CreatedByTypeOutput; + /** The timestamp of resource last modification (UTC) */ + lastModifiedAt?: string; +} + +/** The resource model definition for an Azure Resource Manager resource with an etag. */ +export interface AzureEntityResourceOutput extends ResourceOutput { + /** Resource Etag. */ + readonly etag?: string; +} + +/** The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location */ +export interface ProxyResourceOutput extends ResourceOutput {} + +/** The base extension resource. */ +export interface ExtensionResourceOutput extends ResourceOutput {} + +/** A private link resource. */ +export interface PrivateLinkResourceOutput extends ResourceOutput { + /** Resource properties. */ + properties?: PrivateLinkResourcePropertiesOutput; +} + +/** Properties of a private link resource. */ +export interface PrivateLinkResourcePropertiesOutput { + /** The private link resource group id. */ + readonly groupId?: string; + /** The private link resource required member names. */ + readonly requiredMembers?: string[]; + /** The private link resource private link DNS zone name. */ + requiredZoneNames?: string[]; +} + +/** The private endpoint connection resource */ +export interface PrivateEndpointConnectionOutput extends ResourceOutput { + /** The private endpoint connection properties */ + properties?: PrivateEndpointConnectionPropertiesOutput; +} + +/** Properties of the private endpoint connection. */ +export interface PrivateEndpointConnectionPropertiesOutput { + /** The private endpoint resource. */ + privateEndpoint?: PrivateEndpointOutput; + /** A collection of information about the state of the connection between service consumer and provider. */ + privateLinkServiceConnectionState: PrivateLinkServiceConnectionStateOutput; + /** + * The provisioning state of the private endpoint connection resource. + * + * Possible values: "Succeeded", "Creating", "Deleting", "Failed" + */ + readonly provisioningState?: PrivateEndpointConnectionProvisioningStateOutput; +} + +/** The Private Endpoint resource. */ +export interface PrivateEndpointOutput { + /** The resource identifier for private endpoint */ + readonly id?: string; +} + +/** A collection of information about the state of the connection between service consumer and provider. */ +export interface PrivateLinkServiceConnectionStateOutput { + /** + * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + * + * Possible values: "Pending", "Approved", "Rejected" + */ + status?: PrivateEndpointServiceConnectionStatusOutput; + /** The reason for approval/rejection of the connection. */ + description?: string; + /** A message indicating if changes on the service provider require any updates on the consumer. */ + actionsRequired?: string; +} + +/** The resource model definition containing the full set of allowed properties for a resource. Except properties bag, there cannot be a top level property outside of this set. */ +export interface ResourceModelWithAllowedPropertySetOutput + extends TrackedResourceOutput { + /** + * The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another Azure resource. + * If this is present, complete mode deployment will not delete the resource if it is removed from the template since it is managed by another resource. + */ + managedBy?: string; + /** + * Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. + * If supported, the resource provider must validate and persist this value. + */ + kind?: string; + /** + * The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. + * Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), + * If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields. + */ + eTag?: string; + identity?: IdentityOutput; + sku?: SkuOutput; + plan?: PlanOutput; +} + +/** Identity for the resource. */ +export interface IdentityOutput { + /** The principal ID of resource identity. The value must be an UUID. */ + readonly principalId?: string; + /** The tenant ID of resource. The value must be an UUID. */ + readonly tenantId?: string; + /** The identity type. */ + type?: ResourceIdentityTypeOutput; +} + +/** The resource model definition representing SKU */ +export interface SkuOutput { + /** The name of the SKU. Ex - P3. It is typically a letter+number code */ + name: string; + /** This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. */ + tier?: SkuTierOutput; + /** The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. */ + size?: string; + /** If the service has different generations of hardware, for the same SKU, then that can be captured here. */ + family?: string; + /** If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. */ + capacity?: number; +} + +/** Plan for the resource. */ +export interface PlanOutput { + /** A user defined name of the 3rd Party Artifact that is being procured. */ + name: string; + /** The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic */ + publisher: string; + /** The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at the time of Data Market onboarding. */ + product: string; + /** A publisher provided promotion code as provisioned in Data Market for the said product/artifact. */ + promotionCode?: string; + /** The version of the desired product/artifact. */ + version?: string; +} + +/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. */ +export interface ErrorResponseOutput { + /** The error object. */ + error?: ErrorDetailOutput; +} + +/** The error detail. */ +export interface ErrorDetailOutput { + /** The error code. */ + readonly code?: string; + /** The error message. */ + readonly message?: string; + /** The error target. */ + readonly target?: string; + /** The error details. */ + readonly details?: Array; + /** The error additional info. */ + readonly additionalInfo?: Array; +} + +/** The resource management error additional info. */ +export interface ErrorAdditionalInfoOutput { + /** The additional info type. */ + readonly type?: string; + /** The additional info. */ + readonly info?: Record; +} + +/** Alias for ManagedServiceIdentityTypeOutput */ +export type ManagedServiceIdentityTypeOutput = string; +/** Alias for CreatedByTypeOutput */ +export type CreatedByTypeOutput = string; +/** Alias for PrivateEndpointServiceConnectionStatusOutput */ +export type PrivateEndpointServiceConnectionStatusOutput = string; +/** Alias for PrivateEndpointConnectionProvisioningStateOutput */ +export type PrivateEndpointConnectionProvisioningStateOutput = string; +/** Alias for ResourceIdentityTypeOutput */ +export type ResourceIdentityTypeOutput = "SystemAssigned"; +/** Alias for SkuTierOutput */ +export type SkuTierOutput = "Free" | "Basic" | "Standard" | "Premium"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/parameters.ts new file mode 100644 index 0000000000..cc6d20544a --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/parameters.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RequestParameters } from "@azure-rest/core-client"; +import { ManagedIdentityTrackedResource } from "./models.js"; + +export type GetParameters = RequestParameters; + +export interface CreateWithSystemAssignedBodyParam { + /** Resource create parameters. */ + body: ManagedIdentityTrackedResource; +} + +export type CreateWithSystemAssignedParameters = + CreateWithSystemAssignedBodyParam & RequestParameters; + +export interface UpdateWithUserAssignedAndSystemAssignedBodyParam { + /** The resource properties to be updated. */ + body: ManagedIdentityTrackedResource; +} + +export type UpdateWithUserAssignedAndSystemAssignedParameters = + UpdateWithUserAssignedAndSystemAssignedBodyParam & RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/responses.ts new file mode 100644 index 0000000000..23feb26f57 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/src/rest/responses.ts @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { + ManagedIdentityTrackedResourceOutput, + ErrorResponseOutput, +} from "./outputModels.js"; + +/** Azure operation completed successfully. */ +export interface Get200Response extends HttpResponse { + status: "200"; + body: ManagedIdentityTrackedResourceOutput; +} + +export interface GetDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponseOutput; +} + +/** Resource 'ManagedIdentityTrackedResource' update operation succeeded */ +export interface CreateWithSystemAssigned200Response extends HttpResponse { + status: "200"; + body: ManagedIdentityTrackedResourceOutput; +} + +/** Resource 'ManagedIdentityTrackedResource' create operation succeeded */ +export interface CreateWithSystemAssigned201Response extends HttpResponse { + status: "201"; + body: ManagedIdentityTrackedResourceOutput; +} + +export interface CreateWithSystemAssignedDefaultResponse extends HttpResponse { + status: string; + body: ErrorResponseOutput; +} + +/** Azure operation completed successfully. */ +export interface UpdateWithUserAssignedAndSystemAssigned200Response + extends HttpResponse { + status: "200"; + body: ManagedIdentityTrackedResourceOutput; +} + +export interface UpdateWithUserAssignedAndSystemAssignedDefaultResponse + extends HttpResponse { + status: string; + body: ErrorResponseOutput; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/tsconfig.json b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/tsconfig.json new file mode 100644 index 0000000000..84e3a770b1 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2017", + "module": "NodeNext", + "lib": [], + "declaration": true, + "declarationMap": true, + "inlineSources": true, + "sourceMap": true, + "importHelpers": true, + "strict": true, + "alwaysStrict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "NodeNext", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true + }, + "include": ["./src/**/*.ts"] +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/tspconfig.yaml new file mode 100644 index 0000000000..42a04266ba --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/models/common-types/managed-identity/tspconfig.yaml @@ -0,0 +1,17 @@ +emit: + - "@azure-tools/typespec-ts" +options: + "@azure-tools/typespec-ts": + "emitter-output-dir": "{project-root}" + generateMetadata: true + generateTest: false + addCredentials: false + azureSdkForJs: false + isTypeSpecTest: true + isModularLibrary: true + hierarchyClient: false + experimentalExtensibleEnums: true + packageDetails: + name: "@azure/arm-managedIdentity" + description: "Azure Arm ManagedIdentity Test Service" + version: "1.0.0"