From 4083e03685eaf4c5f90938796d8366f2e5acbe53 Mon Sep 17 00:00:00 2001 From: ZiWei Chen <98569699+kazrael2119@users.noreply.github.com> Date: Wed, 20 Nov 2024 11:14:53 +0800 Subject: [PATCH] [mgmt] terraform release (#31794) https://github.com/Azure/sdk-release-request/issues/5663 --- .github/CODEOWNERS | 3 + common/config/rush/pnpm-lock.yaml | 90 ++-- eng/ignore-links.txt | 1 + rush.json | 5 + sdk/terraform/arm-terraform/CHANGELOG.md | 7 + sdk/terraform/arm-terraform/LICENSE | 21 + sdk/terraform/arm-terraform/README.md | 102 +++++ .../arm-terraform/api-extractor.json | 18 + sdk/terraform/arm-terraform/assets.json | 6 + sdk/terraform/arm-terraform/eslint.config.mjs | 17 + sdk/terraform/arm-terraform/package.json | 160 +++++++ .../review/arm-terraform-models.api.md | 149 +++++++ .../arm-terraform/review/arm-terraform.api.md | 217 ++++++++++ sdk/terraform/arm-terraform/sample.env | 1 + .../samples-dev/operationsListSample.ts | 29 ++ .../terraformExportTerraformSample.ts | 28 ++ .../samples/v1-beta/javascript/README.md | 52 +++ .../javascript/operationsListSample.js | 29 ++ .../samples/v1-beta/javascript/package.json | 33 ++ .../samples/v1-beta/javascript/sample.env | 1 + .../terraformExportTerraformSample.js | 28 ++ .../samples/v1-beta/typescript/README.md | 65 +++ .../samples/v1-beta/typescript/package.json | 42 ++ .../samples/v1-beta/typescript/sample.env | 1 + .../typescript/src/operationsListSample.ts | 29 ++ .../src/terraformExportTerraformSample.ts | 28 ++ .../samples/v1-beta/typescript/tsconfig.json | 17 + .../src/api/azureTerraformContext.ts | 57 +++ sdk/terraform/arm-terraform/src/api/index.ts | 11 + .../arm-terraform/src/api/operations/index.ts | 53 +++ .../arm-terraform/src/api/options.ts | 13 + .../arm-terraform/src/api/terraform/index.ts | 64 +++ .../arm-terraform/src/azureTerraformClient.ts | 44 ++ .../arm-terraform/src/classic/index.ts | 5 + .../src/classic/operations/index.ts | 26 ++ .../src/classic/terraform/index.ts | 35 ++ .../src/helpers/serializerHelpers.ts | 36 ++ sdk/terraform/arm-terraform/src/index.ts | 42 ++ sdk/terraform/arm-terraform/src/logger.ts | 5 + .../arm-terraform/src/models/index.ts | 27 ++ .../arm-terraform/src/models/models.ts | 400 ++++++++++++++++++ .../arm-terraform/src/restorePollerHelpers.ts | 153 +++++++ .../src/static-helpers/pagingHelpers.ts | 241 +++++++++++ .../src/static-helpers/pollingHelpers.ts | 126 ++++++ .../public/terraform_operations_test.spec.ts | 46 ++ .../test/public/utils/recordedClient.ts | 23 + .../tsconfig.browser.config.json | 10 + sdk/terraform/arm-terraform/tsconfig.json | 18 + sdk/terraform/arm-terraform/tsp-location.yaml | 4 + .../arm-terraform/vitest.browser.config.ts | 38 ++ sdk/terraform/arm-terraform/vitest.config.ts | 34 ++ sdk/terraform/ci.mgmt.yml | 32 ++ 52 files changed, 2697 insertions(+), 25 deletions(-) create mode 100644 sdk/terraform/arm-terraform/CHANGELOG.md create mode 100644 sdk/terraform/arm-terraform/LICENSE create mode 100644 sdk/terraform/arm-terraform/README.md create mode 100644 sdk/terraform/arm-terraform/api-extractor.json create mode 100644 sdk/terraform/arm-terraform/assets.json create mode 100644 sdk/terraform/arm-terraform/eslint.config.mjs create mode 100644 sdk/terraform/arm-terraform/package.json create mode 100644 sdk/terraform/arm-terraform/review/arm-terraform-models.api.md create mode 100644 sdk/terraform/arm-terraform/review/arm-terraform.api.md create mode 100644 sdk/terraform/arm-terraform/sample.env create mode 100644 sdk/terraform/arm-terraform/samples-dev/operationsListSample.ts create mode 100644 sdk/terraform/arm-terraform/samples-dev/terraformExportTerraformSample.ts create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/javascript/README.md create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/javascript/operationsListSample.js create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/javascript/package.json create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/javascript/sample.env create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/javascript/terraformExportTerraformSample.js create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/typescript/README.md create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/typescript/package.json create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/typescript/sample.env create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/operationsListSample.ts create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/terraformExportTerraformSample.ts create mode 100644 sdk/terraform/arm-terraform/samples/v1-beta/typescript/tsconfig.json create mode 100644 sdk/terraform/arm-terraform/src/api/azureTerraformContext.ts create mode 100644 sdk/terraform/arm-terraform/src/api/index.ts create mode 100644 sdk/terraform/arm-terraform/src/api/operations/index.ts create mode 100644 sdk/terraform/arm-terraform/src/api/options.ts create mode 100644 sdk/terraform/arm-terraform/src/api/terraform/index.ts create mode 100644 sdk/terraform/arm-terraform/src/azureTerraformClient.ts create mode 100644 sdk/terraform/arm-terraform/src/classic/index.ts create mode 100644 sdk/terraform/arm-terraform/src/classic/operations/index.ts create mode 100644 sdk/terraform/arm-terraform/src/classic/terraform/index.ts create mode 100644 sdk/terraform/arm-terraform/src/helpers/serializerHelpers.ts create mode 100644 sdk/terraform/arm-terraform/src/index.ts create mode 100644 sdk/terraform/arm-terraform/src/logger.ts create mode 100644 sdk/terraform/arm-terraform/src/models/index.ts create mode 100644 sdk/terraform/arm-terraform/src/models/models.ts create mode 100644 sdk/terraform/arm-terraform/src/restorePollerHelpers.ts create mode 100644 sdk/terraform/arm-terraform/src/static-helpers/pagingHelpers.ts create mode 100644 sdk/terraform/arm-terraform/src/static-helpers/pollingHelpers.ts create mode 100644 sdk/terraform/arm-terraform/test/public/terraform_operations_test.spec.ts create mode 100644 sdk/terraform/arm-terraform/test/public/utils/recordedClient.ts create mode 100644 sdk/terraform/arm-terraform/tsconfig.browser.config.json create mode 100644 sdk/terraform/arm-terraform/tsconfig.json create mode 100644 sdk/terraform/arm-terraform/tsp-location.yaml create mode 100644 sdk/terraform/arm-terraform/vitest.browser.config.ts create mode 100644 sdk/terraform/arm-terraform/vitest.config.ts create mode 100644 sdk/terraform/ci.mgmt.yml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c7319c4f110..452928d6de7 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -918,6 +918,9 @@ sdk/ai/ai-inference-rest @glharper @dargilco @jhakulin # PRLabel: %Mgmt /sdk/timeseriesinsights/arm-timeseriesinsights/ @qiaozha @MaryGao +# PRLabel: %Mgmt +/sdk/terraform/arm-terraform/ @qiaozha @MaryGao + # PRLabel: %Mgmt /sdk/trafficmanager/arm-trafficmanager/ @qiaozha @MaryGao diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 27f0fe1a539..e033292d98f 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -782,6 +782,9 @@ dependencies: '@rush-temp/arm-templatespecs': specifier: file:./projects/arm-templatespecs.tgz version: file:projects/arm-templatespecs.tgz + '@rush-temp/arm-terraform': + specifier: file:./projects/arm-terraform.tgz + version: file:projects/arm-terraform.tgz '@rush-temp/arm-timeseriesinsights': specifier: file:./projects/arm-timeseriesinsights.tgz version: file:projects/arm-timeseriesinsights.tgz @@ -3799,13 +3802,13 @@ packages: resolution: {integrity: sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==} dependencies: '@types/connect': 3.4.38 - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/bunyan@1.8.9: resolution: {integrity: sha512-ZqS9JGpBxVOvsawzmVt30sP++gSQMTejCkIAQ3VdadOcRE8izTyW66hufvwLeH+YEGP6Js2AW7Gz+RMyvrEbmw==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/chai-as-promised@7.1.8: @@ -3833,7 +3836,7 @@ packages: /@types/connect@3.4.38: resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/cookie@0.4.1: @@ -3847,7 +3850,7 @@ packages: /@types/cors@2.8.17: resolution: {integrity: sha512-8CGDvrBj1zgo2qE+oS3pOCyYNqCPryMWY2bGfwA0dcfopWGgxs+78df0Rs3rc9THP4JkOhLsAa+15VdpAqkcUA==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/debug@4.1.12: @@ -3859,7 +3862,7 @@ packages: /@types/decompress@4.2.7: resolution: {integrity: sha512-9z+8yjKr5Wn73Pt17/ldnmQToaFHZxK0N1GHysuk/JIPT8RIdQeoInM01wWPgypRcvb6VH1drjuFpQ4zmY437g==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/deep-eql@4.0.2: @@ -3890,7 +3893,7 @@ packages: /@types/express-serve-static-core@4.19.6: resolution: {integrity: sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 '@types/qs': 6.9.17 '@types/range-parser': 1.2.7 '@types/send': 0.17.4 @@ -3909,7 +3912,7 @@ packages: resolution: {integrity: sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ==} dependencies: '@types/jsonfile': 6.1.4 - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/http-errors@2.0.4: @@ -3926,7 +3929,7 @@ packages: /@types/is-buffer@2.0.2: resolution: {integrity: sha512-G6OXy83Va+xEo8XgqAJYOuvOMxeey9xM5XKkvwJNmN8rVdcB+r15HvHsG86hl86JvU0y1aa7Z2ERkNFYWw9ySg==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/json-schema@7.0.15: @@ -3936,19 +3939,19 @@ packages: /@types/jsonfile@6.1.4: resolution: {integrity: sha512-D5qGUYwjvnNNextdU59/+fI+spnwtTFmyQP0h+PfIOSkNfpU6AOICUOkm4i0OnSk+NyjdPJrxCDro0sJsWlRpQ==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/jsonwebtoken@9.0.7: resolution: {integrity: sha512-ugo316mmTYBl2g81zDFnZ7cfxlut3o+/EQdaP7J8QN2kY6lJ22hmQYCK5EHcJHbrW+dkCGSCPgbG8JtYj6qSrg==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/jws@3.2.10: resolution: {integrity: sha512-cOevhttJmssERB88/+XvZXvsq5m9JLKZNUiGfgjUb5lcPRdV2ZQciU6dU76D/qXXFYpSqkP3PrSg4hMTiafTZw==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/linkify-it@5.0.0: @@ -3995,13 +3998,13 @@ packages: /@types/mysql@2.15.26: resolution: {integrity: sha512-DSLCOXhkvfS5WNNPbfn2KdICAmk8lLc+/PNvnPnF7gOdMZCxopXduqv0OQ13y/yA/zXTSikZZqVgybUxOEg6YQ==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/node-fetch@2.6.12: resolution: {integrity: sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 form-data: 4.0.1 dev: false @@ -4040,7 +4043,7 @@ packages: /@types/pg@8.6.1: resolution: {integrity: sha512-1Kc4oAGzAl7uqUStZCDvaLFqZrW9qWSjXOmBfdgyBP5La7Us6Mg4GBvRlSoaZMhQF/zSj1C8CtKMBkoiT8eL8w==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 pg-protocol: 1.7.0 pg-types: 2.2.0 dev: false @@ -4067,7 +4070,7 @@ packages: /@types/readdir-glob@1.1.5: resolution: {integrity: sha512-raiuEPUYqXu+nvtY2Pe8s8FEmZ3x5yAH4VkLdihcPdalvsHltomrRC9BzuStrJ9yk06470hS0Crw0f1pXqD+Hg==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/resolve@1.20.2: @@ -4086,14 +4089,14 @@ packages: resolution: {integrity: sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==} dependencies: '@types/mime': 1.3.5 - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/serve-static@1.15.7: resolution: {integrity: sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==} dependencies: '@types/http-errors': 2.0.4 - '@types/node': 18.19.64 + '@types/node': 20.17.6 '@types/send': 0.17.4 dev: false @@ -4118,13 +4121,13 @@ packages: /@types/stoppable@1.1.3: resolution: {integrity: sha512-7wGKIBJGE4ZxFjk9NkjAxZMLlIXroETqP1FJCdoSvKmEznwmBxQFmTB1dsCkAvVcNemuSZM5qkkd9HE/NL2JTw==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/through@0.0.33: resolution: {integrity: sha512-HsJ+z3QuETzP3cswwtzt2vEIiHBk/dCcHGhbmG5X3ecnwFD/lPrMpliGXxSCg03L9AhrdwA4Oz/qfspkDW+xGQ==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/tough-cookie@4.0.5: @@ -4142,7 +4145,7 @@ packages: /@types/tunnel@0.0.1: resolution: {integrity: sha512-AOqu6bQu5MSWwYvehMXLukFHnupHrpZ8nvgae5Ggie9UwzDR1CCwoXgSSWNZJuyOlCdfdsWMA5F2LlmvyoTv8A==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/underscore@1.13.0: @@ -4160,13 +4163,13 @@ packages: /@types/ws@7.4.7: resolution: {integrity: sha512-JQbbmxZTZehdc2iszGKs5oC3NFnjeay7mtAWrdt7qNtAVK0g19muApzAy4bm9byz79xa2ZnO/BOBC2R8RC5Lww==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/ws@8.5.13: resolution: {integrity: sha512-osM/gWBTPKgHV8XkTunnegTRIsvF6owmf5w+JtAfOw472dptdm0dlGv4xCt6GwQRcC2XVOvvRE/0bAoQcL2QkA==} dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false /@types/yargs-parser@21.0.3: @@ -4183,7 +4186,7 @@ packages: resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} requiresBuild: true dependencies: - '@types/node': 18.19.64 + '@types/node': 20.17.6 dev: false optional: true @@ -5843,7 +5846,7 @@ packages: dependencies: '@types/cookie': 0.4.1 '@types/cors': 2.8.17 - '@types/node': 18.19.64 + '@types/node': 20.17.6 accepts: 1.3.8 base64id: 2.0.0 cookie: 0.7.2 @@ -9212,7 +9215,7 @@ packages: '@protobufjs/path': 1.1.2 '@protobufjs/pool': 1.1.0 '@protobufjs/utf8': 1.1.0 - '@types/node': 18.19.64 + '@types/node': 20.17.6 long: 5.2.3 dev: false @@ -18113,6 +18116,43 @@ packages: - supports-color dev: false + file:projects/arm-terraform.tgz: + resolution: {integrity: sha512-Emfl2nYOlyHvEUQn52bjceznQXcHvOFvn3kEHtbNb5RCyIICzcWSEjQNAD5rDhVA/zEfsmAhFpfS3H8ua3Wk6Q==, tarball: file:projects/arm-terraform.tgz} + name: '@rush-temp/arm-terraform' + version: 0.0.0 + dependencies: + '@microsoft/api-extractor': 7.47.11(@types/node@18.19.64) + '@types/node': 18.19.64 + '@vitest/browser': 2.1.5(@types/node@18.19.64)(playwright@1.49.0)(typescript@5.6.3)(vitest@2.1.5) + '@vitest/coverage-istanbul': 2.1.5(vitest@2.1.5) + dotenv: 16.4.5 + eslint: 8.57.1 + playwright: 1.49.0 + tshy: 2.0.1 + tslib: 2.8.1 + typescript: 5.6.3 + vitest: 2.1.5(@types/node@18.19.64)(@vitest/browser@2.1.5) + transitivePeerDependencies: + - '@edge-runtime/vm' + - '@vitest/ui' + - bufferutil + - happy-dom + - jsdom + - less + - lightningcss + - msw + - safaridriver + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - utf-8-validate + - vite + - webdriverio + dev: false + file:projects/arm-timeseriesinsights.tgz: resolution: {integrity: sha512-M5JNlYjuksfmjRYhRoQQBgymivooZF50jpe2EptMZQNRfn19ukQ2DilgCzx2EdJPHoT6IuVUo1D5DkbL7ebV3w==, tarball: file:projects/arm-timeseriesinsights.tgz} name: '@rush-temp/arm-timeseriesinsights' diff --git a/eng/ignore-links.txt b/eng/ignore-links.txt index 3cd2a78daf9..4f9ed285b40 100644 --- a/eng/ignore-links.txt +++ b/eng/ignore-links.txt @@ -13,4 +13,5 @@ https://docs.microsoft.com/javascript/api/@azure/arm-trustedsigning?view=azure-n https://docs.microsoft.com/javascript/api/@azure/arm-containerorchestratorruntime?view=azure-node-preview https://docs.microsoft.com/javascript/api/@azure/arm-iotoperations?view=azure-node-preview https://docs.microsoft.com/javascript/api/@azure/arm-databoundaries?view=azure-node-preview +https://docs.microsoft.com/javascript/api/@azure/arm-terraform?view=azure-node-preview https://docs.microsoft.com/javascript/api/@azure/arm-connectedcache?view=azure-node-preview diff --git a/rush.json b/rush.json index 59981552adf..a3f65d835cf 100644 --- a/rush.json +++ b/rush.json @@ -2307,6 +2307,11 @@ "projectFolder": "sdk/kubernetesruntime/arm-containerorchestratorruntime", "versionPolicyName": "management" }, + { + "packageName": "@azure/arm-terraform", + "projectFolder": "sdk/terraform/arm-terraform", + "versionPolicyName": "management" + }, { "packageName": "@azure/arm-connectedcache", "projectFolder": "sdk/connectedcache/arm-connectedcache", diff --git a/sdk/terraform/arm-terraform/CHANGELOG.md b/sdk/terraform/arm-terraform/CHANGELOG.md new file mode 100644 index 00000000000..99e19728f30 --- /dev/null +++ b/sdk/terraform/arm-terraform/CHANGELOG.md @@ -0,0 +1,7 @@ +# Release History + +## 1.0.0-beta.1 (2024-11-18) + +### Features Added + +Initial release of the Azure AzureTerraform Package. diff --git a/sdk/terraform/arm-terraform/LICENSE b/sdk/terraform/arm-terraform/LICENSE new file mode 100644 index 00000000000..7d593474096 --- /dev/null +++ b/sdk/terraform/arm-terraform/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/sdk/terraform/arm-terraform/README.md b/sdk/terraform/arm-terraform/README.md new file mode 100644 index 00000000000..48e93caf556 --- /dev/null +++ b/sdk/terraform/arm-terraform/README.md @@ -0,0 +1,102 @@ +# AzureTerraformResourceProvider client library for JavaScript + +This package contains an isomorphic SDK (runs both in Node.js and in browsers) for AzureTerraformResourceProvider client. + +The Azure Terraform management API provides a RESTful set of web services that used to manage your Azure Terraform resources. + +Key links: + +- [Package (NPM)](https://www.npmjs.com/package/@azure/arm-terraform) +- [API reference documentation](https://docs.microsoft.com/javascript/api/@azure/arm-terraform?view=azure-node-preview) + +## 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]. + +### Install the `@azure/arm-terraform` package + +Install the AzureTerraformResourceProvider client library for JavaScript with `npm`: + +```bash +npm install @azure/arm-terraform +``` + +### Create and authenticate a `AzureTerraformClient` + +To create a client object to access the AzureTerraformResourceProvider API, you will need the `endpoint` of your AzureTerraformResourceProvider resource and a `credential`. The AzureTerraformResourceProvider client can use Azure Active Directory credentials to authenticate. +You can find the endpoint for your AzureTerraformResourceProvider resource in the [Azure Portal][azure_portal]. + +You can authenticate with Azure Active Directory using a credential from the [@azure/identity][azure_identity] library or [an existing AAD Token](https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/samples/AzureIdentityExamples.md#authenticating-with-a-pre-fetched-access-token). + +To use the [DefaultAzureCredential][defaultazurecredential] provider shown below, or other credential providers provided with the Azure SDK, please install the `@azure/identity` package: + +```bash +npm install @azure/identity +``` + +You will also need to **register a new AAD application and grant access to AzureTerraformResourceProvider** by assigning the suitable role to your service principal (note: roles such as `"Owner"` will not grant the necessary permissions). +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`. + +For more information about how to create an Azure AD Application check out [this guide](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal). + +```javascript +const { AzureTerraformClient } = require("@azure/arm-terraform"); +const { DefaultAzureCredential } = require("@azure/identity"); +// For client-side applications running in the browser, use InteractiveBrowserCredential instead of DefaultAzureCredential. See https://aka.ms/azsdk/js/identity/examples for more details. + +const subscriptionId = "00000000-0000-0000-0000-000000000000"; +const client = new AzureTerraformClient(new DefaultAzureCredential(), subscriptionId); + +// For client-side applications running in the browser, use this code instead: +// const credential = new InteractiveBrowserCredential({ +// tenantId: "", +// clientId: "" +// }); +// const client = new AzureTerraformClient(credential, subscriptionId); +``` + + +### 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 + +### AzureTerraformClient + +`AzureTerraformClient` is the primary interface for developers using the AzureTerraformResourceProvider client library. Explore the methods on this client object to understand the different features of the AzureTerraformResourceProvider 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/sdk/terraform/arm-terraform/api-extractor.json b/sdk/terraform/arm-terraform/api-extractor.json new file mode 100644 index 00000000000..fd7cf40f687 --- /dev/null +++ b/sdk/terraform/arm-terraform/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-terraform.d.ts" + }, + "messages": { + "tsdocMessageReporting": { "default": { "logLevel": "none" } }, + "extractorMessageReporting": { + "ae-missing-release-tag": { "logLevel": "none" }, + "ae-unresolved-link": { "logLevel": "none" } + } + } +} diff --git a/sdk/terraform/arm-terraform/assets.json b/sdk/terraform/arm-terraform/assets.json new file mode 100644 index 00000000000..b8c9cbc8fde --- /dev/null +++ b/sdk/terraform/arm-terraform/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "js", + "TagPrefix": "js/terraform/arm-terraform", + "Tag": "js/terraform/arm-terraform_89cd053216" +} diff --git a/sdk/terraform/arm-terraform/eslint.config.mjs b/sdk/terraform/arm-terraform/eslint.config.mjs new file mode 100644 index 00000000000..03244d34a19 --- /dev/null +++ b/sdk/terraform/arm-terraform/eslint.config.mjs @@ -0,0 +1,17 @@ +import azsdkEslint from "@azure/eslint-plugin-azure-sdk"; + +export default [ + ...azsdkEslint.configs.recommended, + { + 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", + "@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", + "tsdoc/syntax": "warn", + }, + }, +]; diff --git a/sdk/terraform/arm-terraform/package.json b/sdk/terraform/arm-terraform/package.json new file mode 100644 index 00000000000..338eff013b9 --- /dev/null +++ b/sdk/terraform/arm-terraform/package.json @@ -0,0 +1,160 @@ +{ + "name": "@azure/arm-terraform", + "version": "1.0.0-beta.1", + "description": "A generated SDK for AzureTerraformClient.", + "engines": { + "node": ">=18.0.0" + }, + "sideEffects": false, + "autoPublish": false, + "tshy": { + "exports": { + "./package.json": "./package.json", + ".": "./src/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" + ], + "sdk-type": "mgmt", + "repository": "github:Azure/azure-sdk-for-js", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "prettier": "@azure/eslint-plugin-azure-sdk/prettier.json", + "//metadata": { + "constantPaths": [ + { + "path": "src/api/azureTerraformContext.ts", + "prefix": "userAgentInfo" + } + ] + }, + "dependencies": { + "@azure/core-util": "^1.9.2", + "@azure-rest/core-client": "^2.3.1", + "@azure/core-auth": "^1.6.0", + "@azure/core-rest-pipeline": "^1.5.0", + "@azure/logger": "^1.0.0", + "tslib": "^2.6.2", + "@azure/core-lro": "^3.1.0", + "@azure/abort-controller": "^2.1.2" + }, + "devDependencies": { + "dotenv": "^16.0.0", + "@microsoft/api-extractor": "^7.40.3", + "@types/node": "^18.0.0", + "eslint": "^8.55.0", + "typescript": "~5.6.2", + "tshy": "^2.0.0", + "@azure/identity": "^4.2.1", + "@vitest/browser": "^2.0.5", + "@vitest/coverage-istanbul": "^2.0.5", + "playwright": "^1.41.2", + "vitest": "^2.0.5", + "@azure-tools/test-credential": "^2.0.0", + "@azure-tools/test-recorder": "^4.0.0", + "@azure/dev-tool": "^1.0.0", + "@azure/eslint-plugin-azure-sdk": "^3.0.0" + }, + "scripts": { + "clean": "dev-tool run vendored rimraf --glob dist dist-browser dist-esm test-dist temp types *.tgz *.log", + "extract-api": "dev-tool run vendored rimraf review && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "pack": "npm pack 2>&1", + "lint": "echo skipped", + "lint:fix": "echo skipped", + "unit-test": "npm run unit-test:node && npm run unit-test:browser", + "unit-test:browser": "npm run build:test && dev-tool run test:vitest --browser", + "unit-test:node": "dev-tool run test:vitest", + "integration-test": "npm run integration-test:node && npm run integration-test:browser", + "integration-test:browser": "echo skipped", + "integration-test:node": "echo skipped", + "build:samples": "dev-tool run typecheck --paths samples-dev/*.ts && dev-tool samples publish -f", + "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" \"samples-dev/*.ts\"", + "execute:samples": "dev-tool samples run samples-dev", + "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.{ts,cts,mts}\" \"test/**/*.{ts,cts,mts}\" \"*.{js,cjs,mjs,json}\" \"samples-dev/*.ts\"", + "generate:client": "echo skipped", + "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser && npm run integration-test:browser", + "minify": "dev-tool run vendored uglifyjs -c -m --comments --source-map \"content='./dist/index.js.map'\" -o ./dist/index.min.js ./dist/index.js", + "build:test": "npm run clean && dev-tool run build-package && dev-tool run build-test", + "build": "npm run clean && dev-tool run build-package && dev-tool run vendored mkdirp ./review && dev-tool run extract-api", + "test:node": "npm run clean && dev-tool run build-package && npm run unit-test:node && npm run integration-test:node", + "test": "npm run clean && dev-tool run build-package && npm run unit-test:node && dev-tool run bundle && npm run unit-test:browser && npm run integration-test", + "update-snippets": "echo skipped" + }, + "//sampleConfiguration": { + "productName": "@azure/arm-terraform", + "productSlugs": [ + "azure" + ], + "disableDocsMs": true, + "apiRefLink": "https://docs.microsoft.com/javascript/api/@azure/arm-terraform?view=azure-node-preview" + }, + "exports": { + "./package.json": "./package.json", + ".": { + "browser": { + "types": "./dist/browser/index.d.ts", + "default": "./dist/browser/index.js" + }, + "react-native": { + "types": "./dist/react-native/index.d.ts", + "default": "./dist/react-native/index.js" + }, + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + }, + "./models": { + "browser": { + "types": "./dist/browser/models/index.d.ts", + "default": "./dist/browser/models/index.js" + }, + "react-native": { + "types": "./dist/react-native/models/index.d.ts", + "default": "./dist/react-native/models/index.js" + }, + "import": { + "types": "./dist/esm/models/index.d.ts", + "default": "./dist/esm/models/index.js" + }, + "require": { + "types": "./dist/commonjs/models/index.d.ts", + "default": "./dist/commonjs/models/index.js" + } + } + }, + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "module": "./dist/esm/index.js" +} diff --git a/sdk/terraform/arm-terraform/review/arm-terraform-models.api.md b/sdk/terraform/arm-terraform/review/arm-terraform-models.api.md new file mode 100644 index 00000000000..8353b973ab8 --- /dev/null +++ b/sdk/terraform/arm-terraform/review/arm-terraform-models.api.md @@ -0,0 +1,149 @@ +## API Report File for "@azure/arm-terraform" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +// @public +export type ActionType = string; + +// @public +export interface BaseExportModel { + fullProperties?: boolean; + maskSensitive?: boolean; + targetProvider?: TargetProvider; + type: Type; +} + +// @public +export type BaseExportModelUnion = ExportQuery | ExportResource | ExportResourceGroup | BaseExportModel; + +// @public +export interface ErrorAdditionalInfo { + readonly info?: Record; + readonly type?: string; +} + +// @public +export interface ErrorDetail { + readonly additionalInfo?: ErrorAdditionalInfo[]; + readonly code?: string; + readonly details?: ErrorDetail[]; + readonly message?: string; + readonly target?: string; +} + +// @public +export interface ExportQuery extends BaseExportModel { + namePattern?: string; + query: string; + recursive?: boolean; + type: "ExportQuery"; +} + +// @public +export interface ExportResource extends BaseExportModel { + namePattern?: string; + resourceIds: string[]; + resourceName?: string; + resourceType?: string; + type: "ExportResource"; +} + +// @public +export interface ExportResourceGroup extends BaseExportModel { + namePattern?: string; + resourceGroupName: string; + type: "ExportResourceGroup"; +} + +// @public +export interface ExportResult { + configuration?: string; + errors?: ErrorDetail[]; + skippedResources?: string[]; +} + +// @public +export enum KnownActionType { + Internal = "Internal" +} + +// @public +export enum KnownOrigin { + System = "system", + User = "user", + UserSystem = "user,system" +} + +// @public +export enum KnownResourceProvisioningState { + Canceled = "Canceled", + Failed = "Failed", + Succeeded = "Succeeded" +} + +// @public +export enum KnownTargetProvider { + azapi = "azapi", + azurerm = "azurerm" +} + +// @public +export enum KnownType { + // (undocumented) + ExportQuery = "ExportQuery", + // (undocumented) + ExportResource = "ExportResource", + // (undocumented) + ExportResourceGroup = "ExportResourceGroup" +} + +// @public +export enum KnownVersions { + v2023_07_01_preview = "2023-07-01-preview" +} + +// @public +export interface Operation { + actionType?: ActionType; + readonly display?: OperationDisplay; + readonly isDataAction?: boolean; + readonly name?: string; + readonly origin?: Origin; +} + +// @public +export interface OperationDisplay { + readonly description?: string; + readonly operation?: string; + readonly provider?: string; + readonly resource?: string; +} + +// @public +export type Origin = string; + +// @public +export type ResourceProvisioningState = string; + +// @public +export type TargetProvider = string; + +// @public +export interface TerraformOperationStatus { + readonly endTime?: Date; + readonly error?: ErrorDetail; + readonly name?: string; + readonly percentComplete?: number; + readonly properties?: ExportResult; + readonly startTime?: Date; + status: ResourceProvisioningState; +} + +// @public +export type Type = string; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/sdk/terraform/arm-terraform/review/arm-terraform.api.md b/sdk/terraform/arm-terraform/review/arm-terraform.api.md new file mode 100644 index 00000000000..ad65a53092f --- /dev/null +++ b/sdk/terraform/arm-terraform/review/arm-terraform.api.md @@ -0,0 +1,217 @@ +## API Report File for "@azure/arm-terraform" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { AbortSignalLike } from '@azure/abort-controller'; +import { ClientOptions } from '@azure-rest/core-client'; +import { OperationOptions } from '@azure-rest/core-client'; +import { OperationState } from '@azure/core-lro'; +import { PathUncheckedResponse } from '@azure-rest/core-client'; +import { Pipeline } from '@azure/core-rest-pipeline'; +import { PollerLike } from '@azure/core-lro'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +export type ActionType = string; + +// @public (undocumented) +export class AzureTerraformClient { + constructor(credential: TokenCredential, subscriptionId: string, options?: AzureTerraformClientOptionalParams); + readonly operations: OperationsOperations; + readonly pipeline: Pipeline; + readonly terraform: TerraformOperations; +} + +// @public +export interface AzureTerraformClientOptionalParams extends ClientOptions { + apiVersion?: string; +} + +// @public +export interface BaseExportModel { + fullProperties?: boolean; + maskSensitive?: boolean; + targetProvider?: TargetProvider; + type: Type; +} + +// @public +export type BaseExportModelUnion = ExportQuery | ExportResource | ExportResourceGroup | BaseExportModel; + +// @public +export type ContinuablePage = TPage & { + continuationToken?: string; +}; + +// @public +export interface ErrorAdditionalInfo { + readonly info?: Record; + readonly type?: string; +} + +// @public +export interface ErrorDetail { + readonly additionalInfo?: ErrorAdditionalInfo[]; + readonly code?: string; + readonly details?: ErrorDetail[]; + readonly message?: string; + readonly target?: string; +} + +// @public +export interface ExportQuery extends BaseExportModel { + namePattern?: string; + query: string; + recursive?: boolean; + type: "ExportQuery"; +} + +// @public +export interface ExportResource extends BaseExportModel { + namePattern?: string; + resourceIds: string[]; + resourceName?: string; + resourceType?: string; + type: "ExportResource"; +} + +// @public +export interface ExportResourceGroup extends BaseExportModel { + namePattern?: string; + resourceGroupName: string; + type: "ExportResourceGroup"; +} + +// @public +export interface ExportResult { + configuration?: string; + errors?: ErrorDetail[]; + skippedResources?: string[]; +} + +// @public +export enum KnownActionType { + Internal = "Internal" +} + +// @public +export enum KnownOrigin { + System = "system", + User = "user", + UserSystem = "user,system" +} + +// @public +export enum KnownResourceProvisioningState { + Canceled = "Canceled", + Failed = "Failed", + Succeeded = "Succeeded" +} + +// @public +export enum KnownTargetProvider { + azapi = "azapi", + azurerm = "azurerm" +} + +// @public +export enum KnownType { + // (undocumented) + ExportQuery = "ExportQuery", + // (undocumented) + ExportResource = "ExportResource", + // (undocumented) + ExportResourceGroup = "ExportResourceGroup" +} + +// @public +export enum KnownVersions { + v2023_07_01_preview = "2023-07-01-preview" +} + +// @public +export interface Operation { + actionType?: ActionType; + readonly display?: OperationDisplay; + readonly isDataAction?: boolean; + readonly name?: string; + readonly origin?: Origin; +} + +// @public +export interface OperationDisplay { + readonly description?: string; + readonly operation?: string; + readonly provider?: string; + readonly resource?: string; +} + +// @public +export interface OperationsListOptionalParams extends OperationOptions { +} + +// @public +export interface OperationsOperations { + list: (options?: OperationsListOptionalParams) => PagedAsyncIterableIterator; +} + +// @public +export type Origin = string; + +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; + next(): Promise>; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} + +// @public +export type ResourceProvisioningState = string; + +// @public +export function restorePoller(client: AzureTerraformClient, serializedState: string, sourceOperation: (...args: any[]) => PollerLike, TResult>, options?: RestorePollerOptions): PollerLike, TResult>; + +// @public (undocumented) +export interface RestorePollerOptions extends OperationOptions { + abortSignal?: AbortSignalLike; + processResponseBody?: (result: TResponse) => Promise; + updateIntervalInMs?: number; +} + +// @public +export type TargetProvider = string; + +// @public +export interface TerraformExportTerraformOptionalParams extends OperationOptions { + updateIntervalInMs?: number; +} + +// @public +export interface TerraformOperations { + exportTerraform: (body: BaseExportModelUnion, options?: TerraformExportTerraformOptionalParams) => PollerLike, TerraformOperationStatus>; +} + +// @public +export interface TerraformOperationStatus { + readonly endTime?: Date; + readonly error?: ErrorDetail; + readonly name?: string; + readonly percentComplete?: number; + readonly properties?: ExportResult; + readonly startTime?: Date; + status: ResourceProvisioningState; +} + +// @public +export type Type = string; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/sdk/terraform/arm-terraform/sample.env b/sdk/terraform/arm-terraform/sample.env new file mode 100644 index 00000000000..508439fc7d6 --- /dev/null +++ b/sdk/terraform/arm-terraform/sample.env @@ -0,0 +1 @@ +# Feel free to add your own environment variables. \ No newline at end of file diff --git a/sdk/terraform/arm-terraform/samples-dev/operationsListSample.ts b/sdk/terraform/arm-terraform/samples-dev/operationsListSample.ts new file mode 100644 index 00000000000..7ceb023f836 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples-dev/operationsListSample.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformClient } from "@azure/arm-terraform"; +import { DefaultAzureCredential } from "@azure/identity"; + +/** + * This sample demonstrates how to list the operations for the provider + * + * @summary list the operations for the provider + * x-ms-original-file: 2023-07-01-preview/ListOperations.json + */ +async function getAListOfOperationsForAResourceProvider() { + const credential = new DefaultAzureCredential(); + const subscriptionId = "00000000-0000-0000-0000-00000000000"; + const client = new AzureTerraformClient(credential, subscriptionId); + const resArray = new Array(); + for await (let item of client.operations.list()) { + resArray.push(item); + } + + console.log(resArray); +} + +async function main() { + getAListOfOperationsForAResourceProvider(); +} + +main().catch(console.error); diff --git a/sdk/terraform/arm-terraform/samples-dev/terraformExportTerraformSample.ts b/sdk/terraform/arm-terraform/samples-dev/terraformExportTerraformSample.ts new file mode 100644 index 00000000000..f03c4eb8579 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples-dev/terraformExportTerraformSample.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformClient } from "@azure/arm-terraform"; +import { DefaultAzureCredential } from "@azure/identity"; + +/** + * This sample demonstrates how to exports the Terraform configuration of the specified resource(s). + * + * @summary exports the Terraform configuration of the specified resource(s). + * x-ms-original-file: 2023-07-01-preview/ExportTerraform.json + */ +async function exportTerraform() { + const credential = new DefaultAzureCredential(); + const subscriptionId = "00000000-0000-0000-0000-000000000000"; + const client = new AzureTerraformClient(credential, subscriptionId); + const result = await client.terraform.exportTerraform({ + type: "ExportResourceGroup", + resourceGroupName: "rg1", + }); + console.log(result); +} + +async function main() { + exportTerraform(); +} + +main().catch(console.error); diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/javascript/README.md b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/README.md new file mode 100644 index 00000000000..6ce3d6567c8 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/README.md @@ -0,0 +1,52 @@ +# @azure/arm-terraform client library samples for JavaScript (Beta) + +These sample programs show how to use the JavaScript client libraries for @azure/arm-terraform in some common scenarios. + +| **File Name** | **Description** | +| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| [operationsListSample.js][operationslistsample] | list the operations for the provider x-ms-original-file: 2023-07-01-preview/ListOperations.json | +| [terraformExportTerraformSample.js][terraformexportterraformsample] | exports the Terraform configuration of the specified resource(s). x-ms-original-file: 2023-07-01-preview/ExportTerraform.json | + +## Prerequisites + +The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). + +You need [an Azure subscription][freesub] to run these sample programs. + +Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +3. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node operationsListSample.js +``` + +Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): + +```bash +npx dev-tool run vendored cross-env node operationsListSample.js +``` + +## Next Steps + +Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. + +[operationslistsample]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/terraform/arm-terraform/samples/v1-beta/javascript/operationsListSample.js +[terraformexportterraformsample]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/terraform/arm-terraform/samples/v1-beta/javascript/terraformExportTerraformSample.js +[apiref]: https://docs.microsoft.com/javascript/api/@azure/arm-terraform?view=azure-node-preview +[freesub]: https://azure.microsoft.com/free/ +[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/terraform/arm-terraform/README.md diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/javascript/operationsListSample.js b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/operationsListSample.js new file mode 100644 index 00000000000..1673dbb590f --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/operationsListSample.js @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +const { AzureTerraformClient } = require("@azure/arm-terraform"); +const { DefaultAzureCredential } = require("@azure/identity"); + +/** + * This sample demonstrates how to list the operations for the provider + * + * @summary list the operations for the provider + * x-ms-original-file: 2023-07-01-preview/ListOperations.json + */ +async function getAListOfOperationsForAResourceProvider() { + const credential = new DefaultAzureCredential(); + const subscriptionId = "00000000-0000-0000-0000-00000000000"; + const client = new AzureTerraformClient(credential, subscriptionId); + const resArray = new Array(); + for await (let item of client.operations.list()) { + resArray.push(item); + } + + console.log(resArray); +} + +async function main() { + getAListOfOperationsForAResourceProvider(); +} + +main().catch(console.error); diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/javascript/package.json b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/package.json new file mode 100644 index 00000000000..6ab5ad49d21 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/package.json @@ -0,0 +1,33 @@ +{ + "name": "@azure-samples/arm-terraform-js-beta", + "private": true, + "version": "1.0.0", + "description": "@azure/arm-terraform client library samples for JavaScript (Beta)", + "engines": { + "node": ">=18.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Azure/azure-sdk-for-js.git", + "directory": "sdk/terraform/arm-terraform" + }, + "keywords": [ + "node", + "azure", + "cloud", + "typescript", + "browser", + "isomorphic" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/terraform/arm-terraform", + "dependencies": { + "@azure/arm-terraform": "next", + "dotenv": "latest", + "@azure/identity": "^4.2.1" + } +} diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/javascript/sample.env b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/sample.env new file mode 100644 index 00000000000..508439fc7d6 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/sample.env @@ -0,0 +1 @@ +# Feel free to add your own environment variables. \ No newline at end of file diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/javascript/terraformExportTerraformSample.js b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/terraformExportTerraformSample.js new file mode 100644 index 00000000000..e8b938538d8 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/javascript/terraformExportTerraformSample.js @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +const { AzureTerraformClient } = require("@azure/arm-terraform"); +const { DefaultAzureCredential } = require("@azure/identity"); + +/** + * This sample demonstrates how to exports the Terraform configuration of the specified resource(s). + * + * @summary exports the Terraform configuration of the specified resource(s). + * x-ms-original-file: 2023-07-01-preview/ExportTerraform.json + */ +async function exportTerraform() { + const credential = new DefaultAzureCredential(); + const subscriptionId = "00000000-0000-0000-0000-000000000000"; + const client = new AzureTerraformClient(credential, subscriptionId); + const result = await client.terraform.exportTerraform({ + type: "ExportResourceGroup", + resourceGroupName: "rg1", + }); + console.log(result); +} + +async function main() { + exportTerraform(); +} + +main().catch(console.error); diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/typescript/README.md b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/README.md new file mode 100644 index 00000000000..180b46f77ae --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/README.md @@ -0,0 +1,65 @@ +# @azure/arm-terraform client library samples for TypeScript (Beta) + +These sample programs show how to use the TypeScript client libraries for @azure/arm-terraform in some common scenarios. + +| **File Name** | **Description** | +| ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| [operationsListSample.ts][operationslistsample] | list the operations for the provider x-ms-original-file: 2023-07-01-preview/ListOperations.json | +| [terraformExportTerraformSample.ts][terraformexportterraformsample] | exports the Terraform configuration of the specified resource(s). x-ms-original-file: 2023-07-01-preview/ExportTerraform.json | + +## Prerequisites + +The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule). + +Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: + +```bash +npm install -g typescript +``` + +You need [an Azure subscription][freesub] to run these sample programs. + +Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Compile the samples: + +```bash +npm run build +``` + +3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +4. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node dist/operationsListSample.js +``` + +Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): + +```bash +npx dev-tool run vendored cross-env node dist/operationsListSample.js +``` + +## Next Steps + +Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. + +[operationslistsample]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/operationsListSample.ts +[terraformexportterraformsample]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/terraformExportTerraformSample.ts +[apiref]: https://docs.microsoft.com/javascript/api/@azure/arm-terraform?view=azure-node-preview +[freesub]: https://azure.microsoft.com/free/ +[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/terraform/arm-terraform/README.md +[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/typescript/package.json b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/package.json new file mode 100644 index 00000000000..373bdf80cac --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/package.json @@ -0,0 +1,42 @@ +{ + "name": "@azure-samples/arm-terraform-ts-beta", + "private": true, + "version": "1.0.0", + "description": "@azure/arm-terraform client library samples for TypeScript (Beta)", + "engines": { + "node": ">=18.0.0" + }, + "scripts": { + "build": "tsc", + "prebuild": "rimraf dist/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Azure/azure-sdk-for-js.git", + "directory": "sdk/terraform/arm-terraform" + }, + "keywords": [ + "node", + "azure", + "cloud", + "typescript", + "browser", + "isomorphic" + ], + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/Azure/azure-sdk-for-js/issues" + }, + "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/terraform/arm-terraform", + "dependencies": { + "@azure/arm-terraform": "next", + "dotenv": "latest", + "@azure/identity": "^4.2.1" + }, + "devDependencies": { + "@types/node": "^18.0.0", + "typescript": "~5.6.2", + "rimraf": "latest" + } +} diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/typescript/sample.env b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/sample.env new file mode 100644 index 00000000000..508439fc7d6 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/sample.env @@ -0,0 +1 @@ +# Feel free to add your own environment variables. \ No newline at end of file diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/operationsListSample.ts b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/operationsListSample.ts new file mode 100644 index 00000000000..7ceb023f836 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/operationsListSample.ts @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformClient } from "@azure/arm-terraform"; +import { DefaultAzureCredential } from "@azure/identity"; + +/** + * This sample demonstrates how to list the operations for the provider + * + * @summary list the operations for the provider + * x-ms-original-file: 2023-07-01-preview/ListOperations.json + */ +async function getAListOfOperationsForAResourceProvider() { + const credential = new DefaultAzureCredential(); + const subscriptionId = "00000000-0000-0000-0000-00000000000"; + const client = new AzureTerraformClient(credential, subscriptionId); + const resArray = new Array(); + for await (let item of client.operations.list()) { + resArray.push(item); + } + + console.log(resArray); +} + +async function main() { + getAListOfOperationsForAResourceProvider(); +} + +main().catch(console.error); diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/terraformExportTerraformSample.ts b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/terraformExportTerraformSample.ts new file mode 100644 index 00000000000..f03c4eb8579 --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/src/terraformExportTerraformSample.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformClient } from "@azure/arm-terraform"; +import { DefaultAzureCredential } from "@azure/identity"; + +/** + * This sample demonstrates how to exports the Terraform configuration of the specified resource(s). + * + * @summary exports the Terraform configuration of the specified resource(s). + * x-ms-original-file: 2023-07-01-preview/ExportTerraform.json + */ +async function exportTerraform() { + const credential = new DefaultAzureCredential(); + const subscriptionId = "00000000-0000-0000-0000-000000000000"; + const client = new AzureTerraformClient(credential, subscriptionId); + const result = await client.terraform.exportTerraform({ + type: "ExportResourceGroup", + resourceGroupName: "rg1", + }); + console.log(result); +} + +async function main() { + exportTerraform(); +} + +main().catch(console.error); diff --git a/sdk/terraform/arm-terraform/samples/v1-beta/typescript/tsconfig.json b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/tsconfig.json new file mode 100644 index 00000000000..984eed535aa --- /dev/null +++ b/sdk/terraform/arm-terraform/samples/v1-beta/typescript/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "alwaysStrict": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": [ + "src/**/*.ts" + ] +} diff --git a/sdk/terraform/arm-terraform/src/api/azureTerraformContext.ts b/sdk/terraform/arm-terraform/src/api/azureTerraformContext.ts new file mode 100644 index 00000000000..9219402af37 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/api/azureTerraformContext.ts @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { logger } from "../logger.js"; +import { KnownVersions } from "../models/models.js"; +import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; +import { TokenCredential } from "@azure/core-auth"; + +/** The Azure Terraform management API provides a RESTful set of web services that used to manage your Azure Terraform resources. */ +export interface AzureTerraformContext extends Client {} + +/** Optional parameters for the client. */ +export interface AzureTerraformClientOptionalParams extends ClientOptions { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion?: string; +} + +/** The Azure Terraform management API provides a RESTful set of web services that used to manage your Azure Terraform resources. */ +export function createAzureTerraform( + credential: TokenCredential, + options: AzureTerraformClientOptionalParams = {}, +): AzureTerraformContext { + const endpointUrl = options.endpoint ?? options.baseUrl ?? `https://management.azure.com`; + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentInfo = `azsdk-js-arm-terraform/1.0.0-beta.1`; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-api ${userAgentInfo}` + : `azsdk-js-api ${userAgentInfo}`; + const { apiVersion: _, ...updatedOptions } = { + ...options, + userAgentOptions: { userAgentPrefix }, + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, + credentials: { + scopes: options.credentials?.scopes ?? [`${endpointUrl}/.default`], + }, + }; + const clientContext = getClient(endpointUrl, credential, updatedOptions); + clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + const apiVersion = options.apiVersion ?? "2023-07-01-preview"; + clientContext.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")) { + req.url = `${req.url}${ + Array.from(url.searchParams.keys()).length > 0 ? "&" : "?" + }api-version=${apiVersion}`; + } + + return next(req); + }, + }); + return clientContext; +} diff --git a/sdk/terraform/arm-terraform/src/api/index.ts b/sdk/terraform/arm-terraform/src/api/index.ts new file mode 100644 index 00000000000..5aff4965d15 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/api/index.ts @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { + createAzureTerraform, + AzureTerraformContext, + AzureTerraformClientOptionalParams, +} from "./azureTerraformContext.js"; +export { OperationsListOptionalParams, TerraformExportTerraformOptionalParams } from "./options.js"; +export { operationsList } from "./operations/index.js"; +export { terraformExportTerraform } from "./terraform/index.js"; diff --git a/sdk/terraform/arm-terraform/src/api/operations/index.ts b/sdk/terraform/arm-terraform/src/api/operations/index.ts new file mode 100644 index 00000000000..bc9a9088fd8 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/api/operations/index.ts @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformContext as Client, OperationsListOptionalParams } from "../index.js"; +import { + _OperationListResult, + _operationListResultDeserializer, + Operation, +} from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; + +export function _operationsListSend( + context: Client, + options: OperationsListOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/providers/Microsoft.AzureTerraform/operations") + .get({ ...operationOptionsToRequestParameters(options) }); +} + +export async function _operationsListDeserialize( + result: PathUncheckedResponse, +): Promise<_OperationListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _operationListResultDeserializer(result.body); +} + +/** List the operations for the provider */ +export function operationsList( + context: Client, + options: OperationsListOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _operationsListSend(context, options), + _operationsListDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} diff --git a/sdk/terraform/arm-terraform/src/api/options.ts b/sdk/terraform/arm-terraform/src/api/options.ts new file mode 100644 index 00000000000..49b6fae69fe --- /dev/null +++ b/sdk/terraform/arm-terraform/src/api/options.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { OperationOptions } from "@azure-rest/core-client"; + +/** Optional parameters. */ +export interface OperationsListOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface TerraformExportTerraformOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; +} diff --git a/sdk/terraform/arm-terraform/src/api/terraform/index.ts b/sdk/terraform/arm-terraform/src/api/terraform/index.ts new file mode 100644 index 00000000000..430d7b9935d --- /dev/null +++ b/sdk/terraform/arm-terraform/src/api/terraform/index.ts @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + AzureTerraformContext as Client, + TerraformExportTerraformOptionalParams, +} from "../index.js"; +import { + baseExportModelUnionSerializer, + BaseExportModelUnion, + TerraformOperationStatus, + terraformOperationStatusDeserializer, +} from "../../models/models.js"; +import { getLongRunningPoller } from "../../static-helpers/pollingHelpers.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { PollerLike, OperationState } from "@azure/core-lro"; + +export function _terraformExportTerraformSend( + context: Client, + subscriptionId: string, + body: BaseExportModelUnion, + options: TerraformExportTerraformOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path( + "/subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform", + subscriptionId, + ) + .post({ + ...operationOptionsToRequestParameters(options), + body: baseExportModelUnionSerializer(body), + }); +} + +export async function _terraformExportTerraformDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202", "200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return terraformOperationStatusDeserializer(result.body); +} + +/** Exports the Terraform configuration of the specified resource(s). */ +export function terraformExportTerraform( + context: Client, + subscriptionId: string, + body: BaseExportModelUnion, + options: TerraformExportTerraformOptionalParams = { requestOptions: {} }, +): PollerLike, TerraformOperationStatus> { + return getLongRunningPoller(context, _terraformExportTerraformDeserialize, ["202", "200"], { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => _terraformExportTerraformSend(context, subscriptionId, body, options), + resourceLocationConfig: "azure-async-operation", + }) as PollerLike, TerraformOperationStatus>; +} diff --git a/sdk/terraform/arm-terraform/src/azureTerraformClient.ts b/sdk/terraform/arm-terraform/src/azureTerraformClient.ts new file mode 100644 index 00000000000..612de316d9c --- /dev/null +++ b/sdk/terraform/arm-terraform/src/azureTerraformClient.ts @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { getOperationsOperations, OperationsOperations } from "./classic/operations/index.js"; +import { getTerraformOperations, TerraformOperations } from "./classic/terraform/index.js"; +import { + createAzureTerraform, + AzureTerraformContext, + AzureTerraformClientOptionalParams, +} from "./api/index.js"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { TokenCredential } from "@azure/core-auth"; + +export { AzureTerraformClientOptionalParams } from "./api/azureTerraformContext.js"; + +export class AzureTerraformClient { + private _client: AzureTerraformContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + /** The Azure Terraform management API provides a RESTful set of web services that used to manage your Azure Terraform resources. */ + constructor( + credential: TokenCredential, + subscriptionId: string, + options: AzureTerraformClientOptionalParams = {}, + ) { + const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; + const userAgentPrefix = prefixFromOptions + ? `${prefixFromOptions} azsdk-js-client` + : `azsdk-js-client`; + this._client = createAzureTerraform(credential, { + ...options, + userAgentOptions: { userAgentPrefix }, + }); + this.pipeline = this._client.pipeline; + this.operations = getOperationsOperations(this._client); + this.terraform = getTerraformOperations(this._client, subscriptionId); + } + + /** The operation groups for Operations */ + public readonly operations: OperationsOperations; + /** The operation groups for Terraform */ + public readonly terraform: TerraformOperations; +} diff --git a/sdk/terraform/arm-terraform/src/classic/index.ts b/sdk/terraform/arm-terraform/src/classic/index.ts new file mode 100644 index 00000000000..3d525776680 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/classic/index.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { OperationsOperations } from "./operations/index.js"; +export { TerraformOperations } from "./terraform/index.js"; diff --git a/sdk/terraform/arm-terraform/src/classic/operations/index.ts b/sdk/terraform/arm-terraform/src/classic/operations/index.ts new file mode 100644 index 00000000000..5d50783de5f --- /dev/null +++ b/sdk/terraform/arm-terraform/src/classic/operations/index.ts @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformContext } from "../../api/azureTerraformContext.js"; +import { operationsList } from "../../api/operations/index.js"; +import { OperationsListOptionalParams } from "../../api/options.js"; +import { Operation } from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; + +/** Interface representing a Operations operations. */ +export interface OperationsOperations { + /** List the operations for the provider */ + list: (options?: OperationsListOptionalParams) => PagedAsyncIterableIterator; +} + +export function getOperations(context: AzureTerraformContext) { + return { + list: (options?: OperationsListOptionalParams) => operationsList(context, options), + }; +} + +export function getOperationsOperations(context: AzureTerraformContext): OperationsOperations { + return { + ...getOperations(context), + }; +} diff --git a/sdk/terraform/arm-terraform/src/classic/terraform/index.ts b/sdk/terraform/arm-terraform/src/classic/terraform/index.ts new file mode 100644 index 00000000000..f8210f06b58 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/classic/terraform/index.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformContext } from "../../api/azureTerraformContext.js"; +import { TerraformExportTerraformOptionalParams } from "../../api/options.js"; +import { terraformExportTerraform } from "../../api/terraform/index.js"; +import { BaseExportModelUnion, TerraformOperationStatus } from "../../models/models.js"; +import { PollerLike, OperationState } from "@azure/core-lro"; + +/** Interface representing a Terraform operations. */ +export interface TerraformOperations { + /** Exports the Terraform configuration of the specified resource(s). */ + exportTerraform: ( + body: BaseExportModelUnion, + options?: TerraformExportTerraformOptionalParams, + ) => PollerLike, TerraformOperationStatus>; +} + +export function getTerraform(context: AzureTerraformContext, subscriptionId: string) { + return { + exportTerraform: ( + body: BaseExportModelUnion, + options?: TerraformExportTerraformOptionalParams, + ) => terraformExportTerraform(context, subscriptionId, body, options), + }; +} + +export function getTerraformOperations( + context: AzureTerraformContext, + subscriptionId: string, +): TerraformOperations { + return { + ...getTerraform(context, subscriptionId), + }; +} diff --git a/sdk/terraform/arm-terraform/src/helpers/serializerHelpers.ts b/sdk/terraform/arm-terraform/src/helpers/serializerHelpers.ts new file mode 100644 index 00000000000..7518a16c2ee --- /dev/null +++ b/sdk/terraform/arm-terraform/src/helpers/serializerHelpers.ts @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export function serializeRecord( + 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/sdk/terraform/arm-terraform/src/index.ts b/sdk/terraform/arm-terraform/src/index.ts new file mode 100644 index 00000000000..4b3ef8c8b68 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/index.ts @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./static-helpers/pagingHelpers.js"; + +export { AzureTerraformClient } from "./azureTerraformClient.js"; +export { restorePoller, RestorePollerOptions } from "./restorePollerHelpers.js"; +export { + BaseExportModel, + BaseExportModelUnion, + KnownType, + Type, + KnownTargetProvider, + TargetProvider, + ExportQuery, + ExportResource, + ExportResourceGroup, + ErrorDetail, + ErrorAdditionalInfo, + TerraformOperationStatus, + ExportResult, + KnownResourceProvisioningState, + ResourceProvisioningState, + Operation, + OperationDisplay, + KnownOrigin, + Origin, + KnownActionType, + ActionType, + KnownVersions, +} from "./models/index.js"; +export { + AzureTerraformClientOptionalParams, + OperationsListOptionalParams, + TerraformExportTerraformOptionalParams, +} from "./api/index.js"; +export { OperationsOperations, TerraformOperations } from "./classic/index.js"; +export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/sdk/terraform/arm-terraform/src/logger.ts b/sdk/terraform/arm-terraform/src/logger.ts new file mode 100644 index 00000000000..bc4c9cc97f4 --- /dev/null +++ b/sdk/terraform/arm-terraform/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-terraform"); diff --git a/sdk/terraform/arm-terraform/src/models/index.ts b/sdk/terraform/arm-terraform/src/models/index.ts new file mode 100644 index 00000000000..a6db47d2f42 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/models/index.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +export { + BaseExportModel, + BaseExportModelUnion, + KnownType, + Type, + KnownTargetProvider, + TargetProvider, + ExportQuery, + ExportResource, + ExportResourceGroup, + ErrorDetail, + ErrorAdditionalInfo, + TerraformOperationStatus, + ExportResult, + KnownResourceProvisioningState, + ResourceProvisioningState, + Operation, + OperationDisplay, + KnownOrigin, + Origin, + KnownActionType, + ActionType, + KnownVersions, +} from "./models.js"; diff --git a/sdk/terraform/arm-terraform/src/models/models.ts b/sdk/terraform/arm-terraform/src/models/models.ts new file mode 100644 index 00000000000..0edaaf7ec4d --- /dev/null +++ b/sdk/terraform/arm-terraform/src/models/models.ts @@ -0,0 +1,400 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** The base export parameter */ +export interface BaseExportModel { + /** The parameter type */ + /** The discriminator possible values: ExportQuery, ExportResource, ExportResourceGroup */ + type: Type; + /** The target Azure Terraform Provider */ + targetProvider?: TargetProvider; + /** Whether to output all non-computed properties in the generated Terraform configuration? This probably needs manual modifications to make it valid */ + fullProperties?: boolean; + /** Mask sensitive attributes in the Terraform configuration */ + maskSensitive?: boolean; +} + +export function baseExportModelSerializer(item: BaseExportModel): any { + return { + type: item["type"], + targetProvider: item["targetProvider"], + fullProperties: item["fullProperties"], + maskSensitive: item["maskSensitive"], + }; +} + +/** Alias for BaseExportModelUnion */ +export type BaseExportModelUnion = + | ExportQuery + | ExportResource + | ExportResourceGroup + | BaseExportModel; + +export function baseExportModelUnionSerializer(item: BaseExportModelUnion): any { + switch (item.type) { + case "ExportQuery": + return exportQuerySerializer(item as ExportQuery); + + case "ExportResource": + return exportResourceSerializer(item as ExportResource); + + case "ExportResourceGroup": + return exportResourceGroupSerializer(item as ExportResourceGroup); + + default: + return baseExportModelSerializer(item); + } +} + +/** The parameter type */ +export enum KnownType { + ExportResource = "ExportResource", + ExportResourceGroup = "ExportResourceGroup", + ExportQuery = "ExportQuery", +} + +/** + * The parameter type \ + * {@link KnownType} can be used interchangeably with Type, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **ExportResource** \ + * **ExportResourceGroup** \ + * **ExportQuery** + */ +export type Type = string; + +/** The target Azure Terraform Provider */ +export enum KnownTargetProvider { + /** https://registry.terraform.io/providers/hashicorp/azurerm/latest */ + azurerm = "azurerm", + /** https://registry.terraform.io/providers/Azure/azapi/latest */ + azapi = "azapi", +} + +/** + * The target Azure Terraform Provider \ + * {@link KnowntargetProvider} can be used interchangeably with targetProvider, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **azurerm**: https:\//registry.terraform.io\/providers\/hashicorp\/azurerm\/latest \ + * **azapi**: https:\//registry.terraform.io\/providers\/Azure\/azapi\/latest + */ +export type TargetProvider = string; + +/** Export parameter for resources queried by ARG (Azure Resource Graph) */ +export interface ExportQuery extends BaseExportModel { + /** The ARG where predicate. Note that you can combine multiple conditions in one `where` predicate, e.g. `resourceGroup =~ "my-rg" and type =~ "microsoft.network/virtualnetworks"` */ + query: string; + /** The name pattern of the Terraform resources */ + namePattern?: string; + /** Whether to recursively list child resources of the query result */ + recursive?: boolean; + /** The parameter type */ + type: "ExportQuery"; +} + +export function exportQuerySerializer(item: ExportQuery): any { + return { + type: item["type"], + targetProvider: item["targetProvider"], + fullProperties: item["fullProperties"], + maskSensitive: item["maskSensitive"], + query: item["query"], + namePattern: item["namePattern"], + recursive: item["recursive"], + }; +} + +/** Export parameter for individual resources. */ +export interface ExportResource extends BaseExportModel { + /** The id of the resource to be exported */ + resourceIds: string[]; + /** The Terraform resource name. Only works when `resourceIds` contains only one item. */ + resourceName?: string; + /** The Terraform resource type. Only works when `resourceIds` contains only one item. */ + resourceType?: string; + /** The name pattern of the Terraform resources */ + namePattern?: string; + /** The parameter type */ + type: "ExportResource"; +} + +export function exportResourceSerializer(item: ExportResource): any { + return { + type: item["type"], + targetProvider: item["targetProvider"], + fullProperties: item["fullProperties"], + maskSensitive: item["maskSensitive"], + resourceIds: item["resourceIds"].map((p: any) => { + return p; + }), + resourceName: item["resourceName"], + resourceType: item["resourceType"], + namePattern: item["namePattern"], + }; +} + +/** Export parameter for a resource group */ +export interface ExportResourceGroup extends BaseExportModel { + /** The name of the resource group to be exported */ + resourceGroupName: string; + /** The name pattern of the Terraform resources */ + namePattern?: string; + /** The parameter type */ + type: "ExportResourceGroup"; +} + +export function exportResourceGroupSerializer(item: ExportResourceGroup): any { + return { + type: item["type"], + targetProvider: item["targetProvider"], + fullProperties: item["fullProperties"], + maskSensitive: item["maskSensitive"], + resourceGroupName: item["resourceGroupName"], + namePattern: item["namePattern"], + }; +} + +/** 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[]; +} + +export function errorDetailDeserializer(item: any): ErrorDetail { + return { + code: item["code"], + message: item["message"], + target: item["target"], + details: !item["details"] ? item["details"] : errorDetailArrayDeserializer(item["details"]), + additionalInfo: !item["additionalInfo"] + ? item["additionalInfo"] + : errorAdditionalInfoArrayDeserializer(item["additionalInfo"]), + }; +} + +export function errorDetailArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return errorDetailDeserializer(item); + }); +} + +export function errorAdditionalInfoArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return errorAdditionalInfoDeserializer(item); + }); +} + +/** The resource management error additional info. */ +export interface ErrorAdditionalInfo { + /** The additional info type. */ + readonly type?: string; + /** The additional info. */ + readonly info?: Record; +} + +export function errorAdditionalInfoDeserializer(item: any): ErrorAdditionalInfo { + return { + type: item["type"], + info: !item["info"] ? item["info"] : _errorAdditionalInfoInfoDeserializer(item["info"]), + }; +} + +/** model interface _ErrorAdditionalInfoInfo */ +export interface _ErrorAdditionalInfoInfo {} + +export function _errorAdditionalInfoInfoDeserializer(item: any): _ErrorAdditionalInfoInfo { + return item; +} + +/** The status of the LRO operation. */ +export interface TerraformOperationStatus { + /** RP-specific properties for the operationStatus resource, only appears when operation ended with Succeeded status */ + readonly properties?: ExportResult; + /** The operation status */ + status: ResourceProvisioningState; + /** The name of the operationStatus resource */ + readonly name?: string; + /** Operation start time */ + readonly startTime?: Date; + /** Operation complete time */ + readonly endTime?: Date; + /** The progress made toward completing the operation */ + readonly percentComplete?: number; + /** Errors that occurred if the operation ended with Canceled or Failed status */ + readonly error?: ErrorDetail; +} + +export function terraformOperationStatusDeserializer(item: any): TerraformOperationStatus { + return { + properties: !item["properties"] + ? item["properties"] + : exportResultDeserializer(item["properties"]), + status: item["status"], + name: item["name"], + startTime: !item["startTime"] ? item["startTime"] : new Date(item["startTime"]), + endTime: !item["endTime"] ? item["endTime"] : new Date(item["endTime"]), + percentComplete: item["percentComplete"], + error: !item["error"] ? item["error"] : errorDetailDeserializer(item["error"]), + }; +} + +/** The Terraform export result */ +export interface ExportResult { + /** The Terraform configuration content */ + configuration?: string; + /** A list of Azure resources which are not exported to Terraform due to there is no corresponding resources in Terraform */ + skippedResources?: string[]; + /** A list of errors derived during exporting each resource */ + errors?: ErrorDetail[]; +} + +export function exportResultDeserializer(item: any): ExportResult { + return { + configuration: item["configuration"], + skippedResources: !item["skippedResources"] + ? item["skippedResources"] + : item["skippedResources"].map((p: any) => { + return p; + }), + errors: !item["errors"] ? item["errors"] : errorDetailArrayDeserializer(item["errors"]), + }; +} + +/** The provisioning state of a resource type. */ +export enum KnownResourceProvisioningState { + /** Resource has been created. */ + Succeeded = "Succeeded", + /** Resource creation failed. */ + Failed = "Failed", + /** Resource creation was canceled. */ + Canceled = "Canceled", +} + +/** + * The provisioning state of a resource type. \ + * {@link KnownResourceProvisioningState} can be used interchangeably with ResourceProvisioningState, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Succeeded**: Resource has been created. \ + * **Failed**: Resource creation failed. \ + * **Canceled**: Resource creation was canceled. + */ +export type ResourceProvisioningState = string; + +/** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */ +export interface _OperationListResult { + /** The Operation items on this page */ + value: Operation[]; + /** The link to the next page of items */ + nextLink?: string; +} + +export function _operationListResultDeserializer(item: any): _OperationListResult { + return { + value: operationArrayDeserializer(item["value"]), + nextLink: item["nextLink"], + }; +} + +export function operationArrayDeserializer(result: Array): any[] { + return result.map((item) => { + return operationDeserializer(item); + }); +} + +/** Details of a REST API operation, returned from the Resource Provider Operations API */ +export interface Operation { + /** The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" */ + readonly name?: string; + /** Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane operations. */ + readonly isDataAction?: boolean; + /** Localized display information for this particular operation. */ + readonly display?: OperationDisplay; + /** The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" */ + readonly origin?: Origin; + /** Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ + actionType?: ActionType; +} + +export function operationDeserializer(item: any): Operation { + return { + name: item["name"], + isDataAction: item["isDataAction"], + display: !item["display"] ? item["display"] : operationDisplayDeserializer(item["display"]), + origin: item["origin"], + actionType: item["actionType"], + }; +} + +/** Localized display information for and operation. */ +export interface OperationDisplay { + /** The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". */ + readonly provider?: string; + /** The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". */ + readonly resource?: string; + /** The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine". */ + readonly operation?: string; + /** The short, localized friendly description of the operation; suitable for tool tips and detailed views. */ + readonly description?: string; +} + +export function operationDisplayDeserializer(item: any): OperationDisplay { + return { + provider: item["provider"], + resource: item["resource"], + operation: item["operation"], + description: item["description"], + }; +} + +/** Known values of {@link Origin} that the service accepts. */ +export enum KnownOrigin { + /** user */ + User = "user", + /** system */ + System = "system", + /** user,system */ + UserSystem = "user,system", +} + +/** + * The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" \ + * {@link KnownOrigin} can be used interchangeably with Origin, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **user** \ + * **system** \ + * **user,system** + */ +export type Origin = string; + +/** Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. */ +export enum KnownActionType { + /** Actions are for internal-only APIs. */ + Internal = "Internal", +} + +/** + * Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. \ + * {@link KnownActionType} can be used interchangeably with ActionType, + * this enum contains the known values that the service supports. + * ### Known values supported by the service + * **Internal**: Actions are for internal-only APIs. + */ +export type ActionType = string; + +/** The available API versions. */ +export enum KnownVersions { + /** The 2023-07-01-preview API version. */ + v2023_07_01_preview = "2023-07-01-preview", +} diff --git a/sdk/terraform/arm-terraform/src/restorePollerHelpers.ts b/sdk/terraform/arm-terraform/src/restorePollerHelpers.ts new file mode 100644 index 00000000000..9ca27df21ea --- /dev/null +++ b/sdk/terraform/arm-terraform/src/restorePollerHelpers.ts @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { AzureTerraformClient } from "./azureTerraformClient.js"; +import { _terraformExportTerraformDeserialize } from "./api/terraform/index.js"; +import { getLongRunningPoller } from "./static-helpers/pollingHelpers.js"; +import { OperationOptions, PathUncheckedResponse } from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; +import { + PollerLike, + OperationState, + deserializeState, + ResourceLocationConfig, +} from "@azure/core-lro"; + +export interface RestorePollerOptions< + TResult, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +> extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** Deserialization function for raw response body */ + processResponseBody?: (result: TResponse) => Promise; +} + +/** + * Creates a poller from the serialized state of another poller. This can be + * useful when you want to create pollers on a different host or a poller + * needs to be constructed after the original one is not in scope. + */ +export function restorePoller( + client: AzureTerraformClient, + serializedState: string, + sourceOperation: (...args: any[]) => PollerLike, TResult>, + options?: RestorePollerOptions, +): PollerLike, TResult> { + const pollerConfig = deserializeState(serializedState).config; + const { initialRequestUrl, requestMethod, metadata } = pollerConfig; + if (!initialRequestUrl || !requestMethod) { + throw new Error( + `Invalid serialized state: ${serializedState} for sourceOperation ${sourceOperation?.name}`, + ); + } + const resourceLocationConfig = metadata?.["resourceLocationConfig"] as + | ResourceLocationConfig + | undefined; + const { deserializer, expectedStatuses = [] } = + getDeserializationHelper(initialRequestUrl, requestMethod) ?? {}; + const deserializeHelper = options?.processResponseBody ?? deserializer; + if (!deserializeHelper) { + throw new Error( + `Please ensure the operation is in this client! We can't find its deserializeHelper for ${sourceOperation?.name}.`, + ); + } + return getLongRunningPoller( + (client as any)["_client"] ?? client, + deserializeHelper as (result: TResponse) => Promise, + expectedStatuses, + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + resourceLocationConfig, + restoreFrom: serializedState, + initialRequestUrl, + }, + ); +} + +interface DeserializationHelper { + deserializer: Function; + expectedStatuses: string[]; +} + +const deserializeMap: Record = { + "POST /subscriptions/{subscriptionId}/providers/Microsoft.AzureTerraform/exportTerraform": { + deserializer: _terraformExportTerraformDeserialize, + expectedStatuses: ["202", "200"], + }, +}; + +function getDeserializationHelper( + urlStr: string, + method: string, +): DeserializationHelper | undefined { + const path = new URL(urlStr).pathname; + 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: DeserializationHelper | undefined; + + // Iterate the responseMap to find a match + for (const [key, value] of Object.entries(deserializeMap)) { + // 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/sdk/terraform/arm-terraform/src/static-helpers/pagingHelpers.ts b/sdk/terraform/arm-terraform/src/static-helpers/pagingHelpers.ts new file mode 100644 index 00000000000..ce33af5f417 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/static-helpers/pagingHelpers.ts @@ -0,0 +1,241 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Client, createRestError, PathUncheckedResponse } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; + +/** + * Options for the byPage method + */ +export interface PageSettings { + /** + * A reference to a specific page to start iterating from. + */ + continuationToken?: string; +} + +/** + * An interface that describes a page of results. + */ +export type ContinuablePage = TPage & { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +}; + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; +} + +/** + * An interface that describes how to communicate with the service. + */ +export interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +> { + /** + * Link to the first page of results. + */ + firstPageLink?: string; + /** + * A method that returns a page of results. + */ + getPage: (pageLink?: string) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; + /** + * a function to implement the `byPage` method on the paged async iterator. + */ + byPage?: (settings?: TPageSettings) => AsyncIterableIterator>; + + /** + * A function to extract elements from a page. + */ + toElements?: (page: TPage) => TElement[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse, +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => PromiseLike, + expectedStatuses: string[], + options: BuildPagedAsyncIteratorOptions = {}, +): PagedAsyncIterableIterator { + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; + const pagedResult: PagedResult = { + getPage: async (pageLink?: string) => { + const result = + pageLink === undefined + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + checkPagingRequest(result, expectedStatuses); + const results = await processResponseBody(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName) as TPage; + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }, + }; + return getPagedAsyncIterator(pagedResult); +} + +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ + +function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings, +>( + pagedResult: PagedResult, +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + for await (const page of pages) { + yield* page as unknown as TElement[]; + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {}, +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage(pageLink ?? pagedResult.firstPageLink); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if (typeof nextLink !== "string" && typeof nextLink !== "undefined" && nextLink !== null) { + throw new RestError( + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}`, + ); + } + + if (nextLink === null) { + return undefined; + } + + return nextLink; +} + +/** + * Gets the elements of the current request in the body. + */ +function getElements(body: unknown, itemName: string): T[] { + const value = (body as Record)[itemName] as T[]; + if (!Array.isArray(value)) { + throw new RestError( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}`, + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse, expectedStatuses: string[]): void { + if (!expectedStatuses.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response, + ); + } +} diff --git a/sdk/terraform/arm-terraform/src/static-helpers/pollingHelpers.ts b/sdk/terraform/arm-terraform/src/static-helpers/pollingHelpers.ts new file mode 100644 index 00000000000..f01c41bab69 --- /dev/null +++ b/sdk/terraform/arm-terraform/src/static-helpers/pollingHelpers.ts @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { + PollerLike, + OperationState, + ResourceLocationConfig, + RunningOperation, + createHttpPoller, + OperationResponse, +} from "@azure/core-lro"; + +import { Client, PathUncheckedResponse, createRestError } from "@azure-rest/core-client"; +import { AbortSignalLike } from "@azure/abort-controller"; + +export interface GetLongRunningPollerOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; + /** + * The signal which can be used to abort requests. + */ + abortSignal?: AbortSignalLike; + /** + * The potential location of the result of the LRO if specified by the LRO extension in the swagger. + */ + resourceLocationConfig?: ResourceLocationConfig; + /** + * The original url of the LRO + * Should not be null when restoreFrom is set + */ + initialRequestUrl?: string; + /** + * A serialized poller which can be used to resume an existing paused Long-Running-Operation. + */ + restoreFrom?: string; + /** + * The function to get the initial response + */ + getInitialResponse?: () => PromiseLike; +} +export function getLongRunningPoller( + client: Client, + processResponseBody: (result: TResponse) => Promise, + expectedStatuses: string[], + options: GetLongRunningPollerOptions, +): PollerLike, TResult> { + const { restoreFrom, getInitialResponse } = options; + if (!restoreFrom && !getInitialResponse) { + throw new Error("Either restoreFrom or getInitialResponse must be specified"); + } + let initialResponse: TResponse | undefined = undefined; + const pollAbortController = new AbortController(); + const poller: RunningOperation = { + sendInitialRequest: async () => { + if (!getInitialResponse) { + throw new Error("getInitialResponse is required when initializing a new poller"); + } + initialResponse = await getInitialResponse(); + return getLroResponse(initialResponse, expectedStatuses); + }, + sendPollRequest: async ( + path: string, + pollOptions?: { + abortSignal?: AbortSignalLike; + }, + ) => { + // The poll request would both listen to the user provided abort signal and the poller's own abort signal + function abortListener(): void { + pollAbortController.abort(); + } + const abortSignal = pollAbortController.signal; + if (options.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (pollOptions?.abortSignal?.aborted) { + pollAbortController.abort(); + } else if (!abortSignal.aborted) { + options.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + pollOptions?.abortSignal?.addEventListener("abort", abortListener, { + once: true, + }); + } + let response; + try { + response = await client.pathUnchecked(path).get({ abortSignal }); + } finally { + options.abortSignal?.removeEventListener("abort", abortListener); + pollOptions?.abortSignal?.removeEventListener("abort", abortListener); + } + + return getLroResponse(response as TResponse, expectedStatuses); + }, + }; + return createHttpPoller(poller, { + intervalInMs: options?.updateIntervalInMs, + resourceLocationConfig: options?.resourceLocationConfig, + restoreFrom: options?.restoreFrom, + processResult: (result: unknown) => { + return processResponseBody(result as TResponse); + }, + }); +} +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @param deserializeFn - deserialize function to convert Rest response to modular output + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse( + response: TResponse, + expectedStatuses: string[], +): OperationResponse { + if (!expectedStatuses.includes(response.status)) { + throw createRestError(response); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/sdk/terraform/arm-terraform/test/public/terraform_operations_test.spec.ts b/sdk/terraform/arm-terraform/test/public/terraform_operations_test.spec.ts new file mode 100644 index 00000000000..f9419d89538 --- /dev/null +++ b/sdk/terraform/arm-terraform/test/public/terraform_operations_test.spec.ts @@ -0,0 +1,46 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { env, Recorder, isPlaybackMode } from "@azure-tools/test-recorder"; +import { createTestCredential } from "@azure-tools/test-credential"; +import { assert, beforeEach, afterEach, it, describe } from "vitest"; +import { createRecorder } from "./utils/recordedClient.js"; +import { AzureTerraformClient } from "../../src/azureTerraformClient.js"; + +export const testPollingOptions = { + updateIntervalInMs: isPlaybackMode() ? 0 : undefined, +}; + +describe("AzureTerraform test", () => { + let recorder: Recorder; + let subscriptionId: string; + let client: AzureTerraformClient; + + beforeEach(async (context) => { + process.env.SystemRoot = process.env.SystemRoot || "C:\\Windows"; + recorder = await createRecorder(context); + subscriptionId = env.SUBSCRIPTION_ID || ""; + // This is an example of how the environment variables are used + const credential = createTestCredential(); + client = new AzureTerraformClient( + credential, + subscriptionId, + recorder.configureClientOptions({}), + ); + }); + + afterEach(async function () { + await recorder.stop(); + }); + it("operations list test", async function () { + const resArray = new Array(); + for await (let item of client.operations.list()) { + resArray.push(item); + } + assert.notEqual(resArray.length, 0); + }); +}); diff --git a/sdk/terraform/arm-terraform/test/public/utils/recordedClient.ts b/sdk/terraform/arm-terraform/test/public/utils/recordedClient.ts new file mode 100644 index 00000000000..14dcd9fa397 --- /dev/null +++ b/sdk/terraform/arm-terraform/test/public/utils/recordedClient.ts @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { Recorder, RecorderStartOptions, VitestTestContext } from "@azure-tools/test-recorder"; + +const replaceableVariables: Record = { + SUBSCRIPTION_ID: "azure_subscription_id", +}; + +const recorderEnvSetup: RecorderStartOptions = { + envSetupForPlayback: replaceableVariables, +}; + +/** + * creates the recorder and reads the environment variables from the `.env` file. + * Should be called first in the test suite to make sure environment variables are + * read before they are being used. + */ +export async function createRecorder(context: VitestTestContext): Promise { + const recorder = new Recorder(context); + await recorder.start(recorderEnvSetup); + return recorder; +} diff --git a/sdk/terraform/arm-terraform/tsconfig.browser.config.json b/sdk/terraform/arm-terraform/tsconfig.browser.config.json new file mode 100644 index 00000000000..091177fcb99 --- /dev/null +++ b/sdk/terraform/arm-terraform/tsconfig.browser.config.json @@ -0,0 +1,10 @@ +{ + "extends": "./.tshy/build.json", + "include": ["src/**/*.ts", "src/**/*.mts", "test/**/*.spec.ts"], + "exclude": ["test/**/node/**/*.ts"], + "compilerOptions": { + "outDir": "./dist-test/browser", + "rootDir": ".", + "skipLibCheck": true + } +} diff --git a/sdk/terraform/arm-terraform/tsconfig.json b/sdk/terraform/arm-terraform/tsconfig.json new file mode 100644 index 00000000000..ca8908bb315 --- /dev/null +++ b/sdk/terraform/arm-terraform/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../../tsconfig", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": ".", + "skipLibCheck": true, + "paths": { "@azure/arm-terraform": ["./src/index"] } + }, + "include": [ + "src/**/*.ts", + "src/**/*.mts", + "src/**/*.cts", + "test/**/*.ts", + "test/**/*.ts", + "samples-dev/**/*.ts" + ] +} diff --git a/sdk/terraform/arm-terraform/tsp-location.yaml b/sdk/terraform/arm-terraform/tsp-location.yaml new file mode 100644 index 00000000000..4c7102630e3 --- /dev/null +++ b/sdk/terraform/arm-terraform/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/terraform/Microsoft.AzureTerraform.Management +commit: 6fffb84d331b9712e71b3eadb58283a049ab96d3 +repo: ../azure-rest-api-specs +additionalDirectories: diff --git a/sdk/terraform/arm-terraform/vitest.browser.config.ts b/sdk/terraform/arm-terraform/vitest.browser.config.ts new file mode 100644 index 00000000000..da68c1d231a --- /dev/null +++ b/sdk/terraform/arm-terraform/vitest.browser.config.ts @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { defineConfig } from "vitest/config"; +import { relativeRecordingsPath } from "@azure-tools/test-recorder"; + +process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath(); + +export default defineConfig({ + define: { + "process.env": process.env, + }, + test: { + reporters: ["basic", "junit"], + outputFile: { + junit: "test-results.browser.xml", + }, + browser: { + enabled: true, + headless: true, + name: "chromium", + provider: "playwright", + }, + fakeTimers: { + toFake: ["setTimeout", "Date"], + }, + watch: false, + include: ["dist-test/browser/**/*.spec.js"], + coverage: { + include: ["dist-test/browser/**/*.spec.js"], + provider: "istanbul", + reporter: ["text", "json", "html"], + reportsDirectory: "coverage-browser", + }, + testTimeout: 1200000, + hookTimeout: 1200000, + }, +}); diff --git a/sdk/terraform/arm-terraform/vitest.config.ts b/sdk/terraform/arm-terraform/vitest.config.ts new file mode 100644 index 00000000000..2cf5d0e02c2 --- /dev/null +++ b/sdk/terraform/arm-terraform/vitest.config.ts @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { defineConfig } from "vitest/config"; +import { relativeRecordingsPath } from "@azure-tools/test-recorder"; + +export default defineConfig({ + test: { + reporters: ["basic", "junit"], + outputFile: { + junit: "test-results.browser.xml", + }, + fakeTimers: { + toFake: ["setTimeout", "Date"], + }, + watch: false, + include: ["test/**/*.spec.ts"], + exclude: ["test/**/browser/*.spec.ts"], + coverage: { + include: ["src/**/*.ts"], + exclude: [ + "src/**/*-browser.mts", + "src/**/*-react-native.mts", + "vitest*.config.ts", + "samples-dev/**/*.ts", + ], + provider: "istanbul", + reporter: ["text", "json", "html"], + reportsDirectory: "coverage", + }, + testTimeout: 1200000, + hookTimeout: 1200000, + }, +}); diff --git a/sdk/terraform/ci.mgmt.yml b/sdk/terraform/ci.mgmt.yml new file mode 100644 index 00000000000..402414bb7ff --- /dev/null +++ b/sdk/terraform/ci.mgmt.yml @@ -0,0 +1,32 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - release/* + - hotfix/* + paths: + include: + - sdk/terraform/ci.mgmt.yml + - sdk/terraform/arm-terraform +pr: + branches: + include: + - main + - feature/* + - release/* + - hotfix/* + exclude: + - feature/v4 + paths: + include: + - sdk/terraform/ci.mgmt.yml + - sdk/terraform/arm-terraform +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: terraform + Artifacts: + - name: azure-arm-terraform + safeName: azurearmterraform