From 3b5a63575f492de9529fced9714107db6d57f612 Mon Sep 17 00:00:00 2001 From: Qiaoqiao Zhang <55688292+qiaozha@users.noreply.github.com> Date: Thu, 26 Dec 2024 20:46:20 +0800 Subject: [PATCH] Sdk package methods adoption (#2943) * sdkPackage-methods-adoption * remove client server * reserve work * sdk client type * sdk client type * Modular Emitter Options * encode and format etc * add initial network analytics generation * hierarchies fixes * generate subscriptionId at client level * subscription id fix * fix options and headers map * create client fix * fix paging return type * restore poller fix * fix deserialize func return type * fix unit test * to not include extra body parameters * fix serialize and deser for spread * fix parameter name normalization * Update packages/typespec-ts/test/modularUnit/scenarios/operations/cookieParam/ignoreCookieParam.md * fix encoding * fix collection format * fix paging item name and next link name * fix path constant param * remove some unnecessary as any * fix nullable param serialize and deserialize * fix constant content-type header and optional spread body ser/deser * add option? * fix content type * fix endpoint request url * fix hierarchies * fix a bunch issues in smoke test * fix endpoint undefined case * fix default encoding as base64 * fix unit test * fix paging helper missing * fix restorePollingHelper non lro deser map * reserve work * fix hierarchies in modular * fix group name empty string * fix unit test * fix modular integration test * fix operation name normalize * remove api version and send api version when build request * fix server integration test * fix parameter order change * fix namespace renamed * rlc common format * fix model being used in both spread and unspread operations * reserve work * fix spread ser/deser * fix createContext with fixed enum param * fix path api version has default value * fix param name and operation name conflict * fix content type and optional params * fix revert bytes logic * revert api version as context property change * add apiVersion in the client level but remove the policy in operation level if not query * fix hasCollectionFormat * fix removePolicy and datetime nullable ser/der * fix ci * clean up unused modular models code * fix ci * fix ci * fix ci * resolve comments * fix paging in unbranding * revert client method map * to not expose contentType and accept as parameter or optional parameter and spread optional headers * remove optional contentType with guessed value for optional body --------- Co-authored-by: Qiaoqiao Zhang --- .../sdk/test/arm-test/package.json | 78 +- .../arm-test/src/api/dataProducts/index.ts | 596 +- .../src/api/dataProductsCatalogs/index.ts | 120 +- .../test/arm-test/src/api/dataTypes/index.ts | 370 +- .../sdk/test/arm-test/src/api/index.ts | 42 +- .../src/api/networkAnalyticsContext.ts | 17 +- .../test/arm-test/src/api/operations/index.ts | 9 +- .../sdk/test/arm-test/src/api/options.ts | 64 +- .../src/classic/dataProducts/index.ts | 276 +- .../src/classic/dataProductsCatalogs/index.ts | 51 +- .../arm-test/src/classic/dataTypes/index.ts | 164 +- .../sdk/test/arm-test/src/index.ts | 42 +- .../arm-test/src/networkAnalyticsClient.ts | 45 +- .../test/arm-test/src/restorePollerHelpers.ts | 40 +- .../ai/generated/typespec-ts/package.json | 40 +- .../typespec-ts/review/ai-client.api.md | 2 - .../typespec-ts/src/api/agents/index.ts | 2247 +++---- .../typespec-ts/src/api/azureAIContext.ts | 20 +- .../typespec-ts/src/api/connections/index.ts | 100 +- .../typespec-ts/src/api/evaluations/index.ts | 285 +- .../ai/generated/typespec-ts/src/api/index.ts | 100 +- .../generated/typespec-ts/src/api/options.ts | 632 +- .../typespec-ts/src/azureAIClient.ts | 26 +- .../typespec-ts/src/classic/agents/index.ts | 852 +-- .../src/classic/connections/index.ts | 30 +- .../src/classic/evaluations/index.ts | 122 +- .../ai/generated/typespec-ts/src/index.ts | 100 +- .../typespec-ts/src/models/models.ts | 124 +- .../generated/typespec-ts/package.json | 40 +- .../typespec-ts/src/anomalyDetectorClient.ts | 16 +- .../src/api/anomalyDetectorContext.ts | 8 +- .../generated/typespec-ts/src/api/index.ts | 18 +- .../typespec-ts/src/api/multivariate/index.ts | 297 +- .../generated/typespec-ts/src/api/options.ts | 24 +- .../typespec-ts/src/api/univariate/index.ts | 89 +- .../src/classic/multivariate/index.ts | 156 +- .../src/classic/univariate/index.ts | 50 +- .../generated/typespec-ts/src/index.ts | 18 +- .../typespec-ts/src/models/models.ts | 15 +- .../generated/typespec-ts/review/batch.api.md | 326 +- .../typespec-ts/src/api/batchContext.ts | 32 +- .../generated/typespec-ts/src/api/index.ts | 300 +- .../typespec-ts/src/api/operations.ts | 5633 ++++++++++------- .../generated/typespec-ts/src/api/options.ts | 2082 ++++-- .../generated/typespec-ts/src/batchClient.ts | 1648 ++--- .../generated/typespec-ts/src/index.ts | 150 +- .../typespec-ts/src/models/models.ts | 18 +- .../src/api/chatProtocolContext.ts | 3 +- .../generated/typespec-ts/src/api/index.ts | 4 +- .../typespec-ts/src/api/operations.ts | 66 +- .../generated/typespec-ts/src/api/options.ts | 4 +- .../typespec-ts/src/chatProtocolClient.ts | 20 +- .../generated/typespec-ts/src/index.ts | 2 +- .../review/ai-content-safety.api.md | 1 - .../src/api/contentSafetyContext.ts | 8 +- .../generated/typespec-ts/src/api/index.ts | 36 +- .../typespec-ts/src/api/operations.ts | 429 +- .../generated/typespec-ts/src/api/options.ts | 39 +- .../typespec-ts/src/contentSafetyClient.ts | 148 +- .../generated/typespec-ts/src/index.ts | 18 +- .../typespec-ts/review/eventgrid.api.md | 5 - .../typespec-ts/src/api/eventGridContext.ts | 11 +- .../generated/typespec-ts/src/api/index.ts | 20 +- .../typespec-ts/src/api/operations.ts | 276 +- .../generated/typespec-ts/src/api/options.ts | 30 +- .../typespec-ts/src/eventGridClient.ts | 104 +- .../generated/typespec-ts/src/index.ts | 10 +- .../typespec-ts/src/models/models.ts | 2 +- .../typespec-ts/src/api/operations.ts | 64 +- .../generated/typespec-ts/src/api/options.ts | 6 +- .../src/api/radiologyInsightsContext.ts | 8 +- .../typespec-ts/src/models/models.ts | 10 +- .../generated/typespec-ts/package.json | 78 +- .../typespec-ts/src/api/b/c/index.ts | 1 + .../typespec-ts/src/api/b/e/c/index.ts | 1 + .../generated/typespec-ts/src/api/b/index.ts | 1 + .../generated/typespec-ts/src/api/d/index.ts | 1 + .../typespec-ts/src/api/fooContext.ts | 8 +- .../generated/typespec-ts/src/api/index.ts | 8 +- .../typespec-ts/src/api/operations.ts | 1 + .../generated/typespec-ts/src/api/options.ts | 8 +- .../typespec-ts/src/classic/b/index.ts | 4 +- .../generated/typespec-ts/src/fooClient.ts | 14 +- .../generated/typespec-ts/src/index.ts | 8 +- .../typespec-ts/review/load-testing.api.md | 9 - .../generated/typespec-ts/src/index.ts | 62 +- .../src/loadTestAdministration/api/index.ts | 44 +- .../api/loadTestAdministrationContext.ts | 8 +- .../loadTestAdministration/api/operations.ts | 517 +- .../src/loadTestAdministration/api/options.ts | 65 +- .../src/loadTestAdministration/index.ts | 22 +- .../loadTestAdministrationClient.ts | 200 +- .../typespec-ts/src/loadTestRun/api/index.ts | 52 +- .../src/loadTestRun/api/loadTestRunContext.ts | 8 +- .../src/loadTestRun/api/operations.ts | 676 +- .../src/loadTestRun/api/options.ts | 114 +- .../typespec-ts/src/loadTestRun/index.ts | 26 +- .../src/loadTestRun/loadTestRunClient.ts | 242 +- .../testProfileAdministration/api/index.ts | 12 +- .../api/operations.ts | 171 +- .../testProfileAdministration/api/options.ts | 23 +- .../api/testProfileAdministrationContext.ts | 8 +- .../src/testProfileAdministration/index.ts | 6 +- .../testProfileAdministrationClient.ts | 54 +- .../src/testProfileRun/api/index.ts | 16 +- .../src/testProfileRun/api/operations.ts | 192 +- .../src/testProfileRun/api/options.ts | 21 +- .../api/testProfileRunContext.ts | 8 +- .../typespec-ts/src/testProfileRun/index.ts | 8 +- .../testProfileRun/testProfileRunClient.ts | 70 +- .../generated/typespec-ts/package.json | 238 +- .../typespec-ts/review/openai-generic.api.md | 10 - .../src/api/audio/transcriptions/index.ts | 6 +- .../src/api/audio/translations/index.ts | 6 +- .../src/api/chat/completions/index.ts | 5 + .../typespec-ts/src/api/completions/index.ts | 5 + .../typespec-ts/src/api/edits/index.ts | 5 + .../typespec-ts/src/api/embeddings/index.ts | 5 + .../typespec-ts/src/api/files/index.ts | 152 +- .../typespec-ts/src/api/fineTunes/index.ts | 125 +- .../src/api/fineTuning/jobs/index.ts | 135 +- .../typespec-ts/src/api/images/index.ts | 61 +- .../generated/typespec-ts/src/api/index.ts | 54 +- .../typespec-ts/src/api/models/index.ts | 82 +- .../typespec-ts/src/api/moderations/index.ts | 5 + .../typespec-ts/src/api/openAIContext.ts | 2 +- .../generated/typespec-ts/src/api/options.ts | 116 +- .../typespec-ts/src/classic/audio/index.ts | 4 +- .../typespec-ts/src/classic/files/index.ts | 52 +- .../src/classic/fineTunes/index.ts | 56 +- .../src/classic/fineTuning/jobs/index.ts | 70 +- .../typespec-ts/src/classic/images/index.ts | 30 +- .../typespec-ts/src/classic/models/index.ts | 22 +- .../generated/typespec-ts/src/index.ts | 54 +- .../typespec-ts/src/models/models.ts | 18 +- .../generated/typespec-ts/src/openAIClient.ts | 106 +- .../typespec-ts/review/openai_modular.api.md | 4 - .../generated/typespec-ts/src/api/index.ts | 32 +- .../typespec-ts/src/api/openAIContext.ts | 8 +- .../typespec-ts/src/api/operations.ts | 354 +- .../generated/typespec-ts/src/api/options.ts | 36 +- .../generated/typespec-ts/src/index.ts | 16 +- .../typespec-ts/src/models/models.ts | 36 +- .../generated/typespec-ts/src/openAIClient.ts | 182 +- .../generated/typespec-ts/package.json | 238 +- .../review/openai-non-branded.api.md | 10 - .../src/api/audio/transcriptions/index.ts | 6 +- .../src/api/audio/translations/index.ts | 6 +- .../src/api/chat/completions/index.ts | 5 + .../typespec-ts/src/api/completions/index.ts | 5 + .../typespec-ts/src/api/edits/index.ts | 5 + .../typespec-ts/src/api/embeddings/index.ts | 5 + .../typespec-ts/src/api/files/index.ts | 152 +- .../typespec-ts/src/api/fineTunes/index.ts | 125 +- .../src/api/fineTuning/jobs/index.ts | 135 +- .../typespec-ts/src/api/images/index.ts | 61 +- .../generated/typespec-ts/src/api/index.ts | 54 +- .../typespec-ts/src/api/models/index.ts | 82 +- .../typespec-ts/src/api/moderations/index.ts | 5 + .../typespec-ts/src/api/openAIContext.ts | 2 +- .../generated/typespec-ts/src/api/options.ts | 116 +- .../typespec-ts/src/classic/audio/index.ts | 4 +- .../typespec-ts/src/classic/files/index.ts | 52 +- .../src/classic/fineTunes/index.ts | 56 +- .../src/classic/fineTuning/jobs/index.ts | 70 +- .../typespec-ts/src/classic/images/index.ts | 30 +- .../typespec-ts/src/classic/models/index.ts | 22 +- .../generated/typespec-ts/src/index.ts | 54 +- .../typespec-ts/src/models/models.ts | 18 +- .../generated/typespec-ts/src/openAIClient.ts | 106 +- .../review/overload_modular.api.md | 4 - .../src/api/fooOperations/index.ts | 42 +- .../generated/typespec-ts/src/api/index.ts | 2 +- .../generated/typespec-ts/src/api/options.ts | 12 +- .../src/api/widgetManagerContext.ts | 8 +- .../src/classic/fooOperations/index.ts | 20 +- .../generated/typespec-ts/src/index.ts | 2 +- .../typespec-ts/src/widgetManagerClient.ts | 2 +- .../src/api/confidentialLedger/index.ts | 9 +- .../src/api/parametrizedHostContext.ts | 7 +- .../typespec-ts/src/parametrizedHostClient.ts | 2 +- .../typespec-ts/review/schema-registry.api.md | 4 +- .../generated/typespec-ts/src/api/index.ts | 10 +- .../generated/typespec-ts/src/api/options.ts | 12 +- .../src/api/schemaOperations/index.ts | 277 +- .../src/api/schemaRegistryContext.ts | 12 +- .../src/classic/schemaOperations/index.ts | 116 +- .../generated/typespec-ts/src/index.ts | 10 +- .../typespec-ts/src/schemaRegistryClient.ts | 6 +- .../generated/typespec-ts/src/api/a/index.ts | 116 +- .../typespec-ts/src/api/demoServiceContext.ts | 8 +- .../generated/typespec-ts/src/api/index.ts | 6 +- .../generated/typespec-ts/src/api/options.ts | 8 +- .../typespec-ts/src/classic/a/index.ts | 50 +- .../typespec-ts/src/demoServiceClient.ts | 2 +- .../spread/generated/typespec-ts/src/index.ts | 6 +- .../generated/typespec-ts/package.json | 40 +- .../review/todo-non-branded.api.md | 25 +- .../generated/typespec-ts/src/api/index.ts | 14 +- .../generated/typespec-ts/src/api/options.ts | 39 +- .../typespec-ts/src/api/todoContext.ts | 7 +- .../src/api/todoItems/attachments/index.ts | 80 +- .../typespec-ts/src/api/todoItems/index.ts | 191 +- .../typespec-ts/src/api/users/index.ts | 5 + .../classic/todoItems/attachments/index.ts | 19 +- .../src/classic/todoItems/index.ts | 74 +- .../generated/typespec-ts/src/index.ts | 21 +- .../src/static-helpers/pagingHelpers.ts | 273 + .../generated/typespec-ts/src/todoClient.ts | 10 +- .../generated/typespec-ts/package.json | 40 +- .../typespec-ts/review/widget_dpg.api.md | 2 - .../typespec-ts/src/api/budgets/index.ts | 11 +- .../generated/typespec-ts/src/api/index.ts | 18 +- .../generated/typespec-ts/src/api/options.ts | 52 +- .../src/api/widgetServiceContext.ts | 37 +- .../typespec-ts/src/api/widgets/index.ts | 473 +- .../typespec-ts/src/classic/widgets/index.ts | 180 +- .../generated/typespec-ts/src/index.ts | 18 +- .../typespec-ts/src/restorePollerHelpers.ts | 14 +- .../typespec-ts/src/widgetServiceClient.ts | 16 +- packages/typespec-ts/src/contextManager.ts | 3 +- .../src/framework/load-static-helpers.ts | 25 +- packages/typespec-ts/src/index.ts | 102 +- packages/typespec-ts/src/metaTree.ts | 6 - .../src/modular/buildClassicalClient.ts | 196 +- .../modular/buildClassicalOperationGroups.ts | 100 +- .../src/modular/buildClientContext.ts | 145 +- .../typespec-ts/src/modular/buildCodeModel.ts | 1965 ------ .../src/modular/buildModularOptions.ts | 27 + .../src/modular/buildOperations.ts | 169 +- .../src/modular/buildProjectFiles.ts | 45 +- .../src/modular/buildRestorePoller.ts | 62 +- .../typespec-ts/src/modular/buildRootIndex.ts | 93 +- .../src/modular/buildSubpathIndex.ts | 23 +- .../typespec-ts/src/modular/emitLoggerFile.ts | 22 +- .../typespec-ts/src/modular/emitModels.ts | 22 +- .../src/modular/emitModelsOptions.ts | 143 +- .../typespec-ts/src/modular/emitSamples.ts | 5 +- .../helpers/classicalOperationHelpers.ts | 125 +- .../src/modular/helpers/clientHelpers.ts | 186 +- .../src/modular/helpers/namingHelpers.ts | 71 +- .../src/modular/helpers/operationHelpers.ts | 890 +-- .../src/modular/helpers/typeHelpers.ts | 278 +- .../typespec-ts/src/modular/interfaces.ts | 24 +- .../src/modular/modularCodeModel.ts | 211 - .../buildDeserializerFunction.ts | 7 +- .../serialization/buildSerializerFunction.ts | 3 +- .../modular/serialization/serializeUtils.ts | 61 +- packages/typespec-ts/src/utils/clientUtils.ts | 24 +- .../typespec-ts/src/utils/operationUtil.ts | 120 +- .../azureArmManagedIdentity.spec.ts | 5 +- .../modularIntegration/encodeBytes.spec.ts | 8 +- .../authentication/api-key/src/index.d.ts | 2 +- .../authentication/http/custom/src/index.d.ts | 2 +- .../authentication/oauth2/src/index.d.ts | 2 +- .../authentication/union/src/index.d.ts | 2 +- .../access/src/index.d.ts | 16 +- .../flatten-property/src/index.d.ts | 2 +- .../usage/src/index.d.ts | 4 +- .../generated/azure/core/basic/src/index.d.ts | 13 +- .../azure/core/lro/standard/src/index.d.ts | 4 +- .../generated/azure/core/model/src/index.d.ts | 4 +- .../generated/azure/core/page/src/index.d.ts | 8 +- .../azure/core/scalar/src/index.d.ts | 8 +- .../azure/core/traits/src/index.d.ts | 2 +- .../common-properties/src/index.d.ts | 8 +- .../resource-manager/resources/src/index.d.ts | 30 +- .../generated/client/naming/src/index.d.ts | 20 +- .../client-operation-group/src/index.d.ts | 8 +- .../client/structure/default/src/index.d.ts | 14 +- .../structure/multi-client/src/index.d.ts | 8 +- .../renamed-operation/src/index.d.ts | 10 +- .../two-operation-group/src/index.d.ts | 10 +- .../generated/encode/bytes/src/index.d.ts | 44 +- .../generated/encode/datetime/src/index.d.ts | 36 +- .../generated/encode/duration/src/index.d.ts | 34 +- .../generated/encode/numeric/src/index.d.ts | 4 +- .../generated/parameters/basic/src/index.d.ts | 2 +- .../body-optionality/src/index.d.ts | 6 +- .../collection-format/src/index.d.ts | 10 +- .../parameters/spread/src/index.d.ts | 18 +- .../content-negotiation/src/index.d.ts | 10 +- .../payload/media-type/src/index.d.ts | 8 +- .../resiliency/srv-driven-main/src/index.d.ts | 6 +- .../resiliency/srv-driven-old/src/index.d.ts | 4 +- .../encoded-name/json/src/index.d.ts | 2 +- .../server/path/multiple/src/index.d.ts | 2 +- .../versions/not-versioned/src/index.d.ts | 4 +- .../server/versions/versioned/src/index.d.ts | 8 +- .../generated/special-words/src/index.d.ts | 200 +- .../generated/type/array/src/index.d.ts | 54 +- .../generated/type/dictionary/src/index.d.ts | 42 +- .../type/enum/extensible/src/index.d.ts | 6 +- .../generated/type/enum/fixed/src/index.d.ts | 4 +- .../generated/type/model/empty/src/index.d.ts | 4 +- .../enum-discriminator/src/index.d.ts | 14 +- .../nested-discriminator/src/index.d.ts | 10 +- .../not-discriminated/src/index.d.ts | 4 +- .../inheritance/recursive/src/index.d.ts | 2 +- .../single-discriminator/src/index.d.ts | 12 +- .../generated/type/model/usage/src/index.d.ts | 4 +- .../additional-properties/src/index.d.ts | 126 +- .../type/property/nullable/src/index.d.ts | 68 +- .../type/property/optionality/src/index.d.ts | 126 +- .../type/property/value-types/src/index.d.ts | 114 +- .../generated/type/scalar/src/index.d.ts | 30 +- .../generated/type/union/src/index.d.ts | 38 +- .../generated/versioning/added/src/index.d.ts | 4 +- .../versioning/removed/src/index.d.ts | 2 +- .../versioning/renamedFrom/src/index.d.ts | 2 +- .../versioning/typeChangedFrom/src/index.d.ts | 2 +- .../payloadContentNegotiation.spec.ts | 16 +- .../test/modularIntegration/server.spec.ts | 23 +- .../spreadParameters.spec.ts | 6 +- .../versioningAdded.spec.ts | 4 +- .../versioningRenamedFrom.spec.ts | 4 +- .../versioningTypeChangedFrom.spec.ts | 4 +- .../test/modularUnit/modelsGenerator.spec.ts | 2 +- .../scenarios/anonymous/anonymous.md | 354 +- .../scenarios/apiOperations/apiOperations.md | 437 +- .../scenarios/clientContext/clientContext.md | 16 +- .../scenarios/enumUnion/enumUnion.md | 78 +- .../modularUnit/scenarios/example/example.md | 8 +- .../apiVersion/apiVersionAsFixedEnum.md | 11 +- .../models/serialization/errorModels.md | 6 +- .../modelsGenerator/modelsGenerator.md | 469 +- .../cookieParam/ignoreCookieParam.md | 16 +- .../scenarios/operations/operations.md | 230 +- .../pathParam/requiredPathWithDefault.md | 13 +- .../samples/parameters/bodyOptionalCheck.md | 7 +- .../test/modularUnit/typeHelpers.spec.ts | 762 --- .../generated/models/usage/src/index.d.ts | 4 +- packages/typespec-ts/test/util/emitUtil.ts | 244 +- packages/typespec-ts/test/util/testUtil.ts | 1 - 334 files changed, 18701 insertions(+), 17956 deletions(-) create mode 100644 packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/static-helpers/pagingHelpers.ts delete mode 100644 packages/typespec-ts/src/modular/buildCodeModel.ts create mode 100644 packages/typespec-ts/src/modular/buildModularOptions.ts delete mode 100644 packages/typespec-ts/src/modular/modularCodeModel.ts delete mode 100644 packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/package.json b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/package.json index 181b82aaae..4e9cd468bd 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/package.json +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/package.json @@ -12,10 +12,10 @@ "./package.json": "./package.json", ".": "./src/index.ts", "./models": "./src/models/index.ts", - "./api/operations": "./src/api/operations/index.ts", - "./api/dataProductsCatalogs": "./src/api/dataProductsCatalogs/index.ts", + "./api/dataProducts": "./src/api/dataProducts/index.ts", "./api/dataTypes": "./src/api/dataTypes/index.ts", - "./api/dataProducts": "./src/api/dataProducts/index.ts" + "./api/dataProductsCatalogs": "./src/api/dataProductsCatalogs/index.ts", + "./api/operations": "./src/api/operations/index.ts" }, "dialects": [ "esm", @@ -127,40 +127,22 @@ "default": "./dist/commonjs/models/index.js" } }, - "./api/operations": { - "browser": { - "types": "./dist/browser/api/operations/index.d.ts", - "default": "./dist/browser/api/operations/index.js" - }, - "react-native": { - "types": "./dist/react-native/api/operations/index.d.ts", - "default": "./dist/react-native/api/operations/index.js" - }, - "import": { - "types": "./dist/esm/api/operations/index.d.ts", - "default": "./dist/esm/api/operations/index.js" - }, - "require": { - "types": "./dist/commonjs/api/operations/index.d.ts", - "default": "./dist/commonjs/api/operations/index.js" - } - }, - "./api/dataProductsCatalogs": { + "./api/dataProducts": { "browser": { - "types": "./dist/browser/api/dataProductsCatalogs/index.d.ts", - "default": "./dist/browser/api/dataProductsCatalogs/index.js" + "types": "./dist/browser/api/dataProducts/index.d.ts", + "default": "./dist/browser/api/dataProducts/index.js" }, "react-native": { - "types": "./dist/react-native/api/dataProductsCatalogs/index.d.ts", - "default": "./dist/react-native/api/dataProductsCatalogs/index.js" + "types": "./dist/react-native/api/dataProducts/index.d.ts", + "default": "./dist/react-native/api/dataProducts/index.js" }, "import": { - "types": "./dist/esm/api/dataProductsCatalogs/index.d.ts", - "default": "./dist/esm/api/dataProductsCatalogs/index.js" + "types": "./dist/esm/api/dataProducts/index.d.ts", + "default": "./dist/esm/api/dataProducts/index.js" }, "require": { - "types": "./dist/commonjs/api/dataProductsCatalogs/index.d.ts", - "default": "./dist/commonjs/api/dataProductsCatalogs/index.js" + "types": "./dist/commonjs/api/dataProducts/index.d.ts", + "default": "./dist/commonjs/api/dataProducts/index.js" } }, "./api/dataTypes": { @@ -181,22 +163,40 @@ "default": "./dist/commonjs/api/dataTypes/index.js" } }, - "./api/dataProducts": { + "./api/dataProductsCatalogs": { "browser": { - "types": "./dist/browser/api/dataProducts/index.d.ts", - "default": "./dist/browser/api/dataProducts/index.js" + "types": "./dist/browser/api/dataProductsCatalogs/index.d.ts", + "default": "./dist/browser/api/dataProductsCatalogs/index.js" }, "react-native": { - "types": "./dist/react-native/api/dataProducts/index.d.ts", - "default": "./dist/react-native/api/dataProducts/index.js" + "types": "./dist/react-native/api/dataProductsCatalogs/index.d.ts", + "default": "./dist/react-native/api/dataProductsCatalogs/index.js" }, "import": { - "types": "./dist/esm/api/dataProducts/index.d.ts", - "default": "./dist/esm/api/dataProducts/index.js" + "types": "./dist/esm/api/dataProductsCatalogs/index.d.ts", + "default": "./dist/esm/api/dataProductsCatalogs/index.js" }, "require": { - "types": "./dist/commonjs/api/dataProducts/index.d.ts", - "default": "./dist/commonjs/api/dataProducts/index.js" + "types": "./dist/commonjs/api/dataProductsCatalogs/index.d.ts", + "default": "./dist/commonjs/api/dataProductsCatalogs/index.js" + } + }, + "./api/operations": { + "browser": { + "types": "./dist/browser/api/operations/index.d.ts", + "default": "./dist/browser/api/operations/index.js" + }, + "react-native": { + "types": "./dist/react-native/api/operations/index.d.ts", + "default": "./dist/react-native/api/operations/index.js" + }, + "import": { + "types": "./dist/esm/api/operations/index.d.ts", + "default": "./dist/esm/api/operations/index.js" + }, + "require": { + "types": "./dist/commonjs/api/operations/index.d.ts", + "default": "./dist/commonjs/api/operations/index.js" } } }, diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProducts/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProducts/index.ts index 8618b2b551..1d1fe53058 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProducts/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProducts/index.ts @@ -51,187 +51,194 @@ import { } from "@azure-rest/core-client"; import { PollerLike, OperationState } from "@azure/core-lro"; -export function _createSend( +export function _listBySubscriptionSend( context: Client, - subscriptionId: string, - resourceGroupName: string, - dataProductName: string, - resource: DataProduct, - options: DataProductsCreateOptionalParams = { requestOptions: {} }, + options: DataProductsListBySubscriptionOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", - subscriptionId, - resourceGroupName, - dataProductName, + "/subscriptions/{subscriptionId}/providers/Microsoft.NetworkAnalytics/dataProducts", + context.subscriptionId, ) - .put({ + .get({ ...operationOptionsToRequestParameters(options), - body: dataProductSerializer(resource), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createDeserialize( +export async function _listBySubscriptionDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "201"]; +): Promise<_DataProductListResult> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataProductDeserializer(result.body); + return _dataProductListResultDeserializer(result.body); } -/** Create data product resource. */ -export function create( +/** List data products by subscription. */ +export function listBySubscription( context: Client, - subscriptionId: string, - resourceGroupName: string, - dataProductName: string, - resource: DataProduct, - options: DataProductsCreateOptionalParams = { requestOptions: {} }, -): PollerLike, DataProduct> { - return getLongRunningPoller(context, _createDeserialize, ["200", "201"], { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _createSend( - context, - subscriptionId, - resourceGroupName, - dataProductName, - resource, - options, - ), - resourceLocationConfig: "azure-async-operation", - }) as PollerLike, DataProduct>; + options: DataProductsListBySubscriptionOptionalParams = { + requestOptions: {}, + }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listBySubscriptionSend(context, options), + _listBySubscriptionDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); } -export function _getSend( +export function _listByResourceGroupSend( context: Client, - subscriptionId: string, resourceGroupName: string, - dataProductName: string, - options: DataProductsGetOptionalParams = { requestOptions: {} }, + options: DataProductsListByResourceGroupOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts", + context.subscriptionId, resourceGroupName, - dataProductName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getDeserialize( +export async function _listByResourceGroupDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_DataProductListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataProductDeserializer(result.body); + return _dataProductListResultDeserializer(result.body); } -/** Retrieve data product resource. */ -export async function get( +/** List data products by resource group. */ +export function listByResourceGroup( context: Client, - subscriptionId: string, resourceGroupName: string, - dataProductName: string, - options: DataProductsGetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getSend( + options: DataProductsListByResourceGroupOptionalParams = { + requestOptions: {}, + }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - subscriptionId, - resourceGroupName, - dataProductName, - options, + () => _listByResourceGroupSend(context, resourceGroupName, options), + _listByResourceGroupDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _getDeserialize(result); } -export function _updateSend( +export function _listRolesAssignmentsSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - properties: DataProductUpdate, - options: DataProductsUpdateOptionalParams = { requestOptions: {} }, + body: Record, + options: DataProductsListRolesAssignmentsOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/listRolesAssignments", + context.subscriptionId, resourceGroupName, dataProductName, ) - .patch({ + .post({ ...operationOptionsToRequestParameters(options), - body: dataProductUpdateSerializer(properties), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: _listRolesAssignmentsRequestSerializer(body), }); } -export async function _updateDeserialize( +export async function _listRolesAssignmentsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "202"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataProductDeserializer(result.body); + return listRoleAssignmentsDeserializer(result.body); } -/** Update data product resource. */ -export function update( +/** List user roles associated with the data product. */ +export async function listRolesAssignments( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - properties: DataProductUpdate, - options: DataProductsUpdateOptionalParams = { requestOptions: {} }, -): PollerLike, DataProduct> { - return getLongRunningPoller(context, _updateDeserialize, ["200", "202"], { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _updateSend( - context, - subscriptionId, - resourceGroupName, - dataProductName, - properties, - options, - ), - resourceLocationConfig: "location", - }) as PollerLike, DataProduct>; + body: Record, + options: DataProductsListRolesAssignmentsOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _listRolesAssignmentsSend( + context, + resourceGroupName, + dataProductName, + body, + options, + ); + return _listRolesAssignmentsDeserialize(result); } -export function _$deleteSend( +export function _removeUserRoleSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - options: DataProductsDeleteOptionalParams = { requestOptions: {} }, + body: RoleAssignmentDetail, + options: DataProductsRemoveUserRoleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/removeUserRole", + context.subscriptionId, resourceGroupName, dataProductName, ) - .delete({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: roleAssignmentDetailSerializer(body), + }); } -export async function _$deleteDeserialize( +export async function _removeUserRoleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202", "204", "200"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -239,98 +246,81 @@ export async function _$deleteDeserialize( return; } -/** Delete data product resource. */ -/** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ -export function $delete( +/** Remove role from the data product. */ +export async function removeUserRole( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - options: DataProductsDeleteOptionalParams = { requestOptions: {} }, -): PollerLike, void> { - return getLongRunningPoller( + body: RoleAssignmentDetail, + options: DataProductsRemoveUserRoleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _removeUserRoleSend( context, - _$deleteDeserialize, - ["202", "204", "200"], - { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _$deleteSend( - context, - subscriptionId, - resourceGroupName, - dataProductName, - options, - ), - resourceLocationConfig: "location", - }, - ) as PollerLike, void>; + resourceGroupName, + dataProductName, + body, + options, + ); + return _removeUserRoleDeserialize(result); } -export function _generateStorageAccountSasTokenSend( +export function _addUserRoleSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: AccountSas, - options: DataProductsGenerateStorageAccountSasTokenOptionalParams = { - requestOptions: {}, - }, + body: RoleAssignmentCommonProperties, + options: DataProductsAddUserRoleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/generateStorageAccountSasToken", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/addUserRole", + context.subscriptionId, resourceGroupName, dataProductName, ) .post({ ...operationOptionsToRequestParameters(options), - body: accountSasSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: roleAssignmentCommonPropertiesSerializer(body), }); } -export async function _generateStorageAccountSasTokenDeserialize( +export async function _addUserRoleDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return accountSasTokenDeserializer(result.body); + return roleAssignmentDetailDeserializer(result.body); } -/** Generate sas token for storage account. */ -export async function generateStorageAccountSasToken( +/** Assign role to the data product. */ +export async function addUserRole( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: AccountSas, - options: DataProductsGenerateStorageAccountSasTokenOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _generateStorageAccountSasTokenSend( + body: RoleAssignmentCommonProperties, + options: DataProductsAddUserRoleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _addUserRoleSend( context, - subscriptionId, resourceGroupName, dataProductName, body, options, ); - return _generateStorageAccountSasTokenDeserialize(result); + return _addUserRoleDeserialize(result); } export function _rotateKeySend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: KeyVaultInfo, @@ -339,12 +329,18 @@ export function _rotateKeySend( return context .path( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/rotateKey", - subscriptionId, + context.subscriptionId, resourceGroupName, dataProductName, ) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: keyVaultInfoSerializer(body), }); } @@ -363,7 +359,6 @@ export async function _rotateKeyDeserialize( /** Initiate key rotation on Data Product. */ export async function rotateKey( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, body: KeyVaultInfo, @@ -371,7 +366,6 @@ export async function rotateKey( ): Promise { const result = await _rotateKeySend( context, - subscriptionId, resourceGroupName, dataProductName, body, @@ -380,83 +374,92 @@ export async function rotateKey( return _rotateKeyDeserialize(result); } -export function _addUserRoleSend( +export function _generateStorageAccountSasTokenSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: RoleAssignmentCommonProperties, - options: DataProductsAddUserRoleOptionalParams = { requestOptions: {} }, + body: AccountSas, + options: DataProductsGenerateStorageAccountSasTokenOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/addUserRole", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/generateStorageAccountSasToken", + context.subscriptionId, resourceGroupName, dataProductName, ) .post({ ...operationOptionsToRequestParameters(options), - body: roleAssignmentCommonPropertiesSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: accountSasSerializer(body), }); } -export async function _addUserRoleDeserialize( +export async function _generateStorageAccountSasTokenDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return roleAssignmentDetailDeserializer(result.body); + return accountSasTokenDeserializer(result.body); } -/** Assign role to the data product. */ -export async function addUserRole( +/** Generate sas token for storage account. */ +export async function generateStorageAccountSasToken( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: RoleAssignmentCommonProperties, - options: DataProductsAddUserRoleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _addUserRoleSend( + body: AccountSas, + options: DataProductsGenerateStorageAccountSasTokenOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _generateStorageAccountSasTokenSend( context, - subscriptionId, resourceGroupName, dataProductName, body, options, ); - return _addUserRoleDeserialize(result); + return _generateStorageAccountSasTokenDeserialize(result); } -export function _removeUserRoleSend( +export function _$deleteSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: RoleAssignmentDetail, - options: DataProductsRemoveUserRoleOptionalParams = { requestOptions: {} }, + options: DataProductsDeleteOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/removeUserRole", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", + context.subscriptionId, resourceGroupName, dataProductName, ) - .post({ + .delete({ ...operationOptionsToRequestParameters(options), - body: roleAssignmentDetailSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _removeUserRoleDeserialize( +export async function _$deleteDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["202", "204", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -464,173 +467,198 @@ export async function _removeUserRoleDeserialize( return; } -/** Remove role from the data product. */ -export async function removeUserRole( +/** Delete data product resource. */ +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export function $delete( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: RoleAssignmentDetail, - options: DataProductsRemoveUserRoleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _removeUserRoleSend( + options: DataProductsDeleteOptionalParams = { requestOptions: {} }, +): PollerLike, void> { + return getLongRunningPoller( context, - subscriptionId, - resourceGroupName, - dataProductName, - body, - options, - ); - return _removeUserRoleDeserialize(result); + _$deleteDeserialize, + ["202", "204", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _$deleteSend(context, resourceGroupName, dataProductName, options), + resourceLocationConfig: "location", + }, + ) as PollerLike, void>; } -export function _listRolesAssignmentsSend( +export function _updateSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: Record, - options: DataProductsListRolesAssignmentsOptionalParams = { - requestOptions: {}, - }, + properties: DataProductUpdate, + options: DataProductsUpdateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/listRolesAssignments", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", + context.subscriptionId, resourceGroupName, dataProductName, ) - .post({ + .patch({ ...operationOptionsToRequestParameters(options), - body: _listRolesAssignmentsRequestSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: dataProductUpdateSerializer(properties), }); } -export async function _listRolesAssignmentsDeserialize( +export async function _updateDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["200", "202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listRoleAssignmentsDeserializer(result.body); + return dataProductDeserializer(result.body); } -/** List user roles associated with the data product. */ -export async function listRolesAssignments( +/** Update data product resource. */ +export function update( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - body: Record, - options: DataProductsListRolesAssignmentsOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _listRolesAssignmentsSend( - context, - subscriptionId, - resourceGroupName, - dataProductName, - body, - options, - ); - return _listRolesAssignmentsDeserialize(result); + properties: DataProductUpdate, + options: DataProductsUpdateOptionalParams = { requestOptions: {} }, +): PollerLike, DataProduct> { + return getLongRunningPoller(context, _updateDeserialize, ["200", "202"], { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _updateSend( + context, + resourceGroupName, + dataProductName, + properties, + options, + ), + resourceLocationConfig: "location", + }) as PollerLike, DataProduct>; } -export function _listByResourceGroupSend( +export function _getSend( context: Client, - subscriptionId: string, resourceGroupName: string, - options: DataProductsListByResourceGroupOptionalParams = { - requestOptions: {}, - }, + dataProductName: string, + options: DataProductsGetOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", + context.subscriptionId, resourceGroupName, + dataProductName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _listByResourceGroupDeserialize( +export async function _getDeserialize( result: PathUncheckedResponse, -): Promise<_DataProductListResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _dataProductListResultDeserializer(result.body); + return dataProductDeserializer(result.body); } -/** List data products by resource group. */ -export function listByResourceGroup( +/** Retrieve data product resource. */ +export async function get( context: Client, - subscriptionId: string, resourceGroupName: string, - options: DataProductsListByResourceGroupOptionalParams = { - requestOptions: {}, - }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + dataProductName: string, + options: DataProductsGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend( context, - () => - _listByResourceGroupSend( - context, - subscriptionId, - resourceGroupName, - options, - ), - _listByResourceGroupDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + resourceGroupName, + dataProductName, + options, ); + return _getDeserialize(result); } -export function _listBySubscriptionSend( +export function _createSend( context: Client, - subscriptionId: string, - options: DataProductsListBySubscriptionOptionalParams = { - requestOptions: {}, - }, + resourceGroupName: string, + dataProductName: string, + resource: DataProduct, + options: DataProductsCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/providers/Microsoft.NetworkAnalytics/dataProducts", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}", + context.subscriptionId, + resourceGroupName, + dataProductName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .put({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: dataProductSerializer(resource), + }); } -export async function _listBySubscriptionDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, -): Promise<_DataProductListResult> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["200", "201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _dataProductListResultDeserializer(result.body); + return dataProductDeserializer(result.body); } -/** List data products by subscription. */ -export function listBySubscription( +/** Create data product resource. */ +export function create( context: Client, - subscriptionId: string, - options: DataProductsListBySubscriptionOptionalParams = { - requestOptions: {}, - }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listBySubscriptionSend(context, subscriptionId, options), - _listBySubscriptionDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); + resourceGroupName: string, + dataProductName: string, + resource: DataProduct, + options: DataProductsCreateOptionalParams = { requestOptions: {} }, +): PollerLike, DataProduct> { + return getLongRunningPoller(context, _createDeserialize, ["200", "201"], { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _createSend( + context, + resourceGroupName, + dataProductName, + resource, + options, + ), + resourceLocationConfig: "azure-async-operation", + }) as PollerLike, DataProduct>; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProductsCatalogs/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProductsCatalogs/index.ts index 832580feac..674a845b38 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProductsCatalogs/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataProductsCatalogs/index.ts @@ -24,51 +24,56 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _getSend( +export function _listBySubscriptionSend( context: Client, - subscriptionId: string, - resourceGroupName: string, - options: DataProductsCatalogsGetOptionalParams = { requestOptions: {} }, + options: DataProductsCatalogsListBySubscriptionOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProductsCatalogs/default", - subscriptionId, - resourceGroupName, + "/subscriptions/{subscriptionId}/providers/Microsoft.NetworkAnalytics/dataProductsCatalogs", + context.subscriptionId, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getDeserialize( +export async function _listBySubscriptionDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_DataProductsCatalogListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataProductsCatalogDeserializer(result.body); + return _dataProductsCatalogListResultDeserializer(result.body); } -/** Retrieve data type resource. */ -export async function get( +/** List data catalog by subscription. */ +export function listBySubscription( context: Client, - subscriptionId: string, - resourceGroupName: string, - options: DataProductsCatalogsGetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getSend( + options: DataProductsCatalogsListBySubscriptionOptionalParams = { + requestOptions: {}, + }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - subscriptionId, - resourceGroupName, - options, + () => _listBySubscriptionSend(context, options), + _listBySubscriptionDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _getDeserialize(result); } export function _listByResourceGroupSend( context: Client, - subscriptionId: string, resourceGroupName: string, options: DataProductsCatalogsListByResourceGroupOptionalParams = { requestOptions: {}, @@ -77,10 +82,17 @@ export function _listByResourceGroupSend( return context .path( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProductsCatalogs", - subscriptionId, + context.subscriptionId, resourceGroupName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _listByResourceGroupDeserialize( @@ -97,7 +109,6 @@ export async function _listByResourceGroupDeserialize( /** List data catalog by resource group. */ export function listByResourceGroup( context: Client, - subscriptionId: string, resourceGroupName: string, options: DataProductsCatalogsListByResourceGroupOptionalParams = { requestOptions: {}, @@ -105,58 +116,51 @@ export function listByResourceGroup( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => - _listByResourceGroupSend( - context, - subscriptionId, - resourceGroupName, - options, - ), + () => _listByResourceGroupSend(context, resourceGroupName, options), _listByResourceGroupDeserialize, ["200"], { itemName: "value", nextLinkName: "nextLink" }, ); } -export function _listBySubscriptionSend( +export function _getSend( context: Client, - subscriptionId: string, - options: DataProductsCatalogsListBySubscriptionOptionalParams = { - requestOptions: {}, - }, + resourceGroupName: string, + options: DataProductsCatalogsGetOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/providers/Microsoft.NetworkAnalytics/dataProductsCatalogs", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProductsCatalogs/default", + context.subscriptionId, + resourceGroupName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _listBySubscriptionDeserialize( +export async function _getDeserialize( result: PathUncheckedResponse, -): Promise<_DataProductsCatalogListResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _dataProductsCatalogListResultDeserializer(result.body); + return dataProductsCatalogDeserializer(result.body); } -/** List data catalog by subscription. */ -export function listBySubscription( +/** Retrieve data type resource. */ +export async function get( context: Client, - subscriptionId: string, - options: DataProductsCatalogsListBySubscriptionOptionalParams = { - requestOptions: {}, - }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listBySubscriptionSend(context, subscriptionId, options), - _listBySubscriptionDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); + resourceGroupName: string, + options: DataProductsCatalogsGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend(context, resourceGroupName, options); + return _getDeserialize(result); } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataTypes/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataTypes/index.ts index 0e1f70a78f..a6244da7f9 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataTypes/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/dataTypes/index.ts @@ -38,181 +38,196 @@ import { } from "@azure-rest/core-client"; import { PollerLike, OperationState } from "@azure/core-lro"; -export function _createSend( +export function _listByDataProductSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - dataTypeName: string, - resource: DataType, - options: DataTypesCreateOptionalParams = { requestOptions: {} }, + options: DataTypesListByDataProductOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes", + context.subscriptionId, resourceGroupName, dataProductName, - dataTypeName, ) - .put({ + .get({ ...operationOptionsToRequestParameters(options), - body: dataTypeSerializer(resource), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createDeserialize( +export async function _listByDataProductDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "201"]; +): Promise<_DataTypeListResult> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataTypeDeserializer(result.body); + return _dataTypeListResultDeserializer(result.body); } -/** Create data type resource. */ -export function create( +/** List data type by parent resource. */ +export function listByDataProduct( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - dataTypeName: string, - resource: DataType, - options: DataTypesCreateOptionalParams = { requestOptions: {} }, -): PollerLike, DataType> { - return getLongRunningPoller(context, _createDeserialize, ["200", "201"], { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _createSend( + options: DataTypesListByDataProductOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => + _listByDataProductSend( context, - subscriptionId, resourceGroupName, dataProductName, - dataTypeName, - resource, options, ), - resourceLocationConfig: "azure-async-operation", - }) as PollerLike, DataType>; + _listByDataProductDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); } -export function _getSend( +export function _generateStorageContainerSasTokenSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - options: DataTypesGetOptionalParams = { requestOptions: {} }, + body: ContainerSaS, + options: DataTypesGenerateStorageContainerSasTokenOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}/generateStorageContainerSasToken", + context.subscriptionId, resourceGroupName, dataProductName, dataTypeName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: containerSaSSerializer(body), + }); } -export async function _getDeserialize( +export async function _generateStorageContainerSasTokenDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataTypeDeserializer(result.body); + return containerSasTokenDeserializer(result.body); } -/** Retrieve data type resource. */ -export async function get( +/** Generate sas token for storage container. */ +export async function generateStorageContainerSasToken( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - options: DataTypesGetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getSend( + body: ContainerSaS, + options: DataTypesGenerateStorageContainerSasTokenOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _generateStorageContainerSasTokenSend( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, + body, options, ); - return _getDeserialize(result); + return _generateStorageContainerSasTokenDeserialize(result); } -export function _updateSend( +export function _deleteDataSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - properties: DataTypeUpdate, - options: DataTypesUpdateOptionalParams = { requestOptions: {} }, + body: Record, + options: DataTypesDeleteDataOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}/deleteData", + context.subscriptionId, resourceGroupName, dataProductName, dataTypeName, ) - .patch({ + .post({ ...operationOptionsToRequestParameters(options), - body: dataTypeUpdateSerializer(properties), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: _deleteDataRequestSerializer(body), }); } -export async function _updateDeserialize( +export async function _deleteDataDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "202"]; +): Promise { + const expectedStatuses = ["202", "204", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dataTypeDeserializer(result.body); + return; } -/** Update data type resource. */ -export function update( +/** Delete data for data type. */ +export function deleteData( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - properties: DataTypeUpdate, - options: DataTypesUpdateOptionalParams = { requestOptions: {} }, -): PollerLike, DataType> { - return getLongRunningPoller(context, _updateDeserialize, ["200", "202"], { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _updateSend( - context, - subscriptionId, - resourceGroupName, - dataProductName, - dataTypeName, - properties, - options, - ), - resourceLocationConfig: "location", - }) as PollerLike, DataType>; + body: Record, + options: DataTypesDeleteDataOptionalParams = { requestOptions: {} }, +): PollerLike, void> { + return getLongRunningPoller( + context, + _deleteDataDeserialize, + ["202", "204", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _deleteDataSend( + context, + resourceGroupName, + dataProductName, + dataTypeName, + body, + options, + ), + resourceLocationConfig: "location", + }, + ) as PollerLike, void>; } export function _$deleteSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -221,12 +236,19 @@ export function _$deleteSend( return context .path( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", - subscriptionId, + context.subscriptionId, resourceGroupName, dataProductName, dataTypeName, ) - .delete({ ...operationOptionsToRequestParameters(options) }); + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _$deleteDeserialize( @@ -248,7 +270,6 @@ export async function _$deleteDeserialize( */ export function $delete( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, @@ -264,7 +285,6 @@ export function $delete( getInitialResponse: () => _$deleteSend( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, @@ -275,180 +295,184 @@ export function $delete( ) as PollerLike, void>; } -export function _deleteDataSend( +export function _updateSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: Record, - options: DataTypesDeleteDataOptionalParams = { requestOptions: {} }, + properties: DataTypeUpdate, + options: DataTypesUpdateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}/deleteData", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", + context.subscriptionId, resourceGroupName, dataProductName, dataTypeName, ) - .post({ + .patch({ ...operationOptionsToRequestParameters(options), - body: _deleteDataRequestSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: dataTypeUpdateSerializer(properties), }); } -export async function _deleteDataDeserialize( +export async function _updateDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["202", "204", "200"]; +): Promise { + const expectedStatuses = ["200", "202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return dataTypeDeserializer(result.body); } -/** Delete data for data type. */ -export function deleteData( +/** Update data type resource. */ +export function update( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: Record, - options: DataTypesDeleteDataOptionalParams = { requestOptions: {} }, -): PollerLike, void> { - return getLongRunningPoller( - context, - _deleteDataDeserialize, - ["202", "204", "200"], - { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _deleteDataSend( - context, - subscriptionId, - resourceGroupName, - dataProductName, - dataTypeName, - body, - options, - ), - resourceLocationConfig: "location", - }, - ) as PollerLike, void>; + properties: DataTypeUpdate, + options: DataTypesUpdateOptionalParams = { requestOptions: {} }, +): PollerLike, DataType> { + return getLongRunningPoller(context, _updateDeserialize, ["200", "202"], { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _updateSend( + context, + resourceGroupName, + dataProductName, + dataTypeName, + properties, + options, + ), + resourceLocationConfig: "location", + }) as PollerLike, DataType>; } -export function _generateStorageContainerSasTokenSend( +export function _getSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: ContainerSaS, - options: DataTypesGenerateStorageContainerSasTokenOptionalParams = { - requestOptions: {}, - }, + options: DataTypesGetOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}/generateStorageContainerSasToken", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", + context.subscriptionId, resourceGroupName, dataProductName, dataTypeName, ) - .post({ + .get({ ...operationOptionsToRequestParameters(options), - body: containerSaSSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _generateStorageContainerSasTokenDeserialize( +export async function _getDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return containerSasTokenDeserializer(result.body); + return dataTypeDeserializer(result.body); } -/** Generate sas token for storage container. */ -export async function generateStorageContainerSasToken( +/** Retrieve data type resource. */ +export async function get( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: ContainerSaS, - options: DataTypesGenerateStorageContainerSasTokenOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _generateStorageContainerSasTokenSend( + options: DataTypesGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, - body, options, ); - return _generateStorageContainerSasTokenDeserialize(result); + return _getDeserialize(result); } -export function _listByDataProductSend( +export function _createSend( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - options: DataTypesListByDataProductOptionalParams = { requestOptions: {} }, + dataTypeName: string, + resource: DataType, + options: DataTypesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes", - subscriptionId, + "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}", + context.subscriptionId, resourceGroupName, dataProductName, + dataTypeName, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .put({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: dataTypeSerializer(resource), + }); } -export async function _listByDataProductDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, -): Promise<_DataTypeListResult> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["200", "201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _dataTypeListResultDeserializer(result.body); + return dataTypeDeserializer(result.body); } -/** List data type by parent resource. */ -export function listByDataProduct( +/** Create data type resource. */ +export function create( context: Client, - subscriptionId: string, resourceGroupName: string, dataProductName: string, - options: DataTypesListByDataProductOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => - _listByDataProductSend( + dataTypeName: string, + resource: DataType, + options: DataTypesCreateOptionalParams = { requestOptions: {} }, +): PollerLike, DataType> { + return getLongRunningPoller(context, _createDeserialize, ["200", "201"], { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _createSend( context, - subscriptionId, resourceGroupName, dataProductName, + dataTypeName, + resource, options, ), - _listByDataProductDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); + resourceLocationConfig: "azure-async-operation", + }) as PollerLike, DataType>; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/index.ts index 40148cb69c..1d3346b318 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/index.ts @@ -7,26 +7,26 @@ export { NetworkAnalyticsClientOptionalParams, } from "./networkAnalyticsContext.js"; export { - OperationsListOptionalParams, - DataProductsCatalogsGetOptionalParams, - DataProductsCatalogsListByResourceGroupOptionalParams, - DataProductsCatalogsListBySubscriptionOptionalParams, - DataTypesCreateOptionalParams, - DataTypesGetOptionalParams, - DataTypesUpdateOptionalParams, - DataTypesDeleteOptionalParams, - DataTypesDeleteDataOptionalParams, - DataTypesGenerateStorageContainerSasTokenOptionalParams, - DataTypesListByDataProductOptionalParams, - DataProductsCreateOptionalParams, - DataProductsGetOptionalParams, - DataProductsUpdateOptionalParams, - DataProductsDeleteOptionalParams, - DataProductsGenerateStorageAccountSasTokenOptionalParams, - DataProductsRotateKeyOptionalParams, - DataProductsAddUserRoleOptionalParams, - DataProductsRemoveUserRoleOptionalParams, - DataProductsListRolesAssignmentsOptionalParams, - DataProductsListByResourceGroupOptionalParams, DataProductsListBySubscriptionOptionalParams, + DataProductsListByResourceGroupOptionalParams, + DataProductsListRolesAssignmentsOptionalParams, + DataProductsRemoveUserRoleOptionalParams, + DataProductsAddUserRoleOptionalParams, + DataProductsRotateKeyOptionalParams, + DataProductsGenerateStorageAccountSasTokenOptionalParams, + DataProductsDeleteOptionalParams, + DataProductsUpdateOptionalParams, + DataProductsGetOptionalParams, + DataProductsCreateOptionalParams, + DataTypesListByDataProductOptionalParams, + DataTypesGenerateStorageContainerSasTokenOptionalParams, + DataTypesDeleteDataOptionalParams, + DataTypesDeleteOptionalParams, + DataTypesUpdateOptionalParams, + DataTypesGetOptionalParams, + DataTypesCreateOptionalParams, + DataProductsCatalogsListBySubscriptionOptionalParams, + DataProductsCatalogsListByResourceGroupOptionalParams, + DataProductsCatalogsGetOptionalParams, + OperationsListOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/networkAnalyticsContext.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/networkAnalyticsContext.ts index 17097bfcd7..1ebeda066f 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/networkAnalyticsContext.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/networkAnalyticsContext.ts @@ -6,7 +6,13 @@ import { KnownVersions } from "../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface NetworkAnalyticsContext extends Client {} +export interface NetworkAnalyticsContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; + /** The ID of the target subscription. The value must be an UUID. */ + subscriptionId: string; +} /** Optional parameters for the client. */ export interface NetworkAnalyticsClientOptionalParams extends ClientOptions { @@ -17,10 +23,11 @@ export interface NetworkAnalyticsClientOptionalParams extends ClientOptions { export function createNetworkAnalytics( credential: TokenCredential, + subscriptionId: string, options: NetworkAnalyticsClientOptionalParams = {}, ): NetworkAnalyticsContext { const endpointUrl = - options.endpoint ?? options.baseUrl ?? `https://management.azure.com`; + options.endpoint ?? options.baseUrl ?? "https://management.azure.com"; const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-arm-networkanalytics/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -52,5 +59,9 @@ export function createNetworkAnalytics( return next(req); }, }); - return clientContext; + return { + ...clientContext, + apiVersion, + subscriptionId, + } as NetworkAnalyticsContext; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/operations/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/operations/index.ts index 7b12dfd9dc..ba69d03fde 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/operations/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/operations/index.ts @@ -27,7 +27,14 @@ export function _listSend( ): StreamableMethod { return context .path("/providers/Microsoft.NetworkAnalytics/operations") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _listDeserialize( diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/options.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/options.ts index d93bfef490..c8e5e96a77 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/options.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/api/options.ts @@ -4,99 +4,99 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface OperationsListOptionalParams extends OperationOptions {} +export interface DataProductsListBySubscriptionOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsCatalogsGetOptionalParams +export interface DataProductsListByResourceGroupOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsCatalogsListByResourceGroupOptionalParams +export interface DataProductsListRolesAssignmentsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsCatalogsListBySubscriptionOptionalParams +export interface DataProductsRemoveUserRoleOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataTypesCreateOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; -} +export interface DataProductsAddUserRoleOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface DataTypesGetOptionalParams extends OperationOptions {} +export interface DataProductsRotateKeyOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataTypesUpdateOptionalParams extends OperationOptions { +export interface DataProductsGenerateStorageAccountSasTokenOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface DataProductsDeleteOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } /** Optional parameters. */ -export interface DataTypesDeleteOptionalParams extends OperationOptions { +export interface DataProductsUpdateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } /** Optional parameters. */ -export interface DataTypesDeleteDataOptionalParams extends OperationOptions { +export interface DataProductsGetOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface DataProductsCreateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } /** Optional parameters. */ -export interface DataTypesGenerateStorageContainerSasTokenOptionalParams +export interface DataTypesListByDataProductOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataTypesListByDataProductOptionalParams +export interface DataTypesGenerateStorageContainerSasTokenOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsCreateOptionalParams extends OperationOptions { +export interface DataTypesDeleteDataOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } /** Optional parameters. */ -export interface DataProductsGetOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface DataProductsUpdateOptionalParams extends OperationOptions { +export interface DataTypesDeleteOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } /** Optional parameters. */ -export interface DataProductsDeleteOptionalParams extends OperationOptions { +export interface DataTypesUpdateOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; } /** Optional parameters. */ -export interface DataProductsGenerateStorageAccountSasTokenOptionalParams - extends OperationOptions {} - -/** Optional parameters. */ -export interface DataProductsRotateKeyOptionalParams extends OperationOptions {} +export interface DataTypesGetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsAddUserRoleOptionalParams - extends OperationOptions {} +export interface DataTypesCreateOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; +} /** Optional parameters. */ -export interface DataProductsRemoveUserRoleOptionalParams +export interface DataProductsCatalogsListBySubscriptionOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsListRolesAssignmentsOptionalParams +export interface DataProductsCatalogsListByResourceGroupOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsListByResourceGroupOptionalParams +export interface DataProductsCatalogsGetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DataProductsListBySubscriptionOptionalParams - extends OperationOptions {} +export interface OperationsListOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProducts/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProducts/index.ts index 5c31e36ded..e57e918d4f 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProducts/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProducts/index.ts @@ -3,17 +3,17 @@ import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; import { - create, - get, - update, - $delete, - generateStorageAccountSasToken, - rotateKey, - addUserRole, - removeUserRole, - listRolesAssignments, - listByResourceGroup, listBySubscription, + listByResourceGroup, + listRolesAssignments, + removeUserRole, + addUserRole, + rotateKey, + generateStorageAccountSasToken, + $delete, + update, + get, + create, } from "../../api/dataProducts/index.js"; import { DataProduct, @@ -28,52 +28,58 @@ import { import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; import { - DataProductsCreateOptionalParams, - DataProductsGetOptionalParams, - DataProductsUpdateOptionalParams, - DataProductsDeleteOptionalParams, - DataProductsGenerateStorageAccountSasTokenOptionalParams, - DataProductsRotateKeyOptionalParams, - DataProductsAddUserRoleOptionalParams, - DataProductsRemoveUserRoleOptionalParams, - DataProductsListRolesAssignmentsOptionalParams, - DataProductsListByResourceGroupOptionalParams, DataProductsListBySubscriptionOptionalParams, + DataProductsListByResourceGroupOptionalParams, + DataProductsListRolesAssignmentsOptionalParams, + DataProductsRemoveUserRoleOptionalParams, + DataProductsAddUserRoleOptionalParams, + DataProductsRotateKeyOptionalParams, + DataProductsGenerateStorageAccountSasTokenOptionalParams, + DataProductsDeleteOptionalParams, + DataProductsUpdateOptionalParams, + DataProductsGetOptionalParams, + DataProductsCreateOptionalParams, } from "../../api/options.js"; /** Interface representing a DataProducts operations. */ export interface DataProductsOperations { - /** Create data product resource. */ - create: ( + /** List data products by subscription. */ + listBySubscription: ( + options?: DataProductsListBySubscriptionOptionalParams, + ) => PagedAsyncIterableIterator; + /** List data products by resource group. */ + listByResourceGroup: ( + resourceGroupName: string, + options?: DataProductsListByResourceGroupOptionalParams, + ) => PagedAsyncIterableIterator; + /** List user roles associated with the data product. */ + listRolesAssignments: ( resourceGroupName: string, dataProductName: string, - resource: DataProduct, - options?: DataProductsCreateOptionalParams, - ) => PollerLike, DataProduct>; - /** Retrieve data product resource. */ - get: ( + body: Record, + options?: DataProductsListRolesAssignmentsOptionalParams, + ) => Promise; + /** Remove role from the data product. */ + removeUserRole: ( resourceGroupName: string, dataProductName: string, - options?: DataProductsGetOptionalParams, - ) => Promise; - /** Update data product resource. */ - update: ( + body: RoleAssignmentDetail, + options?: DataProductsRemoveUserRoleOptionalParams, + ) => Promise; + /** Assign role to the data product. */ + addUserRole: ( resourceGroupName: string, dataProductName: string, - properties: DataProductUpdate, - options?: DataProductsUpdateOptionalParams, - ) => PollerLike, DataProduct>; - /** Delete data product resource. */ - /** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ - delete: ( + body: RoleAssignmentCommonProperties, + options?: DataProductsAddUserRoleOptionalParams, + ) => Promise; + /** Initiate key rotation on Data Product. */ + rotateKey: ( resourceGroupName: string, dataProductName: string, - options?: DataProductsDeleteOptionalParams, - ) => PollerLike, void>; + body: KeyVaultInfo, + options?: DataProductsRotateKeyOptionalParams, + ) => Promise; /** Generate sas token for storage account. */ generateStorageAccountSasToken: ( resourceGroupName: string, @@ -81,96 +87,87 @@ export interface DataProductsOperations { body: AccountSas, options?: DataProductsGenerateStorageAccountSasTokenOptionalParams, ) => Promise; - /** Initiate key rotation on Data Product. */ - rotateKey: ( + /** Delete data product resource. */ + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ + delete: ( resourceGroupName: string, dataProductName: string, - body: KeyVaultInfo, - options?: DataProductsRotateKeyOptionalParams, - ) => Promise; - /** Assign role to the data product. */ - addUserRole: ( + options?: DataProductsDeleteOptionalParams, + ) => PollerLike, void>; + /** Update data product resource. */ + update: ( resourceGroupName: string, dataProductName: string, - body: RoleAssignmentCommonProperties, - options?: DataProductsAddUserRoleOptionalParams, - ) => Promise; - /** Remove role from the data product. */ - removeUserRole: ( + properties: DataProductUpdate, + options?: DataProductsUpdateOptionalParams, + ) => PollerLike, DataProduct>; + /** Retrieve data product resource. */ + get: ( resourceGroupName: string, dataProductName: string, - body: RoleAssignmentDetail, - options?: DataProductsRemoveUserRoleOptionalParams, - ) => Promise; - /** List user roles associated with the data product. */ - listRolesAssignments: ( + options?: DataProductsGetOptionalParams, + ) => Promise; + /** Create data product resource. */ + create: ( resourceGroupName: string, dataProductName: string, - body: Record, - options?: DataProductsListRolesAssignmentsOptionalParams, - ) => Promise; - /** List data products by resource group. */ - listByResourceGroup: ( - resourceGroupName: string, - options?: DataProductsListByResourceGroupOptionalParams, - ) => PagedAsyncIterableIterator; - /** List data products by subscription. */ - listBySubscription: ( - options?: DataProductsListBySubscriptionOptionalParams, - ) => PagedAsyncIterableIterator; + resource: DataProduct, + options?: DataProductsCreateOptionalParams, + ) => PollerLike, DataProduct>; } -export function getDataProducts( - context: NetworkAnalyticsContext, - subscriptionId: string, -) { +export function getDataProducts(context: NetworkAnalyticsContext) { return { - create: ( + listBySubscription: ( + options?: DataProductsListBySubscriptionOptionalParams, + ) => listBySubscription(context, options), + listByResourceGroup: ( + resourceGroupName: string, + options?: DataProductsListByResourceGroupOptionalParams, + ) => listByResourceGroup(context, resourceGroupName, options), + listRolesAssignments: ( resourceGroupName: string, dataProductName: string, - resource: DataProduct, - options?: DataProductsCreateOptionalParams, + body: Record, + options?: DataProductsListRolesAssignmentsOptionalParams, ) => - create( + listRolesAssignments( context, - subscriptionId, resourceGroupName, dataProductName, - resource, + body, options, ), - get: ( - resourceGroupName: string, - dataProductName: string, - options?: DataProductsGetOptionalParams, - ) => - get(context, subscriptionId, resourceGroupName, dataProductName, options), - update: ( + removeUserRole: ( resourceGroupName: string, dataProductName: string, - properties: DataProductUpdate, - options?: DataProductsUpdateOptionalParams, + body: RoleAssignmentDetail, + options?: DataProductsRemoveUserRoleOptionalParams, ) => - update( + removeUserRole( context, - subscriptionId, resourceGroupName, dataProductName, - properties, + body, options, ), - delete: ( + addUserRole: ( resourceGroupName: string, dataProductName: string, - options?: DataProductsDeleteOptionalParams, + body: RoleAssignmentCommonProperties, + options?: DataProductsAddUserRoleOptionalParams, ) => - $delete( - context, - subscriptionId, - resourceGroupName, - dataProductName, - options, - ), + addUserRole(context, resourceGroupName, dataProductName, body, options), + rotateKey: ( + resourceGroupName: string, + dataProductName: string, + body: KeyVaultInfo, + options?: DataProductsRotateKeyOptionalParams, + ) => rotateKey(context, resourceGroupName, dataProductName, body, options), generateStorageAccountSasToken: ( resourceGroupName: string, dataProductName: string, @@ -179,84 +176,41 @@ export function getDataProducts( ) => generateStorageAccountSasToken( context, - subscriptionId, resourceGroupName, dataProductName, body, options, ), - rotateKey: ( + delete: ( resourceGroupName: string, dataProductName: string, - body: KeyVaultInfo, - options?: DataProductsRotateKeyOptionalParams, - ) => - rotateKey( - context, - subscriptionId, - resourceGroupName, - dataProductName, - body, - options, - ), - addUserRole: ( + options?: DataProductsDeleteOptionalParams, + ) => $delete(context, resourceGroupName, dataProductName, options), + update: ( resourceGroupName: string, dataProductName: string, - body: RoleAssignmentCommonProperties, - options?: DataProductsAddUserRoleOptionalParams, + properties: DataProductUpdate, + options?: DataProductsUpdateOptionalParams, ) => - addUserRole( - context, - subscriptionId, - resourceGroupName, - dataProductName, - body, - options, - ), - removeUserRole: ( + update(context, resourceGroupName, dataProductName, properties, options), + get: ( resourceGroupName: string, dataProductName: string, - body: RoleAssignmentDetail, - options?: DataProductsRemoveUserRoleOptionalParams, - ) => - removeUserRole( - context, - subscriptionId, - resourceGroupName, - dataProductName, - body, - options, - ), - listRolesAssignments: ( + options?: DataProductsGetOptionalParams, + ) => get(context, resourceGroupName, dataProductName, options), + create: ( resourceGroupName: string, dataProductName: string, - body: Record, - options?: DataProductsListRolesAssignmentsOptionalParams, - ) => - listRolesAssignments( - context, - subscriptionId, - resourceGroupName, - dataProductName, - body, - options, - ), - listByResourceGroup: ( - resourceGroupName: string, - options?: DataProductsListByResourceGroupOptionalParams, - ) => - listByResourceGroup(context, subscriptionId, resourceGroupName, options), - listBySubscription: ( - options?: DataProductsListBySubscriptionOptionalParams, - ) => listBySubscription(context, subscriptionId, options), + resource: DataProduct, + options?: DataProductsCreateOptionalParams, + ) => create(context, resourceGroupName, dataProductName, resource, options), }; } export function getDataProductsOperations( context: NetworkAnalyticsContext, - subscriptionId: string, ): DataProductsOperations { return { - ...getDataProducts(context, subscriptionId), + ...getDataProducts(context), }; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProductsCatalogs/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProductsCatalogs/index.ts index d7048a6b20..122ef0bfbc 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProductsCatalogs/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataProductsCatalogs/index.ts @@ -3,61 +3,56 @@ import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; import { - get, - listByResourceGroup, listBySubscription, + listByResourceGroup, + get, } from "../../api/dataProductsCatalogs/index.js"; import { DataProductsCatalog } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { - DataProductsCatalogsGetOptionalParams, - DataProductsCatalogsListByResourceGroupOptionalParams, DataProductsCatalogsListBySubscriptionOptionalParams, + DataProductsCatalogsListByResourceGroupOptionalParams, + DataProductsCatalogsGetOptionalParams, } from "../../api/options.js"; /** Interface representing a DataProductsCatalogs operations. */ export interface DataProductsCatalogsOperations { - /** Retrieve data type resource. */ - get: ( - resourceGroupName: string, - options?: DataProductsCatalogsGetOptionalParams, - ) => Promise; + /** List data catalog by subscription. */ + listBySubscription: ( + options?: DataProductsCatalogsListBySubscriptionOptionalParams, + ) => PagedAsyncIterableIterator; /** List data catalog by resource group. */ listByResourceGroup: ( resourceGroupName: string, options?: DataProductsCatalogsListByResourceGroupOptionalParams, ) => PagedAsyncIterableIterator; - /** List data catalog by subscription. */ - listBySubscription: ( - options?: DataProductsCatalogsListBySubscriptionOptionalParams, - ) => PagedAsyncIterableIterator; + /** Retrieve data type resource. */ + get: ( + resourceGroupName: string, + options?: DataProductsCatalogsGetOptionalParams, + ) => Promise; } -export function getDataProductsCatalogs( - context: NetworkAnalyticsContext, - subscriptionId: string, -) { +export function getDataProductsCatalogs(context: NetworkAnalyticsContext) { return { - get: ( - resourceGroupName: string, - options?: DataProductsCatalogsGetOptionalParams, - ) => get(context, subscriptionId, resourceGroupName, options), + listBySubscription: ( + options?: DataProductsCatalogsListBySubscriptionOptionalParams, + ) => listBySubscription(context, options), listByResourceGroup: ( resourceGroupName: string, options?: DataProductsCatalogsListByResourceGroupOptionalParams, - ) => - listByResourceGroup(context, subscriptionId, resourceGroupName, options), - listBySubscription: ( - options?: DataProductsCatalogsListBySubscriptionOptionalParams, - ) => listBySubscription(context, subscriptionId, options), + ) => listByResourceGroup(context, resourceGroupName, options), + get: ( + resourceGroupName: string, + options?: DataProductsCatalogsGetOptionalParams, + ) => get(context, resourceGroupName, options), }; } export function getDataProductsCatalogsOperations( context: NetworkAnalyticsContext, - subscriptionId: string, ): DataProductsCatalogsOperations { return { - ...getDataProductsCatalogs(context, subscriptionId), + ...getDataProductsCatalogs(context), }; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataTypes/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataTypes/index.ts index ee6fad5bd4..bc9a766948 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataTypes/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/classic/dataTypes/index.ts @@ -3,13 +3,13 @@ import { NetworkAnalyticsContext } from "../../api/networkAnalyticsContext.js"; import { - create, - get, - update, - $delete, - deleteData, - generateStorageContainerSasToken, listByDataProduct, + generateStorageContainerSasToken, + deleteData, + $delete, + update, + get, + create, } from "../../api/dataTypes/index.js"; import { DataType, @@ -20,40 +20,39 @@ import { import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { PollerLike, OperationState } from "@azure/core-lro"; import { - DataTypesCreateOptionalParams, - DataTypesGetOptionalParams, - DataTypesUpdateOptionalParams, - DataTypesDeleteOptionalParams, - DataTypesDeleteDataOptionalParams, - DataTypesGenerateStorageContainerSasTokenOptionalParams, DataTypesListByDataProductOptionalParams, + DataTypesGenerateStorageContainerSasTokenOptionalParams, + DataTypesDeleteDataOptionalParams, + DataTypesDeleteOptionalParams, + DataTypesUpdateOptionalParams, + DataTypesGetOptionalParams, + DataTypesCreateOptionalParams, } from "../../api/options.js"; /** Interface representing a DataTypes operations. */ export interface DataTypesOperations { - /** Create data type resource. */ - create: ( + /** List data type by parent resource. */ + listByDataProduct: ( resourceGroupName: string, dataProductName: string, - dataTypeName: string, - resource: DataType, - options?: DataTypesCreateOptionalParams, - ) => PollerLike, DataType>; - /** Retrieve data type resource. */ - get: ( + options?: DataTypesListByDataProductOptionalParams, + ) => PagedAsyncIterableIterator; + /** Generate sas token for storage container. */ + generateStorageContainerSasToken: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - options?: DataTypesGetOptionalParams, - ) => Promise; - /** Update data type resource. */ - update: ( + body: ContainerSaS, + options?: DataTypesGenerateStorageContainerSasTokenOptionalParams, + ) => Promise; + /** Delete data for data type. */ + deleteData: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - properties: DataTypeUpdate, - options?: DataTypesUpdateOptionalParams, - ) => PollerLike, DataType>; + body: Record, + options?: DataTypesDeleteDataOptionalParams, + ) => PollerLike, void>; /** Delete data type resource. */ /** * @fixme delete is a reserved word that cannot be used as an operation name. @@ -66,79 +65,67 @@ export interface DataTypesOperations { dataTypeName: string, options?: DataTypesDeleteOptionalParams, ) => PollerLike, void>; - /** Delete data for data type. */ - deleteData: ( + /** Update data type resource. */ + update: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: Record, - options?: DataTypesDeleteDataOptionalParams, - ) => PollerLike, void>; - /** Generate sas token for storage container. */ - generateStorageContainerSasToken: ( + properties: DataTypeUpdate, + options?: DataTypesUpdateOptionalParams, + ) => PollerLike, DataType>; + /** Retrieve data type resource. */ + get: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: ContainerSaS, - options?: DataTypesGenerateStorageContainerSasTokenOptionalParams, - ) => Promise; - /** List data type by parent resource. */ - listByDataProduct: ( + options?: DataTypesGetOptionalParams, + ) => Promise; + /** Create data type resource. */ + create: ( resourceGroupName: string, dataProductName: string, - options?: DataTypesListByDataProductOptionalParams, - ) => PagedAsyncIterableIterator; + dataTypeName: string, + resource: DataType, + options?: DataTypesCreateOptionalParams, + ) => PollerLike, DataType>; } -export function getDataTypes( - context: NetworkAnalyticsContext, - subscriptionId: string, -) { +export function getDataTypes(context: NetworkAnalyticsContext) { return { - create: ( + listByDataProduct: ( resourceGroupName: string, dataProductName: string, - dataTypeName: string, - resource: DataType, - options?: DataTypesCreateOptionalParams, + options?: DataTypesListByDataProductOptionalParams, ) => - create( - context, - subscriptionId, - resourceGroupName, - dataProductName, - dataTypeName, - resource, - options, - ), - get: ( + listByDataProduct(context, resourceGroupName, dataProductName, options), + generateStorageContainerSasToken: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - options?: DataTypesGetOptionalParams, + body: ContainerSaS, + options?: DataTypesGenerateStorageContainerSasTokenOptionalParams, ) => - get( + generateStorageContainerSasToken( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, + body, options, ), - update: ( + deleteData: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - properties: DataTypeUpdate, - options?: DataTypesUpdateOptionalParams, + body: Record, + options?: DataTypesDeleteDataOptionalParams, ) => - update( + deleteData( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, - properties, + body, options, ), delete: ( @@ -149,54 +136,46 @@ export function getDataTypes( ) => $delete( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, options, ), - deleteData: ( + update: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: Record, - options?: DataTypesDeleteDataOptionalParams, + properties: DataTypeUpdate, + options?: DataTypesUpdateOptionalParams, ) => - deleteData( + update( context, - subscriptionId, resourceGroupName, dataProductName, dataTypeName, - body, + properties, options, ), - generateStorageContainerSasToken: ( + get: ( resourceGroupName: string, dataProductName: string, dataTypeName: string, - body: ContainerSaS, - options?: DataTypesGenerateStorageContainerSasTokenOptionalParams, + options?: DataTypesGetOptionalParams, ) => - generateStorageContainerSasToken( - context, - subscriptionId, - resourceGroupName, - dataProductName, - dataTypeName, - body, - options, - ), - listByDataProduct: ( + get(context, resourceGroupName, dataProductName, dataTypeName, options), + create: ( resourceGroupName: string, dataProductName: string, - options?: DataTypesListByDataProductOptionalParams, + dataTypeName: string, + resource: DataType, + options?: DataTypesCreateOptionalParams, ) => - listByDataProduct( + create( context, - subscriptionId, resourceGroupName, dataProductName, + dataTypeName, + resource, options, ), }; @@ -204,9 +183,8 @@ export function getDataTypes( export function getDataTypesOperations( context: NetworkAnalyticsContext, - subscriptionId: string, ): DataTypesOperations { return { - ...getDataTypes(context, subscriptionId), + ...getDataTypes(context), }; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/index.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/index.ts index ffc8e35dae..3ae1eb52fe 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/index.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/index.ts @@ -67,28 +67,28 @@ export { } from "./models/index.js"; export { NetworkAnalyticsClientOptionalParams, - OperationsListOptionalParams, - DataProductsCatalogsGetOptionalParams, - DataProductsCatalogsListByResourceGroupOptionalParams, - DataProductsCatalogsListBySubscriptionOptionalParams, - DataTypesCreateOptionalParams, - DataTypesGetOptionalParams, - DataTypesUpdateOptionalParams, - DataTypesDeleteOptionalParams, - DataTypesDeleteDataOptionalParams, - DataTypesGenerateStorageContainerSasTokenOptionalParams, - DataTypesListByDataProductOptionalParams, - DataProductsCreateOptionalParams, - DataProductsGetOptionalParams, - DataProductsUpdateOptionalParams, - DataProductsDeleteOptionalParams, - DataProductsGenerateStorageAccountSasTokenOptionalParams, - DataProductsRotateKeyOptionalParams, - DataProductsAddUserRoleOptionalParams, - DataProductsRemoveUserRoleOptionalParams, - DataProductsListRolesAssignmentsOptionalParams, - DataProductsListByResourceGroupOptionalParams, DataProductsListBySubscriptionOptionalParams, + DataProductsListByResourceGroupOptionalParams, + DataProductsListRolesAssignmentsOptionalParams, + DataProductsRemoveUserRoleOptionalParams, + DataProductsAddUserRoleOptionalParams, + DataProductsRotateKeyOptionalParams, + DataProductsGenerateStorageAccountSasTokenOptionalParams, + DataProductsDeleteOptionalParams, + DataProductsUpdateOptionalParams, + DataProductsGetOptionalParams, + DataProductsCreateOptionalParams, + DataTypesListByDataProductOptionalParams, + DataTypesGenerateStorageContainerSasTokenOptionalParams, + DataTypesDeleteDataOptionalParams, + DataTypesDeleteOptionalParams, + DataTypesUpdateOptionalParams, + DataTypesGetOptionalParams, + DataTypesCreateOptionalParams, + DataProductsCatalogsListBySubscriptionOptionalParams, + DataProductsCatalogsListByResourceGroupOptionalParams, + DataProductsCatalogsGetOptionalParams, + OperationsListOptionalParams, } from "./api/index.js"; export { DataProductsOperations, diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/networkAnalyticsClient.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/networkAnalyticsClient.ts index 3c50cba66f..6b314c7661 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/networkAnalyticsClient.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/networkAnalyticsClient.ts @@ -2,21 +2,21 @@ // Licensed under the MIT License. import { - getOperationsOperations, - OperationsOperations, -} from "./classic/operations/index.js"; -import { - getDataProductsCatalogsOperations, - DataProductsCatalogsOperations, -} from "./classic/dataProductsCatalogs/index.js"; + getDataProductsOperations, + DataProductsOperations, +} from "./classic/dataProducts/index.js"; import { getDataTypesOperations, DataTypesOperations, } from "./classic/dataTypes/index.js"; import { - getDataProductsOperations, - DataProductsOperations, -} from "./classic/dataProducts/index.js"; + getDataProductsCatalogsOperations, + DataProductsCatalogsOperations, +} from "./classic/dataProductsCatalogs/index.js"; +import { + getOperationsOperations, + OperationsOperations, +} from "./classic/operations/index.js"; import { createNetworkAnalytics, NetworkAnalyticsContext, @@ -41,26 +41,23 @@ export class NetworkAnalyticsClient { const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-client` : `azsdk-js-client`; - this._client = createNetworkAnalytics(credential, { + this._client = createNetworkAnalytics(credential, subscriptionId, { ...options, userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; + this.dataProducts = getDataProductsOperations(this._client); + this.dataTypes = getDataTypesOperations(this._client); + this.dataProductsCatalogs = getDataProductsCatalogsOperations(this._client); this.operations = getOperationsOperations(this._client); - this.dataProductsCatalogs = getDataProductsCatalogsOperations( - this._client, - subscriptionId, - ); - this.dataTypes = getDataTypesOperations(this._client, subscriptionId); - this.dataProducts = getDataProductsOperations(this._client, subscriptionId); } - /** The operation groups for Operations */ - public readonly operations: OperationsOperations; - /** The operation groups for DataProductsCatalogs */ - public readonly dataProductsCatalogs: DataProductsCatalogsOperations; - /** The operation groups for DataTypes */ - public readonly dataTypes: DataTypesOperations; - /** The operation groups for DataProducts */ + /** The operation groups for dataProducts */ public readonly dataProducts: DataProductsOperations; + /** The operation groups for dataTypes */ + public readonly dataTypes: DataTypesOperations; + /** The operation groups for dataProductsCatalogs */ + public readonly dataProductsCatalogs: DataProductsCatalogsOperations; + /** The operation groups for operations */ + public readonly operations: OperationsOperations; } diff --git a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/restorePollerHelpers.ts b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/restorePollerHelpers.ts index 9a0c76fdf0..c2b51a730a 100644 --- a/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/restorePollerHelpers.ts +++ b/packages/typespec-test/test/NetworkAnalytics.Management/generated/typespec-ts/sdk/test/arm-test/src/restorePollerHelpers.ts @@ -3,16 +3,16 @@ import { NetworkAnalyticsClient } from "./networkAnalyticsClient.js"; import { - _createDeserialize, - _updateDeserialize, _$deleteDeserialize, + _updateDeserialize, + _createDeserialize, +} from "./api/dataProducts/index.js"; +import { _deleteDataDeserialize, + _$deleteDeserialize as _$deleteDeserializeDataTypes, + _updateDeserialize as _updateDeserializeDataTypes, + _createDeserialize as _createDeserializeDataTypes, } from "./api/dataTypes/index.js"; -import { - _createDeserialize as _createDeserializeDataProducts, - _updateDeserialize as _updateDeserializeDataProducts, - _$deleteDeserialize as _$deleteDeserializeDataProducts, -} from "./api/dataProducts/index.js"; import { getLongRunningPoller } from "./static-helpers/pollingHelpers.js"; import { OperationOptions, @@ -91,34 +91,34 @@ interface DeserializationHelper { } const deserializeMap: Record = { - "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}": - { deserializer: _createDeserialize, expectedStatuses: ["200", "201"] }, - "PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}": - { deserializer: _updateDeserialize, expectedStatuses: ["200", "202"] }, - "DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}": + "DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}": { deserializer: _$deleteDeserialize, expectedStatuses: ["202", "204", "200"], }, + "PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}": + { deserializer: _updateDeserialize, expectedStatuses: ["200", "202"] }, + "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}": + { deserializer: _createDeserialize, expectedStatuses: ["200", "201"] }, "POST /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}/deleteData": { deserializer: _deleteDataDeserialize, expectedStatuses: ["202", "204", "200"], }, - "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}": + "DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}": { - deserializer: _createDeserializeDataProducts, - expectedStatuses: ["200", "201"], + deserializer: _$deleteDeserializeDataTypes, + expectedStatuses: ["202", "204", "200"], }, - "PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}": + "PATCH /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}": { - deserializer: _updateDeserializeDataProducts, + deserializer: _updateDeserializeDataTypes, expectedStatuses: ["200", "202"], }, - "DELETE /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}": + "PUT /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetworkAnalytics/dataProducts/{dataProductName}/dataTypes/{dataTypeName}": { - deserializer: _$deleteDeserializeDataProducts, - expectedStatuses: ["202", "204", "200"], + deserializer: _createDeserializeDataTypes, + expectedStatuses: ["200", "201"], }, }; diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/package.json b/packages/typespec-test/test/ai/generated/typespec-ts/package.json index a9a2f0b9b4..91fc31367a 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/ai/generated/typespec-ts/package.json @@ -13,9 +13,9 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/agents": "./src/api/agents/index.ts", + "./api/evaluations": "./src/api/evaluations/index.ts", "./api/connections": "./src/api/connections/index.ts", - "./api/evaluations": "./src/api/evaluations/index.ts" + "./api/agents": "./src/api/agents/index.ts" }, "dialects": [ "esm", @@ -127,22 +127,22 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/agents": { + "./api/evaluations": { "browser": { - "types": "./dist/browser/api/agents/index.d.ts", - "default": "./dist/browser/api/agents/index.js" + "types": "./dist/browser/api/evaluations/index.d.ts", + "default": "./dist/browser/api/evaluations/index.js" }, "react-native": { - "types": "./dist/react-native/api/agents/index.d.ts", - "default": "./dist/react-native/api/agents/index.js" + "types": "./dist/react-native/api/evaluations/index.d.ts", + "default": "./dist/react-native/api/evaluations/index.js" }, "import": { - "types": "./dist/esm/api/agents/index.d.ts", - "default": "./dist/esm/api/agents/index.js" + "types": "./dist/esm/api/evaluations/index.d.ts", + "default": "./dist/esm/api/evaluations/index.js" }, "require": { - "types": "./dist/commonjs/api/agents/index.d.ts", - "default": "./dist/commonjs/api/agents/index.js" + "types": "./dist/commonjs/api/evaluations/index.d.ts", + "default": "./dist/commonjs/api/evaluations/index.js" } }, "./api/connections": { @@ -163,22 +163,22 @@ "default": "./dist/commonjs/api/connections/index.js" } }, - "./api/evaluations": { + "./api/agents": { "browser": { - "types": "./dist/browser/api/evaluations/index.d.ts", - "default": "./dist/browser/api/evaluations/index.js" + "types": "./dist/browser/api/agents/index.d.ts", + "default": "./dist/browser/api/agents/index.js" }, "react-native": { - "types": "./dist/react-native/api/evaluations/index.d.ts", - "default": "./dist/react-native/api/evaluations/index.js" + "types": "./dist/react-native/api/agents/index.d.ts", + "default": "./dist/react-native/api/agents/index.js" }, "import": { - "types": "./dist/esm/api/evaluations/index.d.ts", - "default": "./dist/esm/api/evaluations/index.js" + "types": "./dist/esm/api/agents/index.d.ts", + "default": "./dist/esm/api/agents/index.js" }, "require": { - "types": "./dist/commonjs/api/evaluations/index.d.ts", - "default": "./dist/commonjs/api/evaluations/index.js" + "types": "./dist/commonjs/api/agents/index.d.ts", + "default": "./dist/commonjs/api/agents/index.js" } } }, diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/review/ai-client.api.md b/packages/typespec-test/test/ai/generated/typespec-ts/review/ai-client.api.md index a9a544d824..54365dac32 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/review/ai-client.api.md +++ b/packages/typespec-test/test/ai/generated/typespec-ts/review/ai-client.api.md @@ -363,7 +363,6 @@ export interface AgentsUpdateThreadOptionalParams extends OperationOptions { // @public export interface AgentsUploadFileOptionalParams extends OperationOptions { - contentType?: string; filename?: string; } @@ -633,7 +632,6 @@ export interface EvaluationsOperations { // @public export interface EvaluationsUpdateOptionalParams extends OperationOptions { clientRequestId?: string; - contentType?: string; } // @public diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/agents/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/agents/index.ts index aa87b78c7a..fa6e25d463 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/agents/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/agents/index.ts @@ -45,38 +45,37 @@ import { AzureAIContext as Client, } from "../index.js"; import { - toolDefinitionUnionSerializer, - codeInterpreterToolResourceSerializer, - fileSearchToolResourceSerializer, - connectionListResourceSerializer, - azureAISearchResourceSerializer, + toolResourcesSerializer, + toolDefinitionUnionArraySerializer, + agentsApiResponseFormatOptionSerializer, Agent, agentDeserializer, OpenAIPageableListOfAgent, openAIPageableListOfAgentDeserializer, AgentDeletionStatus, agentDeletionStatusDeserializer, - threadMessageOptionsSerializer, MessageRole, - messageAttachmentSerializer, + messageAttachmentArraySerializer, threadMessageOptionsArraySerializer, AgentThread, agentThreadDeserializer, ThreadDeletionStatus, threadDeletionStatusDeserializer, ThreadMessage, - threadMessageSerializer, threadMessageDeserializer, OpenAIPageableListOfThreadMessage, openAIPageableListOfThreadMessageDeserializer, + threadMessageArraySerializer, + truncationObjectSerializer, + agentsApiToolChoiceOptionSerializer, ThreadRun, threadRunDeserializer, - updateCodeInterpreterToolResourceOptionsSerializer, - updateFileSearchToolResourceOptionsSerializer, + updateToolResourcesOptionsSerializer, OpenAIPageableListOfThreadRun, openAIPageableListOfThreadRunDeserializer, ToolOutput, - toolOutputSerializer, + toolOutputArraySerializer, + agentThreadCreationOptionsSerializer, RunStep, runStepDeserializer, OpenAIPageableListOfRunStep, @@ -94,6 +93,8 @@ import { openAIPageableListOfVectorStoreDeserializer, VectorStore, vectorStoreDeserializer, + vectorStoreExpirationPolicySerializer, + vectorStoreChunkingStrategyRequestUnionSerializer, VectorStoreDeletionStatus, vectorStoreDeletionStatusDeserializer, OpenAIPageableListOfVectorStoreFile, @@ -113,93 +114,29 @@ import { } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; -export function _createAgentSend( - context: Client, - model: string, - options: AgentsCreateAgentOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/assistants").post({ - ...operationOptionsToRequestParameters(options), - body: { - model: model, - name: options?.name, - description: options?.description, - instructions: options?.instructions, - tools: !options?.tools - ? options?.tools - : options?.tools.map((p: any) => { - return toolDefinitionUnionSerializer(p); - }), - tool_resources: { - code_interpreter: !options?.toolResources?.["codeInterpreter"] - ? options?.toolResources?.["codeInterpreter"] - : codeInterpreterToolResourceSerializer( - options?.toolResources?.["codeInterpreter"], - ), - file_search: !options?.toolResources?.["fileSearch"] - ? options?.toolResources?.["fileSearch"] - : fileSearchToolResourceSerializer( - options?.toolResources?.["fileSearch"], - ), - bing_grounding: !options?.toolResources?.["bingGrounding"] - ? options?.toolResources?.["bingGrounding"] - : connectionListResourceSerializer( - options?.toolResources?.["bingGrounding"], - ), - microsoft_fabric: !options?.toolResources?.["microsoftFabric"] - ? options?.toolResources?.["microsoftFabric"] - : connectionListResourceSerializer( - options?.toolResources?.["microsoftFabric"], - ), - sharepoint: !options?.toolResources?.["sharePoint"] - ? options?.toolResources?.["sharePoint"] - : connectionListResourceSerializer( - options?.toolResources?.["sharePoint"], - ), - azure_ai_search: !options?.toolResources?.["azureAISearch"] - ? options?.toolResources?.["azureAISearch"] - : azureAISearchResourceSerializer( - options?.toolResources?.["azureAISearch"], - ), - }, - temperature: options?.temperature, - top_p: options?.topP, - response_format: options?.responseFormat as any, - metadata: options?.metadata, - }, - }); -} - -export async function _createAgentDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return agentDeserializer(result.body); -} - -/** Creates a new agent. */ -export async function createAgent( - context: Client, - model: string, - options: AgentsCreateAgentOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createAgentSend(context, model, options); - return _createAgentDeserialize(result); -} - -export function _listAgentsSend( +export function _listVectorStoreFileBatchFilesSend( context: Client, - options: AgentsListAgentsOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + batchId: string, + options: AgentsListVectorStoreFileBatchFilesOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/assistants") + .path( + "/vector_stores/{vectorStoreId}/file_batches/{batchId}/files", + vectorStoreId, + batchId, + ) .get({ ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { + "api-version": context.apiVersion, + filter: options?.filter, limit: options?.limit, order: options?.order, after: options?.after, @@ -208,601 +145,586 @@ export function _listAgentsSend( }); } -export async function _listAgentsDeserialize( +export async function _listVectorStoreFileBatchFilesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfAgentDeserializer(result.body); + return openAIPageableListOfVectorStoreFileDeserializer(result.body); } -/** Gets a list of agents that were previously created. */ -export async function listAgents( +/** Returns a list of vector store files in a batch. */ +export async function listVectorStoreFileBatchFiles( context: Client, - options: AgentsListAgentsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listAgentsSend(context, options); - return _listAgentsDeserialize(result); + vectorStoreId: string, + batchId: string, + options: AgentsListVectorStoreFileBatchFilesOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _listVectorStoreFileBatchFilesSend( + context, + vectorStoreId, + batchId, + options, + ); + return _listVectorStoreFileBatchFilesDeserialize(result); } -export function _getAgentSend( +export function _cancelVectorStoreFileBatchSend( context: Client, - assistantId: string, - options: AgentsGetAgentOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + batchId: string, + options: AgentsCancelVectorStoreFileBatchOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/assistants/{assistantId}", assistantId) - .get({ ...operationOptionsToRequestParameters(options) }); -} - -export async function _getAgentDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return agentDeserializer(result.body); -} - -/** Retrieves an existing agent. */ -export async function getAgent( - context: Client, - assistantId: string, - options: AgentsGetAgentOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getAgentSend(context, assistantId, options); - return _getAgentDeserialize(result); -} - -export function _updateAgentSend( - context: Client, - assistantId: string, - options: AgentsUpdateAgentOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/assistants/{assistantId}", assistantId).post({ - ...operationOptionsToRequestParameters(options), - body: { - model: options?.model, - name: options?.name, - description: options?.description, - instructions: options?.instructions, - tools: !options?.tools - ? options?.tools - : options?.tools.map((p: any) => { - return toolDefinitionUnionSerializer(p); - }), - tool_resources: { - code_interpreter: !options?.toolResources?.["codeInterpreter"] - ? options?.toolResources?.["codeInterpreter"] - : codeInterpreterToolResourceSerializer( - options?.toolResources?.["codeInterpreter"], - ), - file_search: !options?.toolResources?.["fileSearch"] - ? options?.toolResources?.["fileSearch"] - : fileSearchToolResourceSerializer( - options?.toolResources?.["fileSearch"], - ), - bing_grounding: !options?.toolResources?.["bingGrounding"] - ? options?.toolResources?.["bingGrounding"] - : connectionListResourceSerializer( - options?.toolResources?.["bingGrounding"], - ), - microsoft_fabric: !options?.toolResources?.["microsoftFabric"] - ? options?.toolResources?.["microsoftFabric"] - : connectionListResourceSerializer( - options?.toolResources?.["microsoftFabric"], - ), - sharepoint: !options?.toolResources?.["sharePoint"] - ? options?.toolResources?.["sharePoint"] - : connectionListResourceSerializer( - options?.toolResources?.["sharePoint"], - ), - azure_ai_search: !options?.toolResources?.["azureAISearch"] - ? options?.toolResources?.["azureAISearch"] - : azureAISearchResourceSerializer( - options?.toolResources?.["azureAISearch"], - ), + .path( + "/vector_stores/{vectorStoreId}/file_batches/{batchId}/cancel", + vectorStoreId, + batchId, + ) + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, - temperature: options?.temperature, - top_p: options?.topP, - response_format: options?.responseFormat as any, - metadata: options?.metadata, - }, - }); + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _updateAgentDeserialize( +export async function _cancelVectorStoreFileBatchDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return agentDeserializer(result.body); + return vectorStoreFileBatchDeserializer(result.body); } -/** Modifies an existing agent. */ -export async function updateAgent( +/** Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. */ +export async function cancelVectorStoreFileBatch( context: Client, - assistantId: string, - options: AgentsUpdateAgentOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateAgentSend(context, assistantId, options); - return _updateAgentDeserialize(result); + vectorStoreId: string, + batchId: string, + options: AgentsCancelVectorStoreFileBatchOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _cancelVectorStoreFileBatchSend( + context, + vectorStoreId, + batchId, + options, + ); + return _cancelVectorStoreFileBatchDeserialize(result); } -export function _deleteAgentSend( +export function _getVectorStoreFileBatchSend( context: Client, - assistantId: string, - options: AgentsDeleteAgentOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + batchId: string, + options: AgentsGetVectorStoreFileBatchOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/assistants/{assistantId}", assistantId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path( + "/vector_stores/{vectorStoreId}/file_batches/{batchId}", + vectorStoreId, + batchId, + ) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _deleteAgentDeserialize( +export async function _getVectorStoreFileBatchDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return agentDeletionStatusDeserializer(result.body); + return vectorStoreFileBatchDeserializer(result.body); } -/** Deletes an agent. */ -export async function deleteAgent( +/** Retrieve a vector store file batch. */ +export async function getVectorStoreFileBatch( context: Client, - assistantId: string, - options: AgentsDeleteAgentOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteAgentSend(context, assistantId, options); - return _deleteAgentDeserialize(result); + vectorStoreId: string, + batchId: string, + options: AgentsGetVectorStoreFileBatchOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getVectorStoreFileBatchSend( + context, + vectorStoreId, + batchId, + options, + ); + return _getVectorStoreFileBatchDeserialize(result); } -export function _createThreadSend( +export function _createVectorStoreFileBatchSend( context: Client, - options: AgentsCreateThreadOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + fileIds: string[], + options: AgentsCreateVectorStoreFileBatchOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { - return context.path("/threads").post({ - ...operationOptionsToRequestParameters(options), - body: { - messages: !options?.messages - ? options?.messages - : options?.messages.map((p: any) => { - return threadMessageOptionsSerializer(p); - }), - tool_resources: { - code_interpreter: !options?.toolResources?.["codeInterpreter"] - ? options?.toolResources?.["codeInterpreter"] - : codeInterpreterToolResourceSerializer( - options?.toolResources?.["codeInterpreter"], - ), - file_search: !options?.toolResources?.["fileSearch"] - ? options?.toolResources?.["fileSearch"] - : fileSearchToolResourceSerializer( - options?.toolResources?.["fileSearch"], - ), - bing_grounding: !options?.toolResources?.["bingGrounding"] - ? options?.toolResources?.["bingGrounding"] - : connectionListResourceSerializer( - options?.toolResources?.["bingGrounding"], - ), - microsoft_fabric: !options?.toolResources?.["microsoftFabric"] - ? options?.toolResources?.["microsoftFabric"] - : connectionListResourceSerializer( - options?.toolResources?.["microsoftFabric"], - ), - sharepoint: !options?.toolResources?.["sharePoint"] - ? options?.toolResources?.["sharePoint"] - : connectionListResourceSerializer( - options?.toolResources?.["sharePoint"], - ), - azure_ai_search: !options?.toolResources?.["azureAISearch"] - ? options?.toolResources?.["azureAISearch"] - : azureAISearchResourceSerializer( - options?.toolResources?.["azureAISearch"], + return context + .path("/vector_stores/{vectorStoreId}/file_batches", vectorStoreId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + file_ids: fileIds.map((p: any) => { + return p; + }), + chunking_strategy: !options?.chunkingStrategy + ? options?.chunkingStrategy + : vectorStoreChunkingStrategyRequestUnionSerializer( + options?.chunkingStrategy, ), }, - metadata: options?.metadata, - }, - }); + }); } -export async function _createThreadDeserialize( +export async function _createVectorStoreFileBatchDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return agentThreadDeserializer(result.body); + return vectorStoreFileBatchDeserializer(result.body); } -/** Creates a new thread. Threads contain messages and can be run by agents. */ -export async function createThread( +/** Create a vector store file batch. */ +export async function createVectorStoreFileBatch( context: Client, - options: AgentsCreateThreadOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createThreadSend(context, options); - return _createThreadDeserialize(result); + vectorStoreId: string, + fileIds: string[], + options: AgentsCreateVectorStoreFileBatchOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _createVectorStoreFileBatchSend( + context, + vectorStoreId, + fileIds, + options, + ); + return _createVectorStoreFileBatchDeserialize(result); } -export function _getThreadSend( +export function _deleteVectorStoreFileSend( context: Client, - threadId: string, - options: AgentsGetThreadOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + fileId: string, + options: AgentsDeleteVectorStoreFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}", threadId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path( + "/vector_stores/{vectorStoreId}/files/{fileId}", + vectorStoreId, + fileId, + ) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getThreadDeserialize( +export async function _deleteVectorStoreFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return agentThreadDeserializer(result.body); + return vectorStoreFileDeletionStatusDeserializer(result.body); } -/** Gets information about an existing thread. */ -export async function getThread( +/** + * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + * To delete the file, use the delete file endpoint. + */ +export async function deleteVectorStoreFile( context: Client, - threadId: string, - options: AgentsGetThreadOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getThreadSend(context, threadId, options); - return _getThreadDeserialize(result); + vectorStoreId: string, + fileId: string, + options: AgentsDeleteVectorStoreFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteVectorStoreFileSend( + context, + vectorStoreId, + fileId, + options, + ); + return _deleteVectorStoreFileDeserialize(result); } -export function _updateThreadSend( +export function _getVectorStoreFileSend( context: Client, - threadId: string, - options: AgentsUpdateThreadOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + fileId: string, + options: AgentsGetVectorStoreFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}", threadId) - .post({ + .path( + "/vector_stores/{vectorStoreId}/files/{fileId}", + vectorStoreId, + fileId, + ) + .get({ ...operationOptionsToRequestParameters(options), - body: { - tool_resources: { - code_interpreter: !options?.toolResources?.["codeInterpreter"] - ? options?.toolResources?.["codeInterpreter"] - : codeInterpreterToolResourceSerializer( - options?.toolResources?.["codeInterpreter"], - ), - file_search: !options?.toolResources?.["fileSearch"] - ? options?.toolResources?.["fileSearch"] - : fileSearchToolResourceSerializer( - options?.toolResources?.["fileSearch"], - ), - bing_grounding: !options?.toolResources?.["bingGrounding"] - ? options?.toolResources?.["bingGrounding"] - : connectionListResourceSerializer( - options?.toolResources?.["bingGrounding"], - ), - microsoft_fabric: !options?.toolResources?.["microsoftFabric"] - ? options?.toolResources?.["microsoftFabric"] - : connectionListResourceSerializer( - options?.toolResources?.["microsoftFabric"], - ), - sharepoint: !options?.toolResources?.["sharePoint"] - ? options?.toolResources?.["sharePoint"] - : connectionListResourceSerializer( - options?.toolResources?.["sharePoint"], - ), - azure_ai_search: !options?.toolResources?.["azureAISearch"] - ? options?.toolResources?.["azureAISearch"] - : azureAISearchResourceSerializer( - options?.toolResources?.["azureAISearch"], - ), - }, - metadata: options?.metadata, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _updateThreadDeserialize( +export async function _getVectorStoreFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return agentThreadDeserializer(result.body); + return vectorStoreFileDeserializer(result.body); } -/** Modifies an existing thread. */ -export async function updateThread( +/** Retrieves a vector store file. */ +export async function getVectorStoreFile( context: Client, - threadId: string, - options: AgentsUpdateThreadOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateThreadSend(context, threadId, options); - return _updateThreadDeserialize(result); + vectorStoreId: string, + fileId: string, + options: AgentsGetVectorStoreFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getVectorStoreFileSend( + context, + vectorStoreId, + fileId, + options, + ); + return _getVectorStoreFileDeserialize(result); } -export function _deleteThreadSend( +export function _createVectorStoreFileSend( context: Client, - threadId: string, - options: AgentsDeleteThreadOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + fileId: string, + options: AgentsCreateVectorStoreFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}", threadId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/vector_stores/{vectorStoreId}/files", vectorStoreId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + file_id: fileId, + chunking_strategy: !options?.chunkingStrategy + ? options?.chunkingStrategy + : vectorStoreChunkingStrategyRequestUnionSerializer( + options?.chunkingStrategy, + ), + }, + }); } -export async function _deleteThreadDeserialize( +export async function _createVectorStoreFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadDeletionStatusDeserializer(result.body); + return vectorStoreFileDeserializer(result.body); } -/** Deletes an existing thread. */ -export async function deleteThread( +/** Create a vector store file by attaching a file to a vector store. */ +export async function createVectorStoreFile( context: Client, - threadId: string, - options: AgentsDeleteThreadOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteThreadSend(context, threadId, options); - return _deleteThreadDeserialize(result); + vectorStoreId: string, + fileId: string, + options: AgentsCreateVectorStoreFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createVectorStoreFileSend( + context, + vectorStoreId, + fileId, + options, + ); + return _createVectorStoreFileDeserialize(result); } -export function _createMessageSend( - context: Client, - threadId: string, - role: MessageRole, - content: string, - options: AgentsCreateMessageOptionalParams = { requestOptions: {} }, +export function _listVectorStoreFilesSend( + context: Client, + vectorStoreId: string, + options: AgentsListVectorStoreFilesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/threads/{threadId}/messages", threadId).post({ - ...operationOptionsToRequestParameters(options), - body: { - role: role, - content: content, - attachments: !options?.attachments - ? options?.attachments - : options?.attachments.map((p: any) => { - return messageAttachmentSerializer(p); - }), - metadata: options?.metadata, - }, - }); + return context + .path("/vector_stores/{vectorStoreId}/files", vectorStoreId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + filter: options?.filter, + limit: options?.limit, + order: options?.order, + after: options?.after, + before: options?.before, + }, + }); } -export async function _createMessageDeserialize( +export async function _listVectorStoreFilesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadMessageDeserializer(result.body); + return openAIPageableListOfVectorStoreFileDeserializer(result.body); } -/** Creates a new message on a specified thread. */ -export async function createMessage( +/** Returns a list of vector store files. */ +export async function listVectorStoreFiles( context: Client, - threadId: string, - role: MessageRole, - content: string, - options: AgentsCreateMessageOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createMessageSend( + vectorStoreId: string, + options: AgentsListVectorStoreFilesOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listVectorStoreFilesSend( context, - threadId, - role, - content, + vectorStoreId, options, ); - return _createMessageDeserialize(result); + return _listVectorStoreFilesDeserialize(result); } -export function _listMessagesSend( +export function _deleteVectorStoreSend( context: Client, - threadId: string, - options: AgentsListMessagesOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + options: AgentsDeleteVectorStoreOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/messages", threadId) - .get({ + .path("/vector_stores/{vectorStoreId}", vectorStoreId) + .delete({ ...operationOptionsToRequestParameters(options), - queryParameters: { - runId: options?.runId, - limit: options?.limit, - order: options?.order, - after: options?.after, - before: options?.before, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _listMessagesDeserialize( +export async function _deleteVectorStoreDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfThreadMessageDeserializer(result.body); + return vectorStoreDeletionStatusDeserializer(result.body); } -/** Gets a list of messages that exist on a thread. */ -export async function listMessages( +/** Deletes the vector store object matching the specified ID. */ +export async function deleteVectorStore( context: Client, - threadId: string, - options: AgentsListMessagesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listMessagesSend(context, threadId, options); - return _listMessagesDeserialize(result); + vectorStoreId: string, + options: AgentsDeleteVectorStoreOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteVectorStoreSend(context, vectorStoreId, options); + return _deleteVectorStoreDeserialize(result); } -export function _getMessageSend( +export function _modifyVectorStoreSend( context: Client, - threadId: string, - messageId: string, - options: AgentsGetMessageOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + options: AgentsModifyVectorStoreOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/messages/{messageId}", threadId, messageId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/vector_stores/{vectorStoreId}", vectorStoreId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + name: options?.name, + expires_after: !options?.expiresAfter + ? options?.expiresAfter + : vectorStoreExpirationPolicySerializer(options?.expiresAfter), + metadata: options?.metadata, + }, + }); } -export async function _getMessageDeserialize( +export async function _modifyVectorStoreDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadMessageDeserializer(result.body); + return vectorStoreDeserializer(result.body); } -/** Gets an existing message from an existing thread. */ -export async function getMessage( +/** The ID of the vector store to modify. */ +export async function modifyVectorStore( context: Client, - threadId: string, - messageId: string, - options: AgentsGetMessageOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getMessageSend(context, threadId, messageId, options); - return _getMessageDeserialize(result); + vectorStoreId: string, + options: AgentsModifyVectorStoreOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _modifyVectorStoreSend(context, vectorStoreId, options); + return _modifyVectorStoreDeserialize(result); } -export function _updateMessageSend( +export function _getVectorStoreSend( context: Client, - threadId: string, - messageId: string, - options: AgentsUpdateMessageOptionalParams = { requestOptions: {} }, + vectorStoreId: string, + options: AgentsGetVectorStoreOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/messages/{messageId}", threadId, messageId) - .post({ + .path("/vector_stores/{vectorStoreId}", vectorStoreId) + .get({ ...operationOptionsToRequestParameters(options), - body: { metadata: options?.metadata }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _updateMessageDeserialize( +export async function _getVectorStoreDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadMessageDeserializer(result.body); + return vectorStoreDeserializer(result.body); } -/** Modifies an existing message on an existing thread. */ -export async function updateMessage( +/** Returns the vector store object matching the specified ID. */ +export async function getVectorStore( context: Client, - threadId: string, - messageId: string, - options: AgentsUpdateMessageOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateMessageSend( - context, - threadId, - messageId, - options, - ); - return _updateMessageDeserialize(result); + vectorStoreId: string, + options: AgentsGetVectorStoreOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getVectorStoreSend(context, vectorStoreId, options); + return _getVectorStoreDeserialize(result); } -export function _createRunSend( +export function _createVectorStoreSend( context: Client, - threadId: string, - assistantId: string, - options: AgentsCreateRunOptionalParams = { requestOptions: {} }, + options: AgentsCreateVectorStoreOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/threads/{threadId}/runs", threadId).post({ + return context.path("/vector_stores").post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { accept: "application/json", ...options.requestOptions?.headers }, + queryParameters: { "api-version": context.apiVersion }, body: { - assistant_id: assistantId, - model: options?.model, - instructions: options?.instructions, - additional_instructions: options?.additionalInstructions, - additional_messages: !options?.additionalMessages - ? options?.additionalMessages - : options?.additionalMessages.map((p: any) => { - return threadMessageSerializer(p); - }), - tools: !options?.tools - ? options?.tools - : options?.tools.map((p: any) => { - return toolDefinitionUnionSerializer(p); + file_ids: !options?.fileIds + ? options?.fileIds + : options?.fileIds.map((p: any) => { + return p; }), - stream: options?.stream, - temperature: options?.temperature, - top_p: options?.topP, - max_prompt_tokens: options?.maxPromptTokens, - max_completion_tokens: options?.maxCompletionTokens, - truncation_strategy: { - type: options?.truncationStrategy?.["type"], - last_messages: options?.truncationStrategy?.["lastMessages"], - }, - tool_choice: options?.toolChoice as any, - response_format: options?.responseFormat as any, + name: options?.name, + expires_after: !options?.expiresAfter + ? options?.expiresAfter + : vectorStoreExpirationPolicySerializer(options?.expiresAfter), + chunking_strategy: !options?.chunkingStrategy + ? options?.chunkingStrategy + : vectorStoreChunkingStrategyRequestUnionSerializer( + options?.chunkingStrategy, + ), metadata: options?.metadata, }, }); } -export async function _createRunDeserialize( +export async function _createVectorStoreDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadRunDeserializer(result.body); + return vectorStoreDeserializer(result.body); } -/** Creates a new run for an agent thread. */ -export async function createRun( +/** Creates a vector store. */ +export async function createVectorStore( context: Client, - threadId: string, - assistantId: string, - options: AgentsCreateRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createRunSend(context, threadId, assistantId, options); - return _createRunDeserialize(result); + options: AgentsCreateVectorStoreOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createVectorStoreSend(context, options); + return _createVectorStoreDeserialize(result); } -export function _listRunsSend( +export function _listVectorStoresSend( context: Client, - threadId: string, - options: AgentsListRunsOptionalParams = { requestOptions: {} }, + options: AgentsListVectorStoresOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/runs", threadId) + .path("/vector_stores") .get({ ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { + "api-version": context.apiVersion, limit: options?.limit, order: options?.order, after: options?.after, @@ -811,272 +733,269 @@ export function _listRunsSend( }); } -export async function _listRunsDeserialize( +export async function _listVectorStoresDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfThreadRunDeserializer(result.body); + return openAIPageableListOfVectorStoreDeserializer(result.body); } -/** Gets a list of runs for a specified thread. */ -export async function listRuns( +/** Returns a list of vector stores. */ +export async function listVectorStores( context: Client, - threadId: string, - options: AgentsListRunsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listRunsSend(context, threadId, options); - return _listRunsDeserialize(result); + options: AgentsListVectorStoresOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listVectorStoresSend(context, options); + return _listVectorStoresDeserialize(result); } -export function _getRunSend( +export function _getFileContentSend( + context: Client, + fileId: string, + options: AgentsGetFileContentOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/files/{fileId}/content", fileId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); +} + +export async function _getFileContentDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return fileContentResponseDeserializer(result.body); +} + +/** Returns information about a specific file. Does not retrieve file content. */ +export async function getFileContent( + context: Client, + fileId: string, + options: AgentsGetFileContentOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getFileContentSend(context, fileId, options); + return _getFileContentDeserialize(result); +} + +export function _getFileSend( context: Client, - threadId: string, - runId: string, - options: AgentsGetRunOptionalParams = { requestOptions: {} }, + fileId: string, + options: AgentsGetFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/runs/{runId}", threadId, runId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/files/{fileId}", fileId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getRunDeserialize( +export async function _getFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadRunDeserializer(result.body); + return openAIFileDeserializer(result.body); } -/** Gets an existing run from an existing thread. */ -export async function getRun( +/** Returns information about a specific file. Does not retrieve file content. */ +export async function getFile( context: Client, - threadId: string, - runId: string, - options: AgentsGetRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getRunSend(context, threadId, runId, options); - return _getRunDeserialize(result); + fileId: string, + options: AgentsGetFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getFileSend(context, fileId, options); + return _getFileDeserialize(result); } -export function _updateRunSend( +export function _deleteFileSend( context: Client, - threadId: string, - runId: string, - options: AgentsUpdateRunOptionalParams = { requestOptions: {} }, + fileId: string, + options: AgentsDeleteFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/runs/{runId}", threadId, runId) - .post({ + .path("/files/{fileId}", fileId) + .delete({ ...operationOptionsToRequestParameters(options), - body: { metadata: options?.metadata }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _updateRunDeserialize( +export async function _deleteFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadRunDeserializer(result.body); + return fileDeletionStatusDeserializer(result.body); } -/** Modifies an existing thread run. */ -export async function updateRun( +/** Delete a previously uploaded file. */ +export async function deleteFile( context: Client, - threadId: string, - runId: string, - options: AgentsUpdateRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateRunSend(context, threadId, runId, options); - return _updateRunDeserialize(result); + fileId: string, + options: AgentsDeleteFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteFileSend(context, fileId, options); + return _deleteFileDeserialize(result); } -export function _submitToolOutputsToRunSend( +export function _uploadFileSend( context: Client, - threadId: string, - runId: string, - toolOutputs: ToolOutput[], - options: AgentsSubmitToolOutputsToRunOptionalParams = { requestOptions: {} }, + file: Uint8Array, + purpose: FilePurpose, + options: AgentsUploadFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/threads/{threadId}/runs/{runId}/submit_tool_outputs", - threadId, - runId, - ) + .path("/files") .post({ ...operationOptionsToRequestParameters(options), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: { - tool_outputs: toolOutputs.map((p: any) => { - return toolOutputSerializer(p); - }), - stream: options?.stream, + file: uint8ArrayToString(file, "base64"), + purpose: purpose, + filename: options?.filename, }, }); } -export async function _submitToolOutputsToRunDeserialize( +export async function _uploadFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadRunDeserializer(result.body); + return openAIFileDeserializer(result.body); } -/** Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. */ -export async function submitToolOutputsToRun( +/** Uploads a file for use by other operations. */ +export async function uploadFile( context: Client, - threadId: string, - runId: string, - toolOutputs: ToolOutput[], - options: AgentsSubmitToolOutputsToRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _submitToolOutputsToRunSend( - context, - threadId, - runId, - toolOutputs, - options, - ); - return _submitToolOutputsToRunDeserialize(result); + file: Uint8Array, + purpose: FilePurpose, + options: AgentsUploadFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _uploadFileSend(context, file, purpose, options); + return _uploadFileDeserialize(result); } -export function _cancelRunSend( +export function _listFilesSend( context: Client, - threadId: string, - runId: string, - options: AgentsCancelRunOptionalParams = { requestOptions: {} }, + options: AgentsListFilesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/runs/{runId}/cancel", threadId, runId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/files") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + purpose: options?.purpose, + }, + }); } -export async function _cancelRunDeserialize( +export async function _listFilesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadRunDeserializer(result.body); + return fileListResponseDeserializer(result.body); } -/** Cancels a run of an in progress thread. */ -export async function cancelRun( +/** Gets a list of previously uploaded files. */ +export async function listFiles( context: Client, - threadId: string, - runId: string, - options: AgentsCancelRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _cancelRunSend(context, threadId, runId, options); - return _cancelRunDeserialize(result); + options: AgentsListFilesOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listFilesSend(context, options); + return _listFilesDeserialize(result); } -export function _createThreadAndRunSend( +export function _listRunStepsSend( context: Client, - assistantId: string, - options: AgentsCreateThreadAndRunOptionalParams = { requestOptions: {} }, + threadId: string, + runId: string, + options: AgentsListRunStepsOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/threads/runs").post({ - ...operationOptionsToRequestParameters(options), - body: { - assistant_id: assistantId, - thread: { - messages: !options?.thread?.["messages"] - ? options?.thread?.["messages"] - : threadMessageOptionsArraySerializer(options?.thread?.["messages"]), - tool_resources: options?.thread?.["toolResources"], - metadata: options?.thread?.["metadata"], - }, - model: options?.model, - instructions: options?.instructions, - tools: !options?.tools - ? options?.tools - : options?.tools.map((p: any) => { - return toolDefinitionUnionSerializer(p); - }), - tool_resources: { - code_interpreter: !options?.toolResources?.["codeInterpreter"] - ? options?.toolResources?.["codeInterpreter"] - : updateCodeInterpreterToolResourceOptionsSerializer( - options?.toolResources?.["codeInterpreter"], - ), - file_search: !options?.toolResources?.["fileSearch"] - ? options?.toolResources?.["fileSearch"] - : updateFileSearchToolResourceOptionsSerializer( - options?.toolResources?.["fileSearch"], - ), - bing_grounding: !options?.toolResources?.["bingGrounding"] - ? options?.toolResources?.["bingGrounding"] - : connectionListResourceSerializer( - options?.toolResources?.["bingGrounding"], - ), - microsoft_fabric: !options?.toolResources?.["microsoftFabric"] - ? options?.toolResources?.["microsoftFabric"] - : connectionListResourceSerializer( - options?.toolResources?.["microsoftFabric"], - ), - sharepoint: !options?.toolResources?.["sharePoint"] - ? options?.toolResources?.["sharePoint"] - : connectionListResourceSerializer( - options?.toolResources?.["sharePoint"], - ), - azure_ai_search: !options?.toolResources?.["azureAISearch"] - ? options?.toolResources?.["azureAISearch"] - : azureAISearchResourceSerializer( - options?.toolResources?.["azureAISearch"], - ), + return context + .path("/threads/{threadId}/runs/{runId}/steps", threadId, runId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, - stream: options?.stream, - temperature: options?.temperature, - top_p: options?.topP, - max_prompt_tokens: options?.maxPromptTokens, - max_completion_tokens: options?.maxCompletionTokens, - truncation_strategy: { - type: options?.truncationStrategy?.["type"], - last_messages: options?.truncationStrategy?.["lastMessages"], + queryParameters: { + "api-version": context.apiVersion, + limit: options?.limit, + order: options?.order, + after: options?.after, + before: options?.before, }, - tool_choice: options?.toolChoice as any, - response_format: options?.responseFormat as any, - metadata: options?.metadata, - }, - }); + }); } -export async function _createThreadAndRunDeserialize( +export async function _listRunStepsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return threadRunDeserializer(result.body); + return openAIPageableListOfRunStepDeserializer(result.body); } -/** Creates a new agent thread and immediately starts a run using that new thread. */ -export async function createThreadAndRun( +/** Gets a list of run steps from a thread run. */ +export async function listRunSteps( context: Client, - assistantId: string, - options: AgentsCreateThreadAndRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createThreadAndRunSend(context, assistantId, options); - return _createThreadAndRunDeserialize(result); + threadId: string, + runId: string, + options: AgentsListRunStepsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listRunStepsSend(context, threadId, runId, options); + return _listRunStepsDeserialize(result); } export function _getRunStepSend( @@ -1093,7 +1012,14 @@ export function _getRunStepSend( runId, stepId, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _getRunStepDeserialize( @@ -1125,760 +1051,949 @@ export async function getRunStep( return _getRunStepDeserialize(result); } -export function _listRunStepsSend( +export function _createThreadAndRunSend( + context: Client, + assistantId: string, + options: AgentsCreateThreadAndRunOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/threads/runs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + assistant_id: assistantId, + thread: !options?.thread + ? options?.thread + : agentThreadCreationOptionsSerializer(options?.thread), + model: options?.model, + instructions: options?.instructions, + tools: !options?.tools + ? options?.tools + : toolDefinitionUnionArraySerializer(options?.tools), + tool_resources: !options?.toolResources + ? options?.toolResources + : updateToolResourcesOptionsSerializer(options?.toolResources), + stream: options?.stream, + temperature: options?.temperature, + top_p: options?.topP, + max_prompt_tokens: options?.maxPromptTokens, + max_completion_tokens: options?.maxCompletionTokens, + truncation_strategy: !options?.truncationStrategy + ? options?.truncationStrategy + : truncationObjectSerializer(options?.truncationStrategy), + tool_choice: !options?.toolChoice + ? options?.toolChoice + : agentsApiToolChoiceOptionSerializer(options?.toolChoice), + response_format: !options?.responseFormat + ? options?.responseFormat + : agentsApiResponseFormatOptionSerializer(options?.responseFormat), + metadata: options?.metadata, + }, + }); +} + +export async function _createThreadAndRunDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return threadRunDeserializer(result.body); +} + +/** Creates a new agent thread and immediately starts a run using that new thread. */ +export async function createThreadAndRun( + context: Client, + assistantId: string, + options: AgentsCreateThreadAndRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createThreadAndRunSend(context, assistantId, options); + return _createThreadAndRunDeserialize(result); +} + +export function _cancelRunSend( context: Client, threadId: string, runId: string, - options: AgentsListRunStepsOptionalParams = { requestOptions: {} }, + options: AgentsCancelRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/threads/{threadId}/runs/{runId}/steps", threadId, runId) - .get({ + .path("/threads/{threadId}/runs/{runId}/cancel", threadId, runId) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - limit: options?.limit, - order: options?.order, - after: options?.after, - before: options?.before, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _listRunStepsDeserialize( +export async function _cancelRunDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfRunStepDeserializer(result.body); + return threadRunDeserializer(result.body); } -/** Gets a list of run steps from a thread run. */ -export async function listRunSteps( +/** Cancels a run of an in progress thread. */ +export async function cancelRun( context: Client, threadId: string, runId: string, - options: AgentsListRunStepsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listRunStepsSend(context, threadId, runId, options); - return _listRunStepsDeserialize(result); + options: AgentsCancelRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _cancelRunSend(context, threadId, runId, options); + return _cancelRunDeserialize(result); } -export function _listFilesSend( +export function _submitToolOutputsToRunSend( context: Client, - options: AgentsListFilesOptionalParams = { requestOptions: {} }, + threadId: string, + runId: string, + toolOutputs: ToolOutput[], + options: AgentsSubmitToolOutputsToRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files") - .get({ + .path( + "/threads/{threadId}/runs/{runId}/submit_tool_outputs", + threadId, + runId, + ) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { purpose: options?.purpose }, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + tool_outputs: toolOutputArraySerializer(toolOutputs), + stream: options?.stream, + }, }); } -export async function _listFilesDeserialize( +export async function _submitToolOutputsToRunDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return fileListResponseDeserializer(result.body); + return threadRunDeserializer(result.body); } -/** Gets a list of previously uploaded files. */ -export async function listFiles( +/** Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. */ +export async function submitToolOutputsToRun( context: Client, - options: AgentsListFilesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listFilesSend(context, options); - return _listFilesDeserialize(result); + threadId: string, + runId: string, + toolOutputs: ToolOutput[], + options: AgentsSubmitToolOutputsToRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _submitToolOutputsToRunSend( + context, + threadId, + runId, + toolOutputs, + options, + ); + return _submitToolOutputsToRunDeserialize(result); } -export function _uploadFileSend( +export function _updateRunSend( context: Client, - file: Uint8Array, - purpose: FilePurpose, - options: AgentsUploadFileOptionalParams = { requestOptions: {} }, + threadId: string, + runId: string, + options: AgentsUpdateRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files") + .path("/threads/{threadId}/runs/{runId}", threadId, runId) .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(file, "base64"), - purpose: purpose, - filename: options?.filename, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, + body: { metadata: options?.metadata }, }); } -export async function _uploadFileDeserialize( +export async function _updateRunDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIFileDeserializer(result.body); + return threadRunDeserializer(result.body); } -/** Uploads a file for use by other operations. */ -export async function uploadFile( +/** Modifies an existing thread run. */ +export async function updateRun( context: Client, - file: Uint8Array, - purpose: FilePurpose, - options: AgentsUploadFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _uploadFileSend(context, file, purpose, options); - return _uploadFileDeserialize(result); + threadId: string, + runId: string, + options: AgentsUpdateRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateRunSend(context, threadId, runId, options); + return _updateRunDeserialize(result); } -export function _deleteFileSend( +export function _getRunSend( context: Client, - fileId: string, - options: AgentsDeleteFileOptionalParams = { requestOptions: {} }, + threadId: string, + runId: string, + options: AgentsGetRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/{fileId}", fileId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/threads/{threadId}/runs/{runId}", threadId, runId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _deleteFileDeserialize( +export async function _getRunDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return fileDeletionStatusDeserializer(result.body); + return threadRunDeserializer(result.body); } -/** Delete a previously uploaded file. */ -export async function deleteFile( +/** Gets an existing run from an existing thread. */ +export async function getRun( context: Client, - fileId: string, - options: AgentsDeleteFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteFileSend(context, fileId, options); - return _deleteFileDeserialize(result); + threadId: string, + runId: string, + options: AgentsGetRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getRunSend(context, threadId, runId, options); + return _getRunDeserialize(result); } -export function _getFileSend( +export function _listRunsSend( context: Client, - fileId: string, - options: AgentsGetFileOptionalParams = { requestOptions: {} }, + threadId: string, + options: AgentsListRunsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/{fileId}", fileId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/threads/{threadId}/runs", threadId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + limit: options?.limit, + order: options?.order, + after: options?.after, + before: options?.before, + }, + }); } -export async function _getFileDeserialize( +export async function _listRunsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIFileDeserializer(result.body); + return openAIPageableListOfThreadRunDeserializer(result.body); } -/** Returns information about a specific file. Does not retrieve file content. */ -export async function getFile( +/** Gets a list of runs for a specified thread. */ +export async function listRuns( context: Client, - fileId: string, - options: AgentsGetFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getFileSend(context, fileId, options); - return _getFileDeserialize(result); + threadId: string, + options: AgentsListRunsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listRunsSend(context, threadId, options); + return _listRunsDeserialize(result); } -export function _getFileContentSend( +export function _createRunSend( context: Client, - fileId: string, - options: AgentsGetFileContentOptionalParams = { requestOptions: {} }, + threadId: string, + assistantId: string, + options: AgentsCreateRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/{fileId}/content", fileId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/threads/{threadId}/runs", threadId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + assistant_id: assistantId, + model: options?.model, + instructions: options?.instructions, + additional_instructions: options?.additionalInstructions, + additional_messages: !options?.additionalMessages + ? options?.additionalMessages + : threadMessageArraySerializer(options?.additionalMessages), + tools: !options?.tools + ? options?.tools + : toolDefinitionUnionArraySerializer(options?.tools), + stream: options?.stream, + temperature: options?.temperature, + top_p: options?.topP, + max_prompt_tokens: options?.maxPromptTokens, + max_completion_tokens: options?.maxCompletionTokens, + truncation_strategy: !options?.truncationStrategy + ? options?.truncationStrategy + : truncationObjectSerializer(options?.truncationStrategy), + tool_choice: !options?.toolChoice + ? options?.toolChoice + : agentsApiToolChoiceOptionSerializer(options?.toolChoice), + response_format: !options?.responseFormat + ? options?.responseFormat + : agentsApiResponseFormatOptionSerializer(options?.responseFormat), + metadata: options?.metadata, + }, + }); } -export async function _getFileContentDeserialize( +export async function _createRunDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return fileContentResponseDeserializer(result.body); + return threadRunDeserializer(result.body); } -/** Returns information about a specific file. Does not retrieve file content. */ -export async function getFileContent( +/** Creates a new run for an agent thread. */ +export async function createRun( context: Client, - fileId: string, - options: AgentsGetFileContentOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getFileContentSend(context, fileId, options); - return _getFileContentDeserialize(result); + threadId: string, + assistantId: string, + options: AgentsCreateRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createRunSend(context, threadId, assistantId, options); + return _createRunDeserialize(result); } -export function _listVectorStoresSend( +export function _updateMessageSend( context: Client, - options: AgentsListVectorStoresOptionalParams = { requestOptions: {} }, + threadId: string, + messageId: string, + options: AgentsUpdateMessageOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores") - .get({ + .path("/threads/{threadId}/messages/{messageId}", threadId, messageId) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - limit: options?.limit, - order: options?.order, - after: options?.after, - before: options?.before, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, + body: { metadata: options?.metadata }, }); } -export async function _listVectorStoresDeserialize( +export async function _updateMessageDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfVectorStoreDeserializer(result.body); + return threadMessageDeserializer(result.body); } -/** Returns a list of vector stores. */ -export async function listVectorStores( +/** Modifies an existing message on an existing thread. */ +export async function updateMessage( context: Client, - options: AgentsListVectorStoresOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listVectorStoresSend(context, options); - return _listVectorStoresDeserialize(result); + threadId: string, + messageId: string, + options: AgentsUpdateMessageOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateMessageSend( + context, + threadId, + messageId, + options, + ); + return _updateMessageDeserialize(result); } -export function _createVectorStoreSend( +export function _getMessageSend( context: Client, - options: AgentsCreateVectorStoreOptionalParams = { requestOptions: {} }, + threadId: string, + messageId: string, + options: AgentsGetMessageOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/vector_stores").post({ - ...operationOptionsToRequestParameters(options), - body: { - file_ids: !options?.fileIds - ? options?.fileIds - : options?.fileIds.map((p: any) => { - return p; - }), - name: options?.name, - expires_after: { - anchor: options?.expiresAfter?.["anchor"], - days: options?.expiresAfter?.["days"], + return context + .path("/threads/{threadId}/messages/{messageId}", threadId, messageId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, - chunking_strategy: { type: options?.chunkingStrategy?.["type"] }, - metadata: options?.metadata, - }, - }); + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _createVectorStoreDeserialize( +export async function _getMessageDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreDeserializer(result.body); + return threadMessageDeserializer(result.body); } -/** Creates a vector store. */ -export async function createVectorStore( +/** Gets an existing message from an existing thread. */ +export async function getMessage( context: Client, - options: AgentsCreateVectorStoreOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createVectorStoreSend(context, options); - return _createVectorStoreDeserialize(result); + threadId: string, + messageId: string, + options: AgentsGetMessageOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getMessageSend(context, threadId, messageId, options); + return _getMessageDeserialize(result); } -export function _getVectorStoreSend( +export function _listMessagesSend( context: Client, - vectorStoreId: string, - options: AgentsGetVectorStoreOptionalParams = { requestOptions: {} }, + threadId: string, + options: AgentsListMessagesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores/{vectorStoreId}", vectorStoreId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/threads/{threadId}/messages", threadId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + runId: options?.runId, + limit: options?.limit, + order: options?.order, + after: options?.after, + before: options?.before, + }, + }); } -export async function _getVectorStoreDeserialize( +export async function _listMessagesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreDeserializer(result.body); + return openAIPageableListOfThreadMessageDeserializer(result.body); } -/** Returns the vector store object matching the specified ID. */ -export async function getVectorStore( +/** Gets a list of messages that exist on a thread. */ +export async function listMessages( context: Client, - vectorStoreId: string, - options: AgentsGetVectorStoreOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getVectorStoreSend(context, vectorStoreId, options); - return _getVectorStoreDeserialize(result); + threadId: string, + options: AgentsListMessagesOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listMessagesSend(context, threadId, options); + return _listMessagesDeserialize(result); } -export function _modifyVectorStoreSend( +export function _createMessageSend( context: Client, - vectorStoreId: string, - options: AgentsModifyVectorStoreOptionalParams = { requestOptions: {} }, + threadId: string, + role: MessageRole, + content: string, + options: AgentsCreateMessageOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores/{vectorStoreId}", vectorStoreId) + .path("/threads/{threadId}/messages", threadId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: { - name: options?.name, - expires_after: { - anchor: options?.expiresAfter?.["anchor"], - days: options?.expiresAfter?.["days"], - }, + role: role, + content: content, + attachments: !options?.attachments + ? options?.attachments + : messageAttachmentArraySerializer(options?.attachments), metadata: options?.metadata, }, }); } -export async function _modifyVectorStoreDeserialize( +export async function _createMessageDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreDeserializer(result.body); + return threadMessageDeserializer(result.body); } -/** The ID of the vector store to modify. */ -export async function modifyVectorStore( +/** Creates a new message on a specified thread. */ +export async function createMessage( context: Client, - vectorStoreId: string, - options: AgentsModifyVectorStoreOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _modifyVectorStoreSend(context, vectorStoreId, options); - return _modifyVectorStoreDeserialize(result); + threadId: string, + role: MessageRole, + content: string, + options: AgentsCreateMessageOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createMessageSend( + context, + threadId, + role, + content, + options, + ); + return _createMessageDeserialize(result); } -export function _deleteVectorStoreSend( +export function _deleteThreadSend( context: Client, - vectorStoreId: string, - options: AgentsDeleteVectorStoreOptionalParams = { requestOptions: {} }, + threadId: string, + options: AgentsDeleteThreadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores/{vectorStoreId}", vectorStoreId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/threads/{threadId}", threadId) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _deleteVectorStoreDeserialize( +export async function _deleteThreadDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreDeletionStatusDeserializer(result.body); + return threadDeletionStatusDeserializer(result.body); } -/** Deletes the vector store object matching the specified ID. */ -export async function deleteVectorStore( +/** Deletes an existing thread. */ +export async function deleteThread( context: Client, - vectorStoreId: string, - options: AgentsDeleteVectorStoreOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteVectorStoreSend(context, vectorStoreId, options); - return _deleteVectorStoreDeserialize(result); + threadId: string, + options: AgentsDeleteThreadOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteThreadSend(context, threadId, options); + return _deleteThreadDeserialize(result); } -export function _listVectorStoreFilesSend( +export function _updateThreadSend( context: Client, - vectorStoreId: string, - options: AgentsListVectorStoreFilesOptionalParams = { requestOptions: {} }, + threadId: string, + options: AgentsUpdateThreadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores/{vectorStoreId}/files", vectorStoreId) - .get({ + .path("/threads/{threadId}", threadId) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - filter: options?.filter, - limit: options?.limit, - order: options?.order, - after: options?.after, - before: options?.before, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + tool_resources: !options?.toolResources + ? options?.toolResources + : toolResourcesSerializer(options?.toolResources), + metadata: options?.metadata, }, }); } -export async function _listVectorStoreFilesDeserialize( +export async function _updateThreadDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfVectorStoreFileDeserializer(result.body); + return agentThreadDeserializer(result.body); } -/** Returns a list of vector store files. */ -export async function listVectorStoreFiles( +/** Modifies an existing thread. */ +export async function updateThread( context: Client, - vectorStoreId: string, - options: AgentsListVectorStoreFilesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listVectorStoreFilesSend( - context, - vectorStoreId, - options, - ); - return _listVectorStoreFilesDeserialize(result); + threadId: string, + options: AgentsUpdateThreadOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateThreadSend(context, threadId, options); + return _updateThreadDeserialize(result); } -export function _createVectorStoreFileSend( +export function _getThreadSend( context: Client, - vectorStoreId: string, - fileId: string, - options: AgentsCreateVectorStoreFileOptionalParams = { requestOptions: {} }, + threadId: string, + options: AgentsGetThreadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores/{vectorStoreId}/files", vectorStoreId) - .post({ + .path("/threads/{threadId}", threadId) + .get({ ...operationOptionsToRequestParameters(options), - body: { - file_id: fileId, - chunking_strategy: { type: options?.chunkingStrategy?.["type"] }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createVectorStoreFileDeserialize( +export async function _getThreadDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreFileDeserializer(result.body); + return agentThreadDeserializer(result.body); } -/** Create a vector store file by attaching a file to a vector store. */ -export async function createVectorStoreFile( +/** Gets information about an existing thread. */ +export async function getThread( context: Client, - vectorStoreId: string, - fileId: string, - options: AgentsCreateVectorStoreFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createVectorStoreFileSend( - context, - vectorStoreId, - fileId, - options, - ); - return _createVectorStoreFileDeserialize(result); + threadId: string, + options: AgentsGetThreadOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getThreadSend(context, threadId, options); + return _getThreadDeserialize(result); } -export function _getVectorStoreFileSend( +export function _createThreadSend( context: Client, - vectorStoreId: string, - fileId: string, - options: AgentsGetVectorStoreFileOptionalParams = { requestOptions: {} }, + options: AgentsCreateThreadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/vector_stores/{vectorStoreId}/files/{fileId}", - vectorStoreId, - fileId, - ) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/threads") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + messages: !options?.messages + ? options?.messages + : threadMessageOptionsArraySerializer(options?.messages), + tool_resources: !options?.toolResources + ? options?.toolResources + : toolResourcesSerializer(options?.toolResources), + metadata: options?.metadata, + }, + }); } -export async function _getVectorStoreFileDeserialize( +export async function _createThreadDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreFileDeserializer(result.body); + return agentThreadDeserializer(result.body); } -/** Retrieves a vector store file. */ -export async function getVectorStoreFile( +/** Creates a new thread. Threads contain messages and can be run by agents. */ +export async function createThread( context: Client, - vectorStoreId: string, - fileId: string, - options: AgentsGetVectorStoreFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getVectorStoreFileSend( - context, - vectorStoreId, - fileId, - options, - ); - return _getVectorStoreFileDeserialize(result); + options: AgentsCreateThreadOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createThreadSend(context, options); + return _createThreadDeserialize(result); } -export function _deleteVectorStoreFileSend( +export function _deleteAgentSend( context: Client, - vectorStoreId: string, - fileId: string, - options: AgentsDeleteVectorStoreFileOptionalParams = { requestOptions: {} }, + assistantId: string, + options: AgentsDeleteAgentOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/vector_stores/{vectorStoreId}/files/{fileId}", - vectorStoreId, - fileId, - ) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/assistants/{assistantId}", assistantId) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _deleteVectorStoreFileDeserialize( +export async function _deleteAgentDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreFileDeletionStatusDeserializer(result.body); + return agentDeletionStatusDeserializer(result.body); } -/** - * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. - * To delete the file, use the delete file endpoint. - */ -export async function deleteVectorStoreFile( +/** Deletes an agent. */ +export async function deleteAgent( context: Client, - vectorStoreId: string, - fileId: string, - options: AgentsDeleteVectorStoreFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteVectorStoreFileSend( - context, - vectorStoreId, - fileId, - options, - ); - return _deleteVectorStoreFileDeserialize(result); + assistantId: string, + options: AgentsDeleteAgentOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteAgentSend(context, assistantId, options); + return _deleteAgentDeserialize(result); } -export function _createVectorStoreFileBatchSend( +export function _updateAgentSend( context: Client, - vectorStoreId: string, - fileIds: string[], - options: AgentsCreateVectorStoreFileBatchOptionalParams = { - requestOptions: {}, - }, + assistantId: string, + options: AgentsUpdateAgentOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/vector_stores/{vectorStoreId}/file_batches", vectorStoreId) + .path("/assistants/{assistantId}", assistantId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: { - file_ids: fileIds.map((p: any) => { - return p; - }), - chunking_strategy: { type: options?.chunkingStrategy?.["type"] }, + model: options?.model, + name: options?.name, + description: options?.description, + instructions: options?.instructions, + tools: !options?.tools + ? options?.tools + : toolDefinitionUnionArraySerializer(options?.tools), + tool_resources: !options?.toolResources + ? options?.toolResources + : toolResourcesSerializer(options?.toolResources), + temperature: options?.temperature, + top_p: options?.topP, + response_format: !options?.responseFormat + ? options?.responseFormat + : agentsApiResponseFormatOptionSerializer(options?.responseFormat), + metadata: options?.metadata, }, }); } -export async function _createVectorStoreFileBatchDeserialize( +export async function _updateAgentDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreFileBatchDeserializer(result.body); + return agentDeserializer(result.body); } -/** Create a vector store file batch. */ -export async function createVectorStoreFileBatch( +/** Modifies an existing agent. */ +export async function updateAgent( context: Client, - vectorStoreId: string, - fileIds: string[], - options: AgentsCreateVectorStoreFileBatchOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _createVectorStoreFileBatchSend( - context, - vectorStoreId, - fileIds, - options, - ); - return _createVectorStoreFileBatchDeserialize(result); + assistantId: string, + options: AgentsUpdateAgentOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateAgentSend(context, assistantId, options); + return _updateAgentDeserialize(result); } -export function _getVectorStoreFileBatchSend( +export function _getAgentSend( context: Client, - vectorStoreId: string, - batchId: string, - options: AgentsGetVectorStoreFileBatchOptionalParams = { requestOptions: {} }, + assistantId: string, + options: AgentsGetAgentOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/vector_stores/{vectorStoreId}/file_batches/{batchId}", - vectorStoreId, - batchId, - ) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/assistants/{assistantId}", assistantId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getVectorStoreFileBatchDeserialize( +export async function _getAgentDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreFileBatchDeserializer(result.body); + return agentDeserializer(result.body); } -/** Retrieve a vector store file batch. */ -export async function getVectorStoreFileBatch( +/** Retrieves an existing agent. */ +export async function getAgent( context: Client, - vectorStoreId: string, - batchId: string, - options: AgentsGetVectorStoreFileBatchOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getVectorStoreFileBatchSend( - context, - vectorStoreId, - batchId, - options, - ); - return _getVectorStoreFileBatchDeserialize(result); + assistantId: string, + options: AgentsGetAgentOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getAgentSend(context, assistantId, options); + return _getAgentDeserialize(result); } -export function _cancelVectorStoreFileBatchSend( +export function _listAgentsSend( context: Client, - vectorStoreId: string, - batchId: string, - options: AgentsCancelVectorStoreFileBatchOptionalParams = { - requestOptions: {}, - }, + options: AgentsListAgentsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/vector_stores/{vectorStoreId}/file_batches/{batchId}/cancel", - vectorStoreId, - batchId, - ) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/assistants") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + limit: options?.limit, + order: options?.order, + after: options?.after, + before: options?.before, + }, + }); } -export async function _cancelVectorStoreFileBatchDeserialize( +export async function _listAgentsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return vectorStoreFileBatchDeserializer(result.body); + return openAIPageableListOfAgentDeserializer(result.body); } -/** Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. */ -export async function cancelVectorStoreFileBatch( +/** Gets a list of agents that were previously created. */ +export async function listAgents( context: Client, - vectorStoreId: string, - batchId: string, - options: AgentsCancelVectorStoreFileBatchOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _cancelVectorStoreFileBatchSend( - context, - vectorStoreId, - batchId, - options, - ); - return _cancelVectorStoreFileBatchDeserialize(result); + options: AgentsListAgentsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listAgentsSend(context, options); + return _listAgentsDeserialize(result); } -export function _listVectorStoreFileBatchFilesSend( +export function _createAgentSend( context: Client, - vectorStoreId: string, - batchId: string, - options: AgentsListVectorStoreFileBatchFilesOptionalParams = { - requestOptions: {}, - }, + model: string, + options: AgentsCreateAgentOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/vector_stores/{vectorStoreId}/file_batches/{batchId}/files", - vectorStoreId, - batchId, - ) - .get({ + .path("/assistants") + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - filter: options?.filter, - limit: options?.limit, - order: options?.order, - after: options?.after, - before: options?.before, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + model: model, + name: options?.name, + description: options?.description, + instructions: options?.instructions, + tools: !options?.tools + ? options?.tools + : toolDefinitionUnionArraySerializer(options?.tools), + tool_resources: !options?.toolResources + ? options?.toolResources + : toolResourcesSerializer(options?.toolResources), + temperature: options?.temperature, + top_p: options?.topP, + response_format: !options?.responseFormat + ? options?.responseFormat + : agentsApiResponseFormatOptionSerializer(options?.responseFormat), + metadata: options?.metadata, }, }); } -export async function _listVectorStoreFileBatchFilesDeserialize( +export async function _createAgentDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIPageableListOfVectorStoreFileDeserializer(result.body); + return agentDeserializer(result.body); } -/** Returns a list of vector store files in a batch. */ -export async function listVectorStoreFileBatchFiles( +/** Creates a new agent. */ +export async function createAgent( context: Client, - vectorStoreId: string, - batchId: string, - options: AgentsListVectorStoreFileBatchFilesOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _listVectorStoreFileBatchFilesSend( - context, - vectorStoreId, - batchId, - options, - ); - return _listVectorStoreFileBatchFilesDeserialize(result); + model: string, + options: AgentsCreateAgentOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createAgentSend(context, model, options); + return _createAgentDeserialize(result); } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/azureAIContext.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/azureAIContext.ts index 7209c2dad1..f963473440 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/azureAIContext.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/azureAIContext.ts @@ -6,7 +6,17 @@ import { KnownVersions } from "../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface AzureAIContext extends Client {} +export interface AzureAIContext extends Client { + /** The Azure subscription ID. */ + subscriptionId: string; + /** The name of the Azure Resource Group. */ + resourceGroupName: string; + /** The Azure AI Studio project name. */ + projectName: string; + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface AzureAIClientOptionalParams extends ClientOptions { @@ -60,5 +70,11 @@ export function createAzureAI( return next(req); }, }); - return clientContext; + return { + ...clientContext, + subscriptionId, + resourceGroupName, + projectName, + apiVersion, + } as AzureAIContext; } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/connections/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/connections/index.ts index 268a08507d..3db0b95d89 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/connections/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/connections/index.ts @@ -20,40 +20,51 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _listSend( +export function _listSecretsSend( context: Client, - options: ConnectionsListOptionalParams = { requestOptions: {} }, + connectionName: string, + ignored: string, + options: ConnectionsListSecretsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/connections") - .get({ + .path("/connections/{connectionName}/listsecrets", connectionName) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - category: options?.category, - includeAll: options?.includeAll, - target: options?.target, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, + body: { ignored: ignored }, }); } -export async function _listDeserialize( +export async function _listSecretsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return connectionsListResponseDeserializer(result.body); + return connectionsListSecretsResponseDeserializer(result.body); } -/** List the details of all the connections (not including their credentials) */ -export async function list( +/** Get the details of a single connection, including credentials (if available). */ +export async function listSecrets( context: Client, - options: ConnectionsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + connectionName: string, + ignored: string, + options: ConnectionsListSecretsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSecretsSend( + context, + connectionName, + ignored, + options, + ); + return _listSecretsDeserialize(result); } export function _getSend( @@ -63,7 +74,14 @@ export function _getSend( ): StreamableMethod { return context .path("/connections/{connectionName}", connectionName) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _getDeserialize( @@ -87,43 +105,43 @@ export async function get( return _getDeserialize(result); } -export function _listSecretsSend( +export function _listSend( context: Client, - connectionName: string, - ignored: string, - options: ConnectionsListSecretsOptionalParams = { requestOptions: {} }, + options: ConnectionsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/connections/{connectionName}/listsecrets", connectionName) - .post({ + .path("/connections") + .get({ ...operationOptionsToRequestParameters(options), - body: { ignored: ignored }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + category: options?.category, + includeAll: options?.includeAll, + target: options?.target, + }, }); } -export async function _listSecretsDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return connectionsListSecretsResponseDeserializer(result.body); + return connectionsListResponseDeserializer(result.body); } -/** Get the details of a single connection, including credentials (if available). */ -export async function listSecrets( +/** List the details of all the connections (not including their credentials) */ +export async function list( context: Client, - connectionName: string, - ignored: string, - options: ConnectionsListSecretsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSecretsSend( - context, - connectionName, - ignored, - options, - ); - return _listSecretsDeserialize(result); + options: ConnectionsListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/evaluations/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/evaluations/index.ts index 810d12b0a4..3039efc37c 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/evaluations/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/evaluations/index.ts @@ -35,92 +35,64 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _getSend( +export function _deleteScheduleSend( context: Client, id: string, - options: EvaluationsGetOptionalParams = { requestOptions: {} }, + options: EvaluationsDeleteScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/evaluations/runs/{id}", id) - .get({ + .path("/evaluations/schedules/{id}", id) + .delete({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _getDeserialize( +export async function _deleteScheduleDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return evaluationDeserializer(result.body); + return; } -/** Resource read operation template. */ -export async function get( +/** Resource delete operation template. */ +export async function deleteSchedule( context: Client, id: string, - options: EvaluationsGetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getSend(context, id, options); - return _getDeserialize(result); -} - -export function _createSend( - context: Client, - evaluation: Evaluation, - options: EvaluationsCreateOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/evaluations/runs:run") - .post({ - ...operationOptionsToRequestParameters(options), - body: evaluationSerializer(evaluation), - }); -} - -export async function _createDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return evaluationDeserializer(result.body); -} - -/** Run the evaluation. */ -export async function create( - context: Client, - evaluation: Evaluation, - options: EvaluationsCreateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createSend(context, evaluation, options); - return _createDeserialize(result); + options: EvaluationsDeleteScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteScheduleSend(context, id, options); + return _deleteScheduleDeserialize(result); } -export function _listSend( +export function _listScheduleSend( context: Client, - options: EvaluationsListOptionalParams = { requestOptions: {} }, + options: EvaluationsListScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/evaluations/runs") + .path("/evaluations/schedules") .get({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { + "api-version": context.apiVersion, top: options?.top, skip: options?.skip, maxpagesize: options?.maxpagesize, @@ -128,72 +100,83 @@ export function _listSend( }); } -export async function _listDeserialize( +export async function _listScheduleDeserialize( result: PathUncheckedResponse, -): Promise<_PagedEvaluation> { +): Promise<_PagedEvaluationSchedule> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedEvaluationDeserializer(result.body); + return _pagedEvaluationScheduleDeserializer(result.body); } /** Resource list operation template. */ -export function list( +export function listSchedule( context: Client, - options: EvaluationsListOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: EvaluationsListScheduleOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listSend(context, options), - _listDeserialize, + () => _listScheduleSend(context, options), + _listScheduleDeserialize, ["200"], { itemName: "value", nextLinkName: "nextLink" }, ); } -export function _updateSend( +export function _createOrReplaceScheduleSend( context: Client, id: string, - resource: Evaluation, - options: EvaluationsUpdateOptionalParams = { requestOptions: {} }, + resource: EvaluationSchedule, + options: EvaluationsCreateOrReplaceScheduleOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/evaluations/runs/{id}", id) - .patch({ + .path("/evaluations/schedules/{id}", id) + .put({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", + contentType: "application/json", headers: { ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, - body: evaluationSerializer(resource), + queryParameters: { "api-version": context.apiVersion }, + body: evaluationScheduleSerializer(resource), }); } -export async function _updateDeserialize( +export async function _createOrReplaceScheduleDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return evaluationDeserializer(result.body); + return evaluationScheduleDeserializer(result.body); } -/** Resource update operation template. */ -export async function update( +/** Create or replace operation template. */ +export async function createOrReplaceSchedule( context: Client, id: string, - resource: Evaluation, - options: EvaluationsUpdateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateSend(context, id, resource, options); - return _updateDeserialize(result); + resource: EvaluationSchedule, + options: EvaluationsCreateOrReplaceScheduleOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _createOrReplaceScheduleSend( + context, + id, + resource, + options, + ); + return _createOrReplaceScheduleDeserialize(result); } export function _getScheduleSend( @@ -209,7 +192,10 @@ export function _getScheduleSend( ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } @@ -234,70 +220,68 @@ export async function getSchedule( return _getScheduleDeserialize(result); } -export function _createOrReplaceScheduleSend( +export function _updateSend( context: Client, id: string, - resource: EvaluationSchedule, - options: EvaluationsCreateOrReplaceScheduleOptionalParams = { - requestOptions: {}, - }, + resource: Evaluation, + options: EvaluationsUpdateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/evaluations/schedules/{id}", id) - .put({ + .path("/evaluations/runs/{id}", id) + .patch({ ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", headers: { ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, - body: evaluationScheduleSerializer(resource), + queryParameters: { "api-version": context.apiVersion }, + body: evaluationSerializer(resource), }); } -export async function _createOrReplaceScheduleDeserialize( +export async function _updateDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "201"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return evaluationScheduleDeserializer(result.body); + return evaluationDeserializer(result.body); } -/** Create or replace operation template. */ -export async function createOrReplaceSchedule( +/** Resource update operation template. */ +export async function update( context: Client, id: string, - resource: EvaluationSchedule, - options: EvaluationsCreateOrReplaceScheduleOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _createOrReplaceScheduleSend( - context, - id, - resource, - options, - ); - return _createOrReplaceScheduleDeserialize(result); + resource: Evaluation, + options: EvaluationsUpdateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateSend(context, id, resource, options); + return _updateDeserialize(result); } -export function _listScheduleSend( +export function _listSend( context: Client, - options: EvaluationsListScheduleOptionalParams = { requestOptions: {} }, + options: EvaluationsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/evaluations/schedules") + .path("/evaluations/runs") .get({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { + "api-version": context.apiVersion, top: options?.top, skip: options?.skip, maxpagesize: options?.maxpagesize, @@ -305,65 +289,108 @@ export function _listScheduleSend( }); } -export async function _listScheduleDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise<_PagedEvaluationSchedule> { +): Promise<_PagedEvaluation> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedEvaluationScheduleDeserializer(result.body); + return _pagedEvaluationDeserializer(result.body); } /** Resource list operation template. */ -export function listSchedule( +export function list( context: Client, - options: EvaluationsListScheduleOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: EvaluationsListOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listScheduleSend(context, options), - _listScheduleDeserialize, + () => _listSend(context, options), + _listDeserialize, ["200"], { itemName: "value", nextLinkName: "nextLink" }, ); } -export function _deleteScheduleSend( +export function _createSend( + context: Client, + evaluation: Evaluation, + options: EvaluationsCreateOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/evaluations/runs:run") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { apiVersion: context.apiVersion }, + body: evaluationSerializer(evaluation), + }); +} + +export async function _createDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["201"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return evaluationDeserializer(result.body); +} + +/** Run the evaluation. */ +export async function create( + context: Client, + evaluation: Evaluation, + options: EvaluationsCreateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createSend(context, evaluation, options); + return _createDeserialize(result); +} + +export function _getSend( context: Client, id: string, - options: EvaluationsDeleteScheduleOptionalParams = { requestOptions: {} }, + options: EvaluationsGetOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/evaluations/schedules/{id}", id) - .delete({ + .path("/evaluations/runs/{id}", id) + .get({ ...operationOptionsToRequestParameters(options), headers: { ...(options?.clientRequestId !== undefined ? { "x-ms-client-request-id": options?.clientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _deleteScheduleDeserialize( +export async function _getDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return evaluationDeserializer(result.body); } -/** Resource delete operation template. */ -export async function deleteSchedule( +/** Resource read operation template. */ +export async function get( context: Client, id: string, - options: EvaluationsDeleteScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteScheduleSend(context, id, options); - return _deleteScheduleDeserialize(result); + options: EvaluationsGetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSend(context, id, options); + return _getDeserialize(result); } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/index.ts index c9da69e867..ee27dc77f0 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/index.ts @@ -7,55 +7,55 @@ export { AzureAIClientOptionalParams, } from "./azureAIContext.js"; export { - AgentsCreateAgentOptionalParams, - AgentsListAgentsOptionalParams, - AgentsGetAgentOptionalParams, - AgentsUpdateAgentOptionalParams, - AgentsDeleteAgentOptionalParams, - AgentsCreateThreadOptionalParams, - AgentsGetThreadOptionalParams, - AgentsUpdateThreadOptionalParams, - AgentsDeleteThreadOptionalParams, - AgentsCreateMessageOptionalParams, - AgentsListMessagesOptionalParams, - AgentsGetMessageOptionalParams, - AgentsUpdateMessageOptionalParams, - AgentsCreateRunOptionalParams, - AgentsListRunsOptionalParams, - AgentsGetRunOptionalParams, - AgentsUpdateRunOptionalParams, - AgentsSubmitToolOutputsToRunOptionalParams, - AgentsCancelRunOptionalParams, - AgentsCreateThreadAndRunOptionalParams, - AgentsGetRunStepOptionalParams, - AgentsListRunStepsOptionalParams, - AgentsListFilesOptionalParams, - AgentsUploadFileOptionalParams, - AgentsDeleteFileOptionalParams, - AgentsGetFileOptionalParams, - AgentsGetFileContentOptionalParams, - AgentsListVectorStoresOptionalParams, - AgentsCreateVectorStoreOptionalParams, - AgentsGetVectorStoreOptionalParams, - AgentsModifyVectorStoreOptionalParams, - AgentsDeleteVectorStoreOptionalParams, - AgentsListVectorStoreFilesOptionalParams, - AgentsCreateVectorStoreFileOptionalParams, - AgentsGetVectorStoreFileOptionalParams, - AgentsDeleteVectorStoreFileOptionalParams, - AgentsCreateVectorStoreFileBatchOptionalParams, - AgentsGetVectorStoreFileBatchOptionalParams, - AgentsCancelVectorStoreFileBatchOptionalParams, - AgentsListVectorStoreFileBatchFilesOptionalParams, - ConnectionsListOptionalParams, - ConnectionsGetOptionalParams, - ConnectionsListSecretsOptionalParams, - EvaluationsGetOptionalParams, - EvaluationsCreateOptionalParams, - EvaluationsListOptionalParams, - EvaluationsUpdateOptionalParams, - EvaluationsGetScheduleOptionalParams, - EvaluationsCreateOrReplaceScheduleOptionalParams, - EvaluationsListScheduleOptionalParams, EvaluationsDeleteScheduleOptionalParams, + EvaluationsListScheduleOptionalParams, + EvaluationsCreateOrReplaceScheduleOptionalParams, + EvaluationsGetScheduleOptionalParams, + EvaluationsUpdateOptionalParams, + EvaluationsListOptionalParams, + EvaluationsCreateOptionalParams, + EvaluationsGetOptionalParams, + ConnectionsListSecretsOptionalParams, + ConnectionsGetOptionalParams, + ConnectionsListOptionalParams, + AgentsListVectorStoreFileBatchFilesOptionalParams, + AgentsCancelVectorStoreFileBatchOptionalParams, + AgentsGetVectorStoreFileBatchOptionalParams, + AgentsCreateVectorStoreFileBatchOptionalParams, + AgentsDeleteVectorStoreFileOptionalParams, + AgentsGetVectorStoreFileOptionalParams, + AgentsCreateVectorStoreFileOptionalParams, + AgentsListVectorStoreFilesOptionalParams, + AgentsDeleteVectorStoreOptionalParams, + AgentsModifyVectorStoreOptionalParams, + AgentsGetVectorStoreOptionalParams, + AgentsCreateVectorStoreOptionalParams, + AgentsListVectorStoresOptionalParams, + AgentsGetFileContentOptionalParams, + AgentsGetFileOptionalParams, + AgentsDeleteFileOptionalParams, + AgentsUploadFileOptionalParams, + AgentsListFilesOptionalParams, + AgentsListRunStepsOptionalParams, + AgentsGetRunStepOptionalParams, + AgentsCreateThreadAndRunOptionalParams, + AgentsCancelRunOptionalParams, + AgentsSubmitToolOutputsToRunOptionalParams, + AgentsUpdateRunOptionalParams, + AgentsGetRunOptionalParams, + AgentsListRunsOptionalParams, + AgentsCreateRunOptionalParams, + AgentsUpdateMessageOptionalParams, + AgentsGetMessageOptionalParams, + AgentsListMessagesOptionalParams, + AgentsCreateMessageOptionalParams, + AgentsDeleteThreadOptionalParams, + AgentsUpdateThreadOptionalParams, + AgentsGetThreadOptionalParams, + AgentsCreateThreadOptionalParams, + AgentsDeleteAgentOptionalParams, + AgentsUpdateAgentOptionalParams, + AgentsGetAgentOptionalParams, + AgentsListAgentsOptionalParams, + AgentsCreateAgentOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/options.ts index 58cbb95b16..3d864d1f2b 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/api/options.ts @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { OperationOptions } from "@azure-rest/core-client"; import { ConnectionType, ToolDefinitionUnion, @@ -20,137 +19,90 @@ import { ListSortOrder, VectorStoreFileStatusFilter, } from "../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface AgentsCreateAgentOptionalParams extends OperationOptions { - /** The name of the new agent. */ - name?: string | null; - /** The description of the new agent. */ - description?: string | null; - /** The system instructions for the new agent to use. */ - instructions?: string | null; - /** The collection of tools to enable for the new agent. */ - tools?: ToolDefinitionUnion[]; - /** - * A set of resources that are used by the agent's tools. The resources are specific to the type of tool. For example, the `code_interpreter` - * tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - */ - toolResources?: ToolResources | null; - /** - * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, - * while lower values like 0.2 will make it more focused and deterministic. - */ - temperature?: number | null; - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. - * So 0.1 means only the tokens comprising the top 10% probability mass are considered. - * - * We generally recommend altering this or temperature but not both. - */ - topP?: number | null; - /** The response format of the tool calls used by this agent. */ - responseFormat?: AgentsApiResponseFormatOption | null; - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface EvaluationsDeleteScheduleOptionalParams + extends OperationOptions { + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; } /** Optional parameters. */ -export interface AgentsListAgentsOptionalParams extends OperationOptions { - /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ - limit?: number; - /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ - order?: ListSortOrder; - /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */ - after?: string; - /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */ - before?: string; +export interface EvaluationsListScheduleOptionalParams + extends OperationOptions { + /** The number of result items to return. */ + top?: number; + /** The number of result items to skip. */ + skip?: number; + /** The maximum number of result items per page. */ + maxpagesize?: number; + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; } /** Optional parameters. */ -export interface AgentsGetAgentOptionalParams extends OperationOptions {} +export interface EvaluationsCreateOrReplaceScheduleOptionalParams + extends OperationOptions { + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; +} /** Optional parameters. */ -export interface AgentsUpdateAgentOptionalParams extends OperationOptions { - /** The ID of the model to use. */ - model?: string; - /** The modified name for the agent to use. */ - name?: string | null; - /** The modified description for the agent to use. */ - description?: string | null; - /** The modified system instructions for the new agent to use. */ - instructions?: string | null; - /** The modified collection of tools to enable for the agent. */ - tools?: ToolDefinitionUnion[]; - /** - * A set of resources that are used by the agent's tools. The resources are specific to the type of tool. For example, - * the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. - */ - toolResources?: ToolResources; - /** - * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, - * while lower values like 0.2 will make it more focused and deterministic. - */ - temperature?: number | null; - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. - * So 0.1 means only the tokens comprising the top 10% probability mass are considered. - * - * We generally recommend altering this or temperature but not both. - */ - topP?: number | null; - /** The response format of the tool calls used by this agent. */ - responseFormat?: AgentsApiResponseFormatOption | null; - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface EvaluationsGetScheduleOptionalParams extends OperationOptions { + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; } /** Optional parameters. */ -export interface AgentsDeleteAgentOptionalParams extends OperationOptions {} +export interface EvaluationsUpdateOptionalParams extends OperationOptions { + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; +} /** Optional parameters. */ -export interface AgentsCreateThreadOptionalParams extends OperationOptions { - /** The initial messages to associate with the new thread. */ - messages?: ThreadMessageOptions[]; - /** - * A set of resources that are made available to the agent's tools in this thread. The resources are specific to the - * type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires - * a list of vector store IDs. - */ - toolResources?: ToolResources | null; - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface EvaluationsListOptionalParams extends OperationOptions { + /** The number of result items to return. */ + top?: number; + /** The number of result items to skip. */ + skip?: number; + /** The maximum number of result items per page. */ + maxpagesize?: number; + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; } /** Optional parameters. */ -export interface AgentsGetThreadOptionalParams extends OperationOptions {} +export interface EvaluationsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AgentsUpdateThreadOptionalParams extends OperationOptions { - /** - * A set of resources that are made available to the agent's tools in this thread. The resources are specific to the - * type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires - * a list of vector store IDs - */ - toolResources?: ToolResources | null; - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface EvaluationsGetOptionalParams extends OperationOptions { + /** An opaque, globally-unique, client-generated string identifier for the request. */ + clientRequestId?: string; } /** Optional parameters. */ -export interface AgentsDeleteThreadOptionalParams extends OperationOptions {} +export interface ConnectionsListSecretsOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface AgentsCreateMessageOptionalParams extends OperationOptions { - /** A list of files attached to the message, and the tools they should be added to. */ - attachments?: MessageAttachment[] | null; - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface ConnectionsGetOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface ConnectionsListOptionalParams extends OperationOptions { + /** Category of the workspace connection. */ + category?: ConnectionType; + /** Indicates whether to list datastores. Service default: do not list datastores. */ + includeAll?: boolean; + /** Target of the workspace connection. */ + target?: string; } /** Optional parameters. */ -export interface AgentsListMessagesOptionalParams extends OperationOptions { - /** Filter messages by the run ID that generated them. */ - runId?: string; +export interface AgentsListVectorStoreFileBatchFilesOptionalParams + extends OperationOptions { + /** Filter by file status. */ + filter?: VectorStoreFileStatusFilter; /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ limit?: number; /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ @@ -162,71 +114,40 @@ export interface AgentsListMessagesOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface AgentsGetMessageOptionalParams extends OperationOptions {} +export interface AgentsCancelVectorStoreFileBatchOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface AgentsUpdateMessageOptionalParams extends OperationOptions { - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface AgentsGetVectorStoreFileBatchOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsCreateVectorStoreFileBatchOptionalParams + extends OperationOptions { + /** The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. */ + chunkingStrategy?: VectorStoreChunkingStrategyRequestUnion; } /** Optional parameters. */ -export interface AgentsCreateRunOptionalParams extends OperationOptions { - /** The overridden model name that the agent should use to run the thread. */ - model?: string | null; - /** The overridden system instructions that the agent should use to run the thread. */ - instructions?: string | null; - /** - * Additional instructions to append at the end of the instructions for the run. This is useful for modifying the behavior - * on a per-run basis without overriding other instructions. - */ - additionalInstructions?: string | null; - /** Adds additional messages to the thread before creating the run. */ - additionalMessages?: ThreadMessage[] | null; - /** The overridden list of enabled tools that the agent should use to run the thread. */ - tools?: ToolDefinitionUnion[] | null; - /** - * If `true`, returns a stream of events that happen during the Run as server-sent events, - * terminating when the Run enters a terminal state with a `data: [DONE]` message. - */ - stream?: boolean; - /** - * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - * more random, while lower values like 0.2 will make it more focused and deterministic. - */ - temperature?: number | null; - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model - * considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - * comprising the top 10% probability mass are considered. - * - * We generally recommend altering this or temperature but not both. - */ - topP?: number | null; - /** - * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only - * the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, - * the run will end with status `incomplete`. See `incomplete_details` for more info. - */ - maxPromptTokens?: number | null; - /** - * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort - * to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - * completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. - */ - maxCompletionTokens?: number | null; - /** The strategy to use for dropping messages as the context windows moves forward. */ - truncationStrategy?: TruncationObject | null; - /** Controls whether or not and which tool is called by the model. */ - toolChoice?: AgentsApiToolChoiceOption | null; - /** Specifies the format that the model must output. */ - responseFormat?: AgentsApiResponseFormatOption | null; - /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ - metadata?: Record | null; +export interface AgentsDeleteVectorStoreFileOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsGetVectorStoreFileOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsCreateVectorStoreFileOptionalParams + extends OperationOptions { + /** The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. */ + chunkingStrategy?: VectorStoreChunkingStrategyRequestUnion; } /** Optional parameters. */ -export interface AgentsListRunsOptionalParams extends OperationOptions { +export interface AgentsListVectorStoreFilesOptionalParams + extends OperationOptions { + /** Filter by file status. */ + filter?: VectorStoreFileStatusFilter; /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ limit?: number; /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ @@ -238,23 +159,85 @@ export interface AgentsListRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface AgentsGetRunOptionalParams extends OperationOptions {} +export interface AgentsDeleteVectorStoreOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface AgentsUpdateRunOptionalParams extends OperationOptions { +export interface AgentsModifyVectorStoreOptionalParams + extends OperationOptions { + /** The name of the vector store. */ + name?: string | null; + /** Details on when this vector store expires */ + expiresAfter?: VectorStoreExpirationPolicy | null; /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsSubmitToolOutputsToRunOptionalParams - extends OperationOptions { - /** If true, returns a stream of events that happen during the Run as server-sent events, terminating when the run enters a terminal state. */ - stream?: boolean | null; +export interface AgentsGetVectorStoreOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsCreateVectorStoreOptionalParams + extends OperationOptions { + /** A list of file IDs that the vector store should use. Useful for tools like `file_search` that can access files. */ + fileIds?: string[]; + /** The name of the vector store. */ + name?: string; + /** Details on when this vector store expires */ + expiresAfter?: VectorStoreExpirationPolicy; + /** The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. Only applicable if file_ids is non-empty. */ + chunkingStrategy?: VectorStoreChunkingStrategyRequestUnion; + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsCancelRunOptionalParams extends OperationOptions {} +export interface AgentsListVectorStoresOptionalParams extends OperationOptions { + /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ + limit?: number; + /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ + order?: ListSortOrder; + /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */ + after?: string; + /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */ + before?: string; +} + +/** Optional parameters. */ +export interface AgentsGetFileContentOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsGetFileOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsDeleteFileOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsUploadFileOptionalParams extends OperationOptions { + /** The name of the file. */ + filename?: string; +} + +/** Optional parameters. */ +export interface AgentsListFilesOptionalParams extends OperationOptions { + /** The purpose of the file. */ + purpose?: FilePurpose; +} + +/** Optional parameters. */ +export interface AgentsListRunStepsOptionalParams extends OperationOptions { + /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ + limit?: number; + /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ + order?: ListSortOrder; + /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */ + after?: string; + /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */ + before?: string; +} + +/** Optional parameters. */ +export interface AgentsGetRunStepOptionalParams extends OperationOptions {} /** Optional parameters. */ export interface AgentsCreateThreadAndRunOptionalParams @@ -310,45 +293,26 @@ export interface AgentsCreateThreadAndRunOptionalParams } /** Optional parameters. */ -export interface AgentsGetRunStepOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface AgentsListRunStepsOptionalParams extends OperationOptions { - /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ - limit?: number; - /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ - order?: ListSortOrder; - /** A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. */ - after?: string; - /** A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. */ - before?: string; -} +export interface AgentsCancelRunOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AgentsListFilesOptionalParams extends OperationOptions { - /** The purpose of the file. */ - purpose?: FilePurpose; +export interface AgentsSubmitToolOutputsToRunOptionalParams + extends OperationOptions { + /** If true, returns a stream of events that happen during the Run as server-sent events, terminating when the run enters a terminal state. */ + stream?: boolean | null; } /** Optional parameters. */ -export interface AgentsUploadFileOptionalParams extends OperationOptions { - /** The name of the file to upload. */ - contentType?: string; - /** The name of the file. */ - filename?: string; +export interface AgentsUpdateRunOptionalParams extends OperationOptions { + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsDeleteFileOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface AgentsGetFileOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface AgentsGetFileContentOptionalParams extends OperationOptions {} +export interface AgentsGetRunOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AgentsListVectorStoresOptionalParams extends OperationOptions { +export interface AgentsListRunsOptionalParams extends OperationOptions { /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ limit?: number; /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ @@ -360,43 +324,73 @@ export interface AgentsListVectorStoresOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface AgentsCreateVectorStoreOptionalParams - extends OperationOptions { - /** A list of file IDs that the vector store should use. Useful for tools like `file_search` that can access files. */ - fileIds?: string[]; - /** The name of the vector store. */ - name?: string; - /** Details on when this vector store expires */ - expiresAfter?: VectorStoreExpirationPolicy; - /** The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. Only applicable if file_ids is non-empty. */ - chunkingStrategy?: VectorStoreChunkingStrategyRequestUnion; +export interface AgentsCreateRunOptionalParams extends OperationOptions { + /** The overridden model name that the agent should use to run the thread. */ + model?: string | null; + /** The overridden system instructions that the agent should use to run the thread. */ + instructions?: string | null; + /** + * Additional instructions to append at the end of the instructions for the run. This is useful for modifying the behavior + * on a per-run basis without overriding other instructions. + */ + additionalInstructions?: string | null; + /** Adds additional messages to the thread before creating the run. */ + additionalMessages?: ThreadMessage[] | null; + /** The overridden list of enabled tools that the agent should use to run the thread. */ + tools?: ToolDefinitionUnion[] | null; + /** + * If `true`, returns a stream of events that happen during the Run as server-sent events, + * terminating when the Run enters a terminal state with a `data: [DONE]` message. + */ + stream?: boolean; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + * more random, while lower values like 0.2 will make it more focused and deterministic. + */ + temperature?: number | null; + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model + * considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + * comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + topP?: number | null; + /** + * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + * the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + * the run will end with status `incomplete`. See `incomplete_details` for more info. + */ + maxPromptTokens?: number | null; + /** + * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + * to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + * completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + */ + maxCompletionTokens?: number | null; + /** The strategy to use for dropping messages as the context windows moves forward. */ + truncationStrategy?: TruncationObject | null; + /** Controls whether or not and which tool is called by the model. */ + toolChoice?: AgentsApiToolChoiceOption | null; + /** Specifies the format that the model must output. */ + responseFormat?: AgentsApiResponseFormatOption | null; /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsGetVectorStoreOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface AgentsModifyVectorStoreOptionalParams - extends OperationOptions { - /** The name of the vector store. */ - name?: string | null; - /** Details on when this vector store expires */ - expiresAfter?: VectorStoreExpirationPolicy | null; +export interface AgentsUpdateMessageOptionalParams extends OperationOptions { /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsDeleteVectorStoreOptionalParams - extends OperationOptions {} +export interface AgentsGetMessageOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AgentsListVectorStoreFilesOptionalParams - extends OperationOptions { - /** Filter by file status. */ - filter?: VectorStoreFileStatusFilter; +export interface AgentsListMessagesOptionalParams extends OperationOptions { + /** Filter messages by the run ID that generated them. */ + runId?: string; /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ limit?: number; /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ @@ -408,40 +402,88 @@ export interface AgentsListVectorStoreFilesOptionalParams } /** Optional parameters. */ -export interface AgentsCreateVectorStoreFileOptionalParams - extends OperationOptions { - /** The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. */ - chunkingStrategy?: VectorStoreChunkingStrategyRequestUnion; +export interface AgentsCreateMessageOptionalParams extends OperationOptions { + /** A list of files attached to the message, and the tools they should be added to. */ + attachments?: MessageAttachment[] | null; + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsGetVectorStoreFileOptionalParams - extends OperationOptions {} +export interface AgentsDeleteThreadOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AgentsDeleteVectorStoreFileOptionalParams - extends OperationOptions {} +export interface AgentsUpdateThreadOptionalParams extends OperationOptions { + /** + * A set of resources that are made available to the agent's tools in this thread. The resources are specific to the + * type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + * a list of vector store IDs + */ + toolResources?: ToolResources | null; + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; +} /** Optional parameters. */ -export interface AgentsCreateVectorStoreFileBatchOptionalParams - extends OperationOptions { - /** The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. */ - chunkingStrategy?: VectorStoreChunkingStrategyRequestUnion; +export interface AgentsGetThreadOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsCreateThreadOptionalParams extends OperationOptions { + /** The initial messages to associate with the new thread. */ + messages?: ThreadMessageOptions[]; + /** + * A set of resources that are made available to the agent's tools in this thread. The resources are specific to the + * type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + * a list of vector store IDs. + */ + toolResources?: ToolResources | null; + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; } /** Optional parameters. */ -export interface AgentsGetVectorStoreFileBatchOptionalParams - extends OperationOptions {} +export interface AgentsDeleteAgentOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AgentsCancelVectorStoreFileBatchOptionalParams - extends OperationOptions {} +export interface AgentsUpdateAgentOptionalParams extends OperationOptions { + /** The ID of the model to use. */ + model?: string; + /** The modified name for the agent to use. */ + name?: string | null; + /** The modified description for the agent to use. */ + description?: string | null; + /** The modified system instructions for the new agent to use. */ + instructions?: string | null; + /** The modified collection of tools to enable for the agent. */ + tools?: ToolDefinitionUnion[]; + /** + * A set of resources that are used by the agent's tools. The resources are specific to the type of tool. For example, + * the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + */ + toolResources?: ToolResources; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + * while lower values like 0.2 will make it more focused and deterministic. + */ + temperature?: number | null; + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + * So 0.1 means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + topP?: number | null; + /** The response format of the tool calls used by this agent. */ + responseFormat?: AgentsApiResponseFormatOption | null; + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; +} /** Optional parameters. */ -export interface AgentsListVectorStoreFileBatchFilesOptionalParams - extends OperationOptions { - /** Filter by file status. */ - filter?: VectorStoreFileStatusFilter; +export interface AgentsGetAgentOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AgentsListAgentsOptionalParams extends OperationOptions { /** A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. */ limit?: number; /** Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. */ @@ -453,80 +495,34 @@ export interface AgentsListVectorStoreFileBatchFilesOptionalParams } /** Optional parameters. */ -export interface ConnectionsListOptionalParams extends OperationOptions { - /** Category of the workspace connection. */ - category?: ConnectionType; - /** Indicates whether to list datastores. Service default: do not list datastores. */ - includeAll?: boolean; - /** Target of the workspace connection. */ - target?: string; -} - -/** Optional parameters. */ -export interface ConnectionsGetOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface ConnectionsListSecretsOptionalParams - extends OperationOptions {} - -/** Optional parameters. */ -export interface EvaluationsGetOptionalParams extends OperationOptions { - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; -} - -/** Optional parameters. */ -export interface EvaluationsCreateOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface EvaluationsListOptionalParams extends OperationOptions { - /** The number of result items to return. */ - top?: number; - /** The number of result items to skip. */ - skip?: number; - /** The maximum number of result items per page. */ - maxpagesize?: number; - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; -} - -/** Optional parameters. */ -export interface EvaluationsUpdateOptionalParams extends OperationOptions { - /** This request has a JSON Merge Patch body. */ - contentType?: string; - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; -} - -/** Optional parameters. */ -export interface EvaluationsGetScheduleOptionalParams extends OperationOptions { - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; -} - -/** Optional parameters. */ -export interface EvaluationsCreateOrReplaceScheduleOptionalParams - extends OperationOptions { - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; -} - -/** Optional parameters. */ -export interface EvaluationsListScheduleOptionalParams - extends OperationOptions { - /** The number of result items to return. */ - top?: number; - /** The number of result items to skip. */ - skip?: number; - /** The maximum number of result items per page. */ - maxpagesize?: number; - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; -} - -/** Optional parameters. */ -export interface EvaluationsDeleteScheduleOptionalParams - extends OperationOptions { - /** An opaque, globally-unique, client-generated string identifier for the request. */ - clientRequestId?: string; +export interface AgentsCreateAgentOptionalParams extends OperationOptions { + /** The name of the new agent. */ + name?: string | null; + /** The description of the new agent. */ + description?: string | null; + /** The system instructions for the new agent to use. */ + instructions?: string | null; + /** The collection of tools to enable for the new agent. */ + tools?: ToolDefinitionUnion[]; + /** + * A set of resources that are used by the agent's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + * tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + */ + toolResources?: ToolResources | null; + /** + * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + * while lower values like 0.2 will make it more focused and deterministic. + */ + temperature?: number | null; + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + * So 0.1 means only the tokens comprising the top 10% probability mass are considered. + * + * We generally recommend altering this or temperature but not both. + */ + topP?: number | null; + /** The response format of the tool calls used by this agent. */ + responseFormat?: AgentsApiResponseFormatOption | null; + /** A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. */ + metadata?: Record | null; } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/azureAIClient.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/azureAIClient.ts index 6478f29185..420bb83754 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/azureAIClient.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/azureAIClient.ts @@ -2,17 +2,17 @@ // Licensed under the MIT License. import { - getAgentsOperations, - AgentsOperations, -} from "./classic/agents/index.js"; + getEvaluationsOperations, + EvaluationsOperations, +} from "./classic/evaluations/index.js"; import { getConnectionsOperations, ConnectionsOperations, } from "./classic/connections/index.js"; import { - getEvaluationsOperations, - EvaluationsOperations, -} from "./classic/evaluations/index.js"; + getAgentsOperations, + AgentsOperations, +} from "./classic/agents/index.js"; import { createAzureAI, AzureAIContext, @@ -49,15 +49,15 @@ export class AzureAIClient { { ...options, userAgentOptions: { userAgentPrefix } }, ); this.pipeline = this._client.pipeline; - this.agents = getAgentsOperations(this._client); - this.connections = getConnectionsOperations(this._client); this.evaluations = getEvaluationsOperations(this._client); + this.connections = getConnectionsOperations(this._client); + this.agents = getAgentsOperations(this._client); } - /** The operation groups for Agents */ - public readonly agents: AgentsOperations; - /** The operation groups for Connections */ - public readonly connections: ConnectionsOperations; - /** The operation groups for Evaluations */ + /** The operation groups for evaluations */ public readonly evaluations: EvaluationsOperations; + /** The operation groups for connections */ + public readonly connections: ConnectionsOperations; + /** The operation groups for agents */ + public readonly agents: AgentsOperations; } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/agents/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/agents/index.ts index 5608ec07ef..0cc3827383 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/agents/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/agents/index.ts @@ -3,46 +3,46 @@ import { AzureAIContext } from "../../api/azureAIContext.js"; import { - createAgent, - listAgents, - getAgent, - updateAgent, - deleteAgent, - createThread, - getThread, - updateThread, - deleteThread, - createMessage, - listMessages, - getMessage, - updateMessage, - createRun, - listRuns, - getRun, - updateRun, - submitToolOutputsToRun, - cancelRun, - createThreadAndRun, - getRunStep, - listRunSteps, - listFiles, - uploadFile, - deleteFile, - getFile, - getFileContent, - listVectorStores, - createVectorStore, - getVectorStore, - modifyVectorStore, - deleteVectorStore, - listVectorStoreFiles, - createVectorStoreFile, - getVectorStoreFile, - deleteVectorStoreFile, - createVectorStoreFileBatch, - getVectorStoreFileBatch, - cancelVectorStoreFileBatch, listVectorStoreFileBatchFiles, + cancelVectorStoreFileBatch, + getVectorStoreFileBatch, + createVectorStoreFileBatch, + deleteVectorStoreFile, + getVectorStoreFile, + createVectorStoreFile, + listVectorStoreFiles, + deleteVectorStore, + modifyVectorStore, + getVectorStore, + createVectorStore, + listVectorStores, + getFileContent, + getFile, + deleteFile, + uploadFile, + listFiles, + listRunSteps, + getRunStep, + createThreadAndRun, + cancelRun, + submitToolOutputsToRun, + updateRun, + getRun, + listRuns, + createRun, + updateMessage, + getMessage, + listMessages, + createMessage, + deleteThread, + updateThread, + getThread, + createThread, + deleteAgent, + updateAgent, + getAgent, + listAgents, + createAgent, } from "../../api/agents/index.js"; import { Agent, @@ -72,433 +72,433 @@ import { VectorStoreFileBatch, } from "../../models/models.js"; import { - AgentsCreateAgentOptionalParams, - AgentsListAgentsOptionalParams, - AgentsGetAgentOptionalParams, - AgentsUpdateAgentOptionalParams, - AgentsDeleteAgentOptionalParams, - AgentsCreateThreadOptionalParams, - AgentsGetThreadOptionalParams, - AgentsUpdateThreadOptionalParams, - AgentsDeleteThreadOptionalParams, - AgentsCreateMessageOptionalParams, - AgentsListMessagesOptionalParams, - AgentsGetMessageOptionalParams, - AgentsUpdateMessageOptionalParams, - AgentsCreateRunOptionalParams, - AgentsListRunsOptionalParams, - AgentsGetRunOptionalParams, - AgentsUpdateRunOptionalParams, - AgentsSubmitToolOutputsToRunOptionalParams, - AgentsCancelRunOptionalParams, - AgentsCreateThreadAndRunOptionalParams, - AgentsGetRunStepOptionalParams, - AgentsListRunStepsOptionalParams, - AgentsListFilesOptionalParams, - AgentsUploadFileOptionalParams, - AgentsDeleteFileOptionalParams, - AgentsGetFileOptionalParams, - AgentsGetFileContentOptionalParams, - AgentsListVectorStoresOptionalParams, - AgentsCreateVectorStoreOptionalParams, - AgentsGetVectorStoreOptionalParams, - AgentsModifyVectorStoreOptionalParams, - AgentsDeleteVectorStoreOptionalParams, - AgentsListVectorStoreFilesOptionalParams, - AgentsCreateVectorStoreFileOptionalParams, - AgentsGetVectorStoreFileOptionalParams, - AgentsDeleteVectorStoreFileOptionalParams, - AgentsCreateVectorStoreFileBatchOptionalParams, - AgentsGetVectorStoreFileBatchOptionalParams, - AgentsCancelVectorStoreFileBatchOptionalParams, AgentsListVectorStoreFileBatchFilesOptionalParams, + AgentsCancelVectorStoreFileBatchOptionalParams, + AgentsGetVectorStoreFileBatchOptionalParams, + AgentsCreateVectorStoreFileBatchOptionalParams, + AgentsDeleteVectorStoreFileOptionalParams, + AgentsGetVectorStoreFileOptionalParams, + AgentsCreateVectorStoreFileOptionalParams, + AgentsListVectorStoreFilesOptionalParams, + AgentsDeleteVectorStoreOptionalParams, + AgentsModifyVectorStoreOptionalParams, + AgentsGetVectorStoreOptionalParams, + AgentsCreateVectorStoreOptionalParams, + AgentsListVectorStoresOptionalParams, + AgentsGetFileContentOptionalParams, + AgentsGetFileOptionalParams, + AgentsDeleteFileOptionalParams, + AgentsUploadFileOptionalParams, + AgentsListFilesOptionalParams, + AgentsListRunStepsOptionalParams, + AgentsGetRunStepOptionalParams, + AgentsCreateThreadAndRunOptionalParams, + AgentsCancelRunOptionalParams, + AgentsSubmitToolOutputsToRunOptionalParams, + AgentsUpdateRunOptionalParams, + AgentsGetRunOptionalParams, + AgentsListRunsOptionalParams, + AgentsCreateRunOptionalParams, + AgentsUpdateMessageOptionalParams, + AgentsGetMessageOptionalParams, + AgentsListMessagesOptionalParams, + AgentsCreateMessageOptionalParams, + AgentsDeleteThreadOptionalParams, + AgentsUpdateThreadOptionalParams, + AgentsGetThreadOptionalParams, + AgentsCreateThreadOptionalParams, + AgentsDeleteAgentOptionalParams, + AgentsUpdateAgentOptionalParams, + AgentsGetAgentOptionalParams, + AgentsListAgentsOptionalParams, + AgentsCreateAgentOptionalParams, } from "../../api/options.js"; /** Interface representing a Agents operations. */ export interface AgentsOperations { - /** Creates a new agent. */ - createAgent: ( - model: string, - options?: AgentsCreateAgentOptionalParams, - ) => Promise; - /** Gets a list of agents that were previously created. */ - listAgents: ( - options?: AgentsListAgentsOptionalParams, - ) => Promise; - /** Retrieves an existing agent. */ - getAgent: ( - assistantId: string, - options?: AgentsGetAgentOptionalParams, - ) => Promise; - /** Modifies an existing agent. */ - updateAgent: ( - assistantId: string, - options?: AgentsUpdateAgentOptionalParams, - ) => Promise; - /** Deletes an agent. */ - deleteAgent: ( - assistantId: string, - options?: AgentsDeleteAgentOptionalParams, - ) => Promise; - /** Creates a new thread. Threads contain messages and can be run by agents. */ - createThread: ( - options?: AgentsCreateThreadOptionalParams, - ) => Promise; - /** Gets information about an existing thread. */ - getThread: ( - threadId: string, - options?: AgentsGetThreadOptionalParams, - ) => Promise; - /** Modifies an existing thread. */ - updateThread: ( - threadId: string, - options?: AgentsUpdateThreadOptionalParams, - ) => Promise; - /** Deletes an existing thread. */ - deleteThread: ( - threadId: string, - options?: AgentsDeleteThreadOptionalParams, - ) => Promise; - /** Creates a new message on a specified thread. */ - createMessage: ( - threadId: string, - role: MessageRole, - content: string, - options?: AgentsCreateMessageOptionalParams, - ) => Promise; - /** Gets a list of messages that exist on a thread. */ - listMessages: ( - threadId: string, - options?: AgentsListMessagesOptionalParams, - ) => Promise; - /** Gets an existing message from an existing thread. */ - getMessage: ( - threadId: string, - messageId: string, - options?: AgentsGetMessageOptionalParams, - ) => Promise; - /** Modifies an existing message on an existing thread. */ - updateMessage: ( - threadId: string, - messageId: string, - options?: AgentsUpdateMessageOptionalParams, - ) => Promise; - /** Creates a new run for an agent thread. */ - createRun: ( - threadId: string, - assistantId: string, - options?: AgentsCreateRunOptionalParams, - ) => Promise; - /** Gets a list of runs for a specified thread. */ - listRuns: ( - threadId: string, - options?: AgentsListRunsOptionalParams, - ) => Promise; - /** Gets an existing run from an existing thread. */ - getRun: ( - threadId: string, - runId: string, - options?: AgentsGetRunOptionalParams, - ) => Promise; - /** Modifies an existing thread run. */ - updateRun: ( - threadId: string, - runId: string, - options?: AgentsUpdateRunOptionalParams, - ) => Promise; - /** Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. */ - submitToolOutputsToRun: ( - threadId: string, - runId: string, - toolOutputs: ToolOutput[], - options?: AgentsSubmitToolOutputsToRunOptionalParams, - ) => Promise; - /** Cancels a run of an in progress thread. */ - cancelRun: ( - threadId: string, - runId: string, - options?: AgentsCancelRunOptionalParams, - ) => Promise; - /** Creates a new agent thread and immediately starts a run using that new thread. */ - createThreadAndRun: ( - assistantId: string, - options?: AgentsCreateThreadAndRunOptionalParams, - ) => Promise; - /** Gets a single run step from a thread run. */ - getRunStep: ( - threadId: string, - runId: string, - stepId: string, - options?: AgentsGetRunStepOptionalParams, - ) => Promise; - /** Gets a list of run steps from a thread run. */ - listRunSteps: ( - threadId: string, - runId: string, - options?: AgentsListRunStepsOptionalParams, - ) => Promise; - /** Gets a list of previously uploaded files. */ - listFiles: ( - options?: AgentsListFilesOptionalParams, - ) => Promise; - /** Uploads a file for use by other operations. */ - uploadFile: ( - file: Uint8Array, - purpose: FilePurpose, - options?: AgentsUploadFileOptionalParams, - ) => Promise; - /** Delete a previously uploaded file. */ - deleteFile: ( - fileId: string, - options?: AgentsDeleteFileOptionalParams, - ) => Promise; - /** Returns information about a specific file. Does not retrieve file content. */ - getFile: ( - fileId: string, - options?: AgentsGetFileOptionalParams, - ) => Promise; - /** Returns information about a specific file. Does not retrieve file content. */ - getFileContent: ( - fileId: string, - options?: AgentsGetFileContentOptionalParams, - ) => Promise; - /** Returns a list of vector stores. */ - listVectorStores: ( - options?: AgentsListVectorStoresOptionalParams, - ) => Promise; - /** Creates a vector store. */ - createVectorStore: ( - options?: AgentsCreateVectorStoreOptionalParams, - ) => Promise; - /** Returns the vector store object matching the specified ID. */ - getVectorStore: ( + /** Returns a list of vector store files in a batch. */ + listVectorStoreFileBatchFiles: ( vectorStoreId: string, - options?: AgentsGetVectorStoreOptionalParams, - ) => Promise; - /** The ID of the vector store to modify. */ - modifyVectorStore: ( + batchId: string, + options?: AgentsListVectorStoreFileBatchFilesOptionalParams, + ) => Promise; + /** Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. */ + cancelVectorStoreFileBatch: ( vectorStoreId: string, - options?: AgentsModifyVectorStoreOptionalParams, - ) => Promise; - /** Deletes the vector store object matching the specified ID. */ - deleteVectorStore: ( + batchId: string, + options?: AgentsCancelVectorStoreFileBatchOptionalParams, + ) => Promise; + /** Retrieve a vector store file batch. */ + getVectorStoreFileBatch: ( vectorStoreId: string, - options?: AgentsDeleteVectorStoreOptionalParams, - ) => Promise; - /** Returns a list of vector store files. */ - listVectorStoreFiles: ( + batchId: string, + options?: AgentsGetVectorStoreFileBatchOptionalParams, + ) => Promise; + /** Create a vector store file batch. */ + createVectorStoreFileBatch: ( vectorStoreId: string, - options?: AgentsListVectorStoreFilesOptionalParams, - ) => Promise; - /** Create a vector store file by attaching a file to a vector store. */ - createVectorStoreFile: ( + fileIds: string[], + options?: AgentsCreateVectorStoreFileBatchOptionalParams, + ) => Promise; + /** + * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + * To delete the file, use the delete file endpoint. + */ + deleteVectorStoreFile: ( vectorStoreId: string, fileId: string, - options?: AgentsCreateVectorStoreFileOptionalParams, - ) => Promise; + options?: AgentsDeleteVectorStoreFileOptionalParams, + ) => Promise; /** Retrieves a vector store file. */ getVectorStoreFile: ( vectorStoreId: string, fileId: string, options?: AgentsGetVectorStoreFileOptionalParams, ) => Promise; - /** - * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. - * To delete the file, use the delete file endpoint. - */ - deleteVectorStoreFile: ( + /** Create a vector store file by attaching a file to a vector store. */ + createVectorStoreFile: ( vectorStoreId: string, fileId: string, - options?: AgentsDeleteVectorStoreFileOptionalParams, - ) => Promise; - /** Create a vector store file batch. */ - createVectorStoreFileBatch: ( + options?: AgentsCreateVectorStoreFileOptionalParams, + ) => Promise; + /** Returns a list of vector store files. */ + listVectorStoreFiles: ( vectorStoreId: string, - fileIds: string[], - options?: AgentsCreateVectorStoreFileBatchOptionalParams, - ) => Promise; - /** Retrieve a vector store file batch. */ - getVectorStoreFileBatch: ( + options?: AgentsListVectorStoreFilesOptionalParams, + ) => Promise; + /** Deletes the vector store object matching the specified ID. */ + deleteVectorStore: ( vectorStoreId: string, - batchId: string, - options?: AgentsGetVectorStoreFileBatchOptionalParams, - ) => Promise; - /** Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. */ - cancelVectorStoreFileBatch: ( + options?: AgentsDeleteVectorStoreOptionalParams, + ) => Promise; + /** The ID of the vector store to modify. */ + modifyVectorStore: ( vectorStoreId: string, - batchId: string, - options?: AgentsCancelVectorStoreFileBatchOptionalParams, - ) => Promise; - /** Returns a list of vector store files in a batch. */ - listVectorStoreFileBatchFiles: ( + options?: AgentsModifyVectorStoreOptionalParams, + ) => Promise; + /** Returns the vector store object matching the specified ID. */ + getVectorStore: ( vectorStoreId: string, - batchId: string, - options?: AgentsListVectorStoreFileBatchFilesOptionalParams, - ) => Promise; -} - -export function getAgents(context: AzureAIContext) { - return { - createAgent: (model: string, options?: AgentsCreateAgentOptionalParams) => - createAgent(context, model, options), - listAgents: (options?: AgentsListAgentsOptionalParams) => - listAgents(context, options), - getAgent: (assistantId: string, options?: AgentsGetAgentOptionalParams) => - getAgent(context, assistantId, options), - updateAgent: ( - assistantId: string, - options?: AgentsUpdateAgentOptionalParams, - ) => updateAgent(context, assistantId, options), - deleteAgent: ( - assistantId: string, - options?: AgentsDeleteAgentOptionalParams, - ) => deleteAgent(context, assistantId, options), - createThread: (options?: AgentsCreateThreadOptionalParams) => - createThread(context, options), - getThread: (threadId: string, options?: AgentsGetThreadOptionalParams) => - getThread(context, threadId, options), - updateThread: ( - threadId: string, - options?: AgentsUpdateThreadOptionalParams, - ) => updateThread(context, threadId, options), - deleteThread: ( - threadId: string, - options?: AgentsDeleteThreadOptionalParams, - ) => deleteThread(context, threadId, options), - createMessage: ( - threadId: string, - role: MessageRole, - content: string, - options?: AgentsCreateMessageOptionalParams, - ) => createMessage(context, threadId, role, content, options), - listMessages: ( - threadId: string, - options?: AgentsListMessagesOptionalParams, - ) => listMessages(context, threadId, options), - getMessage: ( - threadId: string, - messageId: string, - options?: AgentsGetMessageOptionalParams, - ) => getMessage(context, threadId, messageId, options), - updateMessage: ( - threadId: string, - messageId: string, - options?: AgentsUpdateMessageOptionalParams, - ) => updateMessage(context, threadId, messageId, options), - createRun: ( - threadId: string, - assistantId: string, - options?: AgentsCreateRunOptionalParams, - ) => createRun(context, threadId, assistantId, options), - listRuns: (threadId: string, options?: AgentsListRunsOptionalParams) => - listRuns(context, threadId, options), - getRun: ( - threadId: string, - runId: string, - options?: AgentsGetRunOptionalParams, - ) => getRun(context, threadId, runId, options), - updateRun: ( - threadId: string, - runId: string, - options?: AgentsUpdateRunOptionalParams, - ) => updateRun(context, threadId, runId, options), - submitToolOutputsToRun: ( - threadId: string, - runId: string, - toolOutputs: ToolOutput[], - options?: AgentsSubmitToolOutputsToRunOptionalParams, - ) => submitToolOutputsToRun(context, threadId, runId, toolOutputs, options), - cancelRun: ( - threadId: string, - runId: string, - options?: AgentsCancelRunOptionalParams, - ) => cancelRun(context, threadId, runId, options), - createThreadAndRun: ( - assistantId: string, - options?: AgentsCreateThreadAndRunOptionalParams, - ) => createThreadAndRun(context, assistantId, options), - getRunStep: ( - threadId: string, - runId: string, - stepId: string, - options?: AgentsGetRunStepOptionalParams, - ) => getRunStep(context, threadId, runId, stepId, options), - listRunSteps: ( - threadId: string, - runId: string, - options?: AgentsListRunStepsOptionalParams, - ) => listRunSteps(context, threadId, runId, options), - listFiles: (options?: AgentsListFilesOptionalParams) => - listFiles(context, options), - uploadFile: ( - file: Uint8Array, - purpose: FilePurpose, - options?: AgentsUploadFileOptionalParams, - ) => uploadFile(context, file, purpose, options), - deleteFile: (fileId: string, options?: AgentsDeleteFileOptionalParams) => - deleteFile(context, fileId, options), - getFile: (fileId: string, options?: AgentsGetFileOptionalParams) => - getFile(context, fileId, options), - getFileContent: ( - fileId: string, - options?: AgentsGetFileContentOptionalParams, - ) => getFileContent(context, fileId, options), - listVectorStores: (options?: AgentsListVectorStoresOptionalParams) => - listVectorStores(context, options), - createVectorStore: (options?: AgentsCreateVectorStoreOptionalParams) => - createVectorStore(context, options), - getVectorStore: ( + options?: AgentsGetVectorStoreOptionalParams, + ) => Promise; + /** Creates a vector store. */ + createVectorStore: ( + options?: AgentsCreateVectorStoreOptionalParams, + ) => Promise; + /** Returns a list of vector stores. */ + listVectorStores: ( + options?: AgentsListVectorStoresOptionalParams, + ) => Promise; + /** Returns information about a specific file. Does not retrieve file content. */ + getFileContent: ( + fileId: string, + options?: AgentsGetFileContentOptionalParams, + ) => Promise; + /** Returns information about a specific file. Does not retrieve file content. */ + getFile: ( + fileId: string, + options?: AgentsGetFileOptionalParams, + ) => Promise; + /** Delete a previously uploaded file. */ + deleteFile: ( + fileId: string, + options?: AgentsDeleteFileOptionalParams, + ) => Promise; + /** Uploads a file for use by other operations. */ + uploadFile: ( + file: Uint8Array, + purpose: FilePurpose, + options?: AgentsUploadFileOptionalParams, + ) => Promise; + /** Gets a list of previously uploaded files. */ + listFiles: ( + options?: AgentsListFilesOptionalParams, + ) => Promise; + /** Gets a list of run steps from a thread run. */ + listRunSteps: ( + threadId: string, + runId: string, + options?: AgentsListRunStepsOptionalParams, + ) => Promise; + /** Gets a single run step from a thread run. */ + getRunStep: ( + threadId: string, + runId: string, + stepId: string, + options?: AgentsGetRunStepOptionalParams, + ) => Promise; + /** Creates a new agent thread and immediately starts a run using that new thread. */ + createThreadAndRun: ( + assistantId: string, + options?: AgentsCreateThreadAndRunOptionalParams, + ) => Promise; + /** Cancels a run of an in progress thread. */ + cancelRun: ( + threadId: string, + runId: string, + options?: AgentsCancelRunOptionalParams, + ) => Promise; + /** Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. */ + submitToolOutputsToRun: ( + threadId: string, + runId: string, + toolOutputs: ToolOutput[], + options?: AgentsSubmitToolOutputsToRunOptionalParams, + ) => Promise; + /** Modifies an existing thread run. */ + updateRun: ( + threadId: string, + runId: string, + options?: AgentsUpdateRunOptionalParams, + ) => Promise; + /** Gets an existing run from an existing thread. */ + getRun: ( + threadId: string, + runId: string, + options?: AgentsGetRunOptionalParams, + ) => Promise; + /** Gets a list of runs for a specified thread. */ + listRuns: ( + threadId: string, + options?: AgentsListRunsOptionalParams, + ) => Promise; + /** Creates a new run for an agent thread. */ + createRun: ( + threadId: string, + assistantId: string, + options?: AgentsCreateRunOptionalParams, + ) => Promise; + /** Modifies an existing message on an existing thread. */ + updateMessage: ( + threadId: string, + messageId: string, + options?: AgentsUpdateMessageOptionalParams, + ) => Promise; + /** Gets an existing message from an existing thread. */ + getMessage: ( + threadId: string, + messageId: string, + options?: AgentsGetMessageOptionalParams, + ) => Promise; + /** Gets a list of messages that exist on a thread. */ + listMessages: ( + threadId: string, + options?: AgentsListMessagesOptionalParams, + ) => Promise; + /** Creates a new message on a specified thread. */ + createMessage: ( + threadId: string, + role: MessageRole, + content: string, + options?: AgentsCreateMessageOptionalParams, + ) => Promise; + /** Deletes an existing thread. */ + deleteThread: ( + threadId: string, + options?: AgentsDeleteThreadOptionalParams, + ) => Promise; + /** Modifies an existing thread. */ + updateThread: ( + threadId: string, + options?: AgentsUpdateThreadOptionalParams, + ) => Promise; + /** Gets information about an existing thread. */ + getThread: ( + threadId: string, + options?: AgentsGetThreadOptionalParams, + ) => Promise; + /** Creates a new thread. Threads contain messages and can be run by agents. */ + createThread: ( + options?: AgentsCreateThreadOptionalParams, + ) => Promise; + /** Deletes an agent. */ + deleteAgent: ( + assistantId: string, + options?: AgentsDeleteAgentOptionalParams, + ) => Promise; + /** Modifies an existing agent. */ + updateAgent: ( + assistantId: string, + options?: AgentsUpdateAgentOptionalParams, + ) => Promise; + /** Retrieves an existing agent. */ + getAgent: ( + assistantId: string, + options?: AgentsGetAgentOptionalParams, + ) => Promise; + /** Gets a list of agents that were previously created. */ + listAgents: ( + options?: AgentsListAgentsOptionalParams, + ) => Promise; + /** Creates a new agent. */ + createAgent: ( + model: string, + options?: AgentsCreateAgentOptionalParams, + ) => Promise; +} + +export function getAgents(context: AzureAIContext) { + return { + listVectorStoreFileBatchFiles: ( vectorStoreId: string, - options?: AgentsGetVectorStoreOptionalParams, - ) => getVectorStore(context, vectorStoreId, options), - modifyVectorStore: ( + batchId: string, + options?: AgentsListVectorStoreFileBatchFilesOptionalParams, + ) => + listVectorStoreFileBatchFiles(context, vectorStoreId, batchId, options), + cancelVectorStoreFileBatch: ( vectorStoreId: string, - options?: AgentsModifyVectorStoreOptionalParams, - ) => modifyVectorStore(context, vectorStoreId, options), - deleteVectorStore: ( + batchId: string, + options?: AgentsCancelVectorStoreFileBatchOptionalParams, + ) => cancelVectorStoreFileBatch(context, vectorStoreId, batchId, options), + getVectorStoreFileBatch: ( vectorStoreId: string, - options?: AgentsDeleteVectorStoreOptionalParams, - ) => deleteVectorStore(context, vectorStoreId, options), - listVectorStoreFiles: ( + batchId: string, + options?: AgentsGetVectorStoreFileBatchOptionalParams, + ) => getVectorStoreFileBatch(context, vectorStoreId, batchId, options), + createVectorStoreFileBatch: ( vectorStoreId: string, - options?: AgentsListVectorStoreFilesOptionalParams, - ) => listVectorStoreFiles(context, vectorStoreId, options), - createVectorStoreFile: ( + fileIds: string[], + options?: AgentsCreateVectorStoreFileBatchOptionalParams, + ) => createVectorStoreFileBatch(context, vectorStoreId, fileIds, options), + deleteVectorStoreFile: ( vectorStoreId: string, fileId: string, - options?: AgentsCreateVectorStoreFileOptionalParams, - ) => createVectorStoreFile(context, vectorStoreId, fileId, options), + options?: AgentsDeleteVectorStoreFileOptionalParams, + ) => deleteVectorStoreFile(context, vectorStoreId, fileId, options), getVectorStoreFile: ( vectorStoreId: string, fileId: string, options?: AgentsGetVectorStoreFileOptionalParams, ) => getVectorStoreFile(context, vectorStoreId, fileId, options), - deleteVectorStoreFile: ( + createVectorStoreFile: ( vectorStoreId: string, fileId: string, - options?: AgentsDeleteVectorStoreFileOptionalParams, - ) => deleteVectorStoreFile(context, vectorStoreId, fileId, options), - createVectorStoreFileBatch: ( + options?: AgentsCreateVectorStoreFileOptionalParams, + ) => createVectorStoreFile(context, vectorStoreId, fileId, options), + listVectorStoreFiles: ( vectorStoreId: string, - fileIds: string[], - options?: AgentsCreateVectorStoreFileBatchOptionalParams, - ) => createVectorStoreFileBatch(context, vectorStoreId, fileIds, options), - getVectorStoreFileBatch: ( + options?: AgentsListVectorStoreFilesOptionalParams, + ) => listVectorStoreFiles(context, vectorStoreId, options), + deleteVectorStore: ( vectorStoreId: string, - batchId: string, - options?: AgentsGetVectorStoreFileBatchOptionalParams, - ) => getVectorStoreFileBatch(context, vectorStoreId, batchId, options), - cancelVectorStoreFileBatch: ( + options?: AgentsDeleteVectorStoreOptionalParams, + ) => deleteVectorStore(context, vectorStoreId, options), + modifyVectorStore: ( vectorStoreId: string, - batchId: string, - options?: AgentsCancelVectorStoreFileBatchOptionalParams, - ) => cancelVectorStoreFileBatch(context, vectorStoreId, batchId, options), - listVectorStoreFileBatchFiles: ( + options?: AgentsModifyVectorStoreOptionalParams, + ) => modifyVectorStore(context, vectorStoreId, options), + getVectorStore: ( vectorStoreId: string, - batchId: string, - options?: AgentsListVectorStoreFileBatchFilesOptionalParams, - ) => - listVectorStoreFileBatchFiles(context, vectorStoreId, batchId, options), + options?: AgentsGetVectorStoreOptionalParams, + ) => getVectorStore(context, vectorStoreId, options), + createVectorStore: (options?: AgentsCreateVectorStoreOptionalParams) => + createVectorStore(context, options), + listVectorStores: (options?: AgentsListVectorStoresOptionalParams) => + listVectorStores(context, options), + getFileContent: ( + fileId: string, + options?: AgentsGetFileContentOptionalParams, + ) => getFileContent(context, fileId, options), + getFile: (fileId: string, options?: AgentsGetFileOptionalParams) => + getFile(context, fileId, options), + deleteFile: (fileId: string, options?: AgentsDeleteFileOptionalParams) => + deleteFile(context, fileId, options), + uploadFile: ( + file: Uint8Array, + purpose: FilePurpose, + options?: AgentsUploadFileOptionalParams, + ) => uploadFile(context, file, purpose, options), + listFiles: (options?: AgentsListFilesOptionalParams) => + listFiles(context, options), + listRunSteps: ( + threadId: string, + runId: string, + options?: AgentsListRunStepsOptionalParams, + ) => listRunSteps(context, threadId, runId, options), + getRunStep: ( + threadId: string, + runId: string, + stepId: string, + options?: AgentsGetRunStepOptionalParams, + ) => getRunStep(context, threadId, runId, stepId, options), + createThreadAndRun: ( + assistantId: string, + options?: AgentsCreateThreadAndRunOptionalParams, + ) => createThreadAndRun(context, assistantId, options), + cancelRun: ( + threadId: string, + runId: string, + options?: AgentsCancelRunOptionalParams, + ) => cancelRun(context, threadId, runId, options), + submitToolOutputsToRun: ( + threadId: string, + runId: string, + toolOutputs: ToolOutput[], + options?: AgentsSubmitToolOutputsToRunOptionalParams, + ) => submitToolOutputsToRun(context, threadId, runId, toolOutputs, options), + updateRun: ( + threadId: string, + runId: string, + options?: AgentsUpdateRunOptionalParams, + ) => updateRun(context, threadId, runId, options), + getRun: ( + threadId: string, + runId: string, + options?: AgentsGetRunOptionalParams, + ) => getRun(context, threadId, runId, options), + listRuns: (threadId: string, options?: AgentsListRunsOptionalParams) => + listRuns(context, threadId, options), + createRun: ( + threadId: string, + assistantId: string, + options?: AgentsCreateRunOptionalParams, + ) => createRun(context, threadId, assistantId, options), + updateMessage: ( + threadId: string, + messageId: string, + options?: AgentsUpdateMessageOptionalParams, + ) => updateMessage(context, threadId, messageId, options), + getMessage: ( + threadId: string, + messageId: string, + options?: AgentsGetMessageOptionalParams, + ) => getMessage(context, threadId, messageId, options), + listMessages: ( + threadId: string, + options?: AgentsListMessagesOptionalParams, + ) => listMessages(context, threadId, options), + createMessage: ( + threadId: string, + role: MessageRole, + content: string, + options?: AgentsCreateMessageOptionalParams, + ) => createMessage(context, threadId, role, content, options), + deleteThread: ( + threadId: string, + options?: AgentsDeleteThreadOptionalParams, + ) => deleteThread(context, threadId, options), + updateThread: ( + threadId: string, + options?: AgentsUpdateThreadOptionalParams, + ) => updateThread(context, threadId, options), + getThread: (threadId: string, options?: AgentsGetThreadOptionalParams) => + getThread(context, threadId, options), + createThread: (options?: AgentsCreateThreadOptionalParams) => + createThread(context, options), + deleteAgent: ( + assistantId: string, + options?: AgentsDeleteAgentOptionalParams, + ) => deleteAgent(context, assistantId, options), + updateAgent: ( + assistantId: string, + options?: AgentsUpdateAgentOptionalParams, + ) => updateAgent(context, assistantId, options), + getAgent: (assistantId: string, options?: AgentsGetAgentOptionalParams) => + getAgent(context, assistantId, options), + listAgents: (options?: AgentsListAgentsOptionalParams) => + listAgents(context, options), + createAgent: (model: string, options?: AgentsCreateAgentOptionalParams) => + createAgent(context, model, options), }; } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/connections/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/connections/index.ts index fd33f216f9..75ceca3621 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/connections/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/connections/index.ts @@ -2,11 +2,11 @@ // Licensed under the MIT License. import { AzureAIContext } from "../../api/azureAIContext.js"; -import { list, get, listSecrets } from "../../api/connections/index.js"; +import { listSecrets, get, list } from "../../api/connections/index.js"; import { - ConnectionsListOptionalParams, - ConnectionsGetOptionalParams, ConnectionsListSecretsOptionalParams, + ConnectionsGetOptionalParams, + ConnectionsListOptionalParams, } from "../../api/options.js"; import { ConnectionsListResponse, @@ -15,33 +15,33 @@ import { /** Interface representing a Connections operations. */ export interface ConnectionsOperations { - /** List the details of all the connections (not including their credentials) */ - list: ( - options?: ConnectionsListOptionalParams, - ) => Promise; - /** Get the details of a single connection, without credentials. */ - get: ( - connectionName: string, - options?: ConnectionsGetOptionalParams, - ) => Promise; /** Get the details of a single connection, including credentials (if available). */ listSecrets: ( connectionName: string, ignored: string, options?: ConnectionsListSecretsOptionalParams, ) => Promise; + /** Get the details of a single connection, without credentials. */ + get: ( + connectionName: string, + options?: ConnectionsGetOptionalParams, + ) => Promise; + /** List the details of all the connections (not including their credentials) */ + list: ( + options?: ConnectionsListOptionalParams, + ) => Promise; } export function getConnections(context: AzureAIContext) { return { - list: (options?: ConnectionsListOptionalParams) => list(context, options), - get: (connectionName: string, options?: ConnectionsGetOptionalParams) => - get(context, connectionName, options), listSecrets: ( connectionName: string, ignored: string, options?: ConnectionsListSecretsOptionalParams, ) => listSecrets(context, connectionName, ignored, options), + get: (connectionName: string, options?: ConnectionsGetOptionalParams) => + get(context, connectionName, options), + list: (options?: ConnectionsListOptionalParams) => list(context, options), }; } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/evaluations/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/evaluations/index.ts index 5022e9e570..def0c46ecd 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/evaluations/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/classic/evaluations/index.ts @@ -3,99 +3,99 @@ import { AzureAIContext } from "../../api/azureAIContext.js"; import { - get, - create, - list, - update, - getSchedule, - createOrReplaceSchedule, - listSchedule, deleteSchedule, + listSchedule, + createOrReplaceSchedule, + getSchedule, + update, + list, + create, + get, } from "../../api/evaluations/index.js"; import { - EvaluationsGetOptionalParams, - EvaluationsCreateOptionalParams, - EvaluationsListOptionalParams, - EvaluationsUpdateOptionalParams, - EvaluationsGetScheduleOptionalParams, - EvaluationsCreateOrReplaceScheduleOptionalParams, - EvaluationsListScheduleOptionalParams, EvaluationsDeleteScheduleOptionalParams, + EvaluationsListScheduleOptionalParams, + EvaluationsCreateOrReplaceScheduleOptionalParams, + EvaluationsGetScheduleOptionalParams, + EvaluationsUpdateOptionalParams, + EvaluationsListOptionalParams, + EvaluationsCreateOptionalParams, + EvaluationsGetOptionalParams, } from "../../api/options.js"; import { Evaluation, EvaluationSchedule } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; /** Interface representing a Evaluations operations. */ export interface EvaluationsOperations { - /** Resource read operation template. */ - get: ( + /** Resource delete operation template. */ + deleteSchedule: ( id: string, - options?: EvaluationsGetOptionalParams, - ) => Promise; - /** Run the evaluation. */ - create: ( - evaluation: Evaluation, - options?: EvaluationsCreateOptionalParams, - ) => Promise; + options?: EvaluationsDeleteScheduleOptionalParams, + ) => Promise; /** Resource list operation template. */ - list: ( - options?: EvaluationsListOptionalParams, - ) => PagedAsyncIterableIterator; - /** Resource update operation template. */ - update: ( + listSchedule: ( + options?: EvaluationsListScheduleOptionalParams, + ) => PagedAsyncIterableIterator; + /** Create or replace operation template. */ + createOrReplaceSchedule: ( id: string, - resource: Evaluation, - options?: EvaluationsUpdateOptionalParams, - ) => Promise; + resource: EvaluationSchedule, + options?: EvaluationsCreateOrReplaceScheduleOptionalParams, + ) => Promise; /** Resource read operation template. */ getSchedule: ( id: string, options?: EvaluationsGetScheduleOptionalParams, ) => Promise; - /** Create or replace operation template. */ - createOrReplaceSchedule: ( + /** Resource update operation template. */ + update: ( id: string, - resource: EvaluationSchedule, - options?: EvaluationsCreateOrReplaceScheduleOptionalParams, - ) => Promise; + resource: Evaluation, + options?: EvaluationsUpdateOptionalParams, + ) => Promise; /** Resource list operation template. */ - listSchedule: ( - options?: EvaluationsListScheduleOptionalParams, - ) => PagedAsyncIterableIterator; - /** Resource delete operation template. */ - deleteSchedule: ( + list: ( + options?: EvaluationsListOptionalParams, + ) => PagedAsyncIterableIterator; + /** Run the evaluation. */ + create: ( + evaluation: Evaluation, + options?: EvaluationsCreateOptionalParams, + ) => Promise; + /** Resource read operation template. */ + get: ( id: string, - options?: EvaluationsDeleteScheduleOptionalParams, - ) => Promise; + options?: EvaluationsGetOptionalParams, + ) => Promise; } export function getEvaluations(context: AzureAIContext) { return { - get: (id: string, options?: EvaluationsGetOptionalParams) => - get(context, id, options), - create: ( - evaluation: Evaluation, - options?: EvaluationsCreateOptionalParams, - ) => create(context, evaluation, options), - list: (options?: EvaluationsListOptionalParams) => list(context, options), - update: ( + deleteSchedule: ( id: string, - resource: Evaluation, - options?: EvaluationsUpdateOptionalParams, - ) => update(context, id, resource, options), - getSchedule: (id: string, options?: EvaluationsGetScheduleOptionalParams) => - getSchedule(context, id, options), + options?: EvaluationsDeleteScheduleOptionalParams, + ) => deleteSchedule(context, id, options), + listSchedule: (options?: EvaluationsListScheduleOptionalParams) => + listSchedule(context, options), createOrReplaceSchedule: ( id: string, resource: EvaluationSchedule, options?: EvaluationsCreateOrReplaceScheduleOptionalParams, ) => createOrReplaceSchedule(context, id, resource, options), - listSchedule: (options?: EvaluationsListScheduleOptionalParams) => - listSchedule(context, options), - deleteSchedule: ( + getSchedule: (id: string, options?: EvaluationsGetScheduleOptionalParams) => + getSchedule(context, id, options), + update: ( id: string, - options?: EvaluationsDeleteScheduleOptionalParams, - ) => deleteSchedule(context, id, options), + resource: Evaluation, + options?: EvaluationsUpdateOptionalParams, + ) => update(context, id, resource, options), + list: (options?: EvaluationsListOptionalParams) => list(context, options), + create: ( + evaluation: Evaluation, + options?: EvaluationsCreateOptionalParams, + ) => create(context, evaluation, options), + get: (id: string, options?: EvaluationsGetOptionalParams) => + get(context, id, options), }; } diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/index.ts index 670a629133..7873ee29db 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/index.ts @@ -216,57 +216,57 @@ export { } from "./models/index.js"; export { AzureAIClientOptionalParams, - AgentsCreateAgentOptionalParams, - AgentsListAgentsOptionalParams, - AgentsGetAgentOptionalParams, - AgentsUpdateAgentOptionalParams, - AgentsDeleteAgentOptionalParams, - AgentsCreateThreadOptionalParams, - AgentsGetThreadOptionalParams, - AgentsUpdateThreadOptionalParams, - AgentsDeleteThreadOptionalParams, - AgentsCreateMessageOptionalParams, - AgentsListMessagesOptionalParams, - AgentsGetMessageOptionalParams, - AgentsUpdateMessageOptionalParams, - AgentsCreateRunOptionalParams, - AgentsListRunsOptionalParams, - AgentsGetRunOptionalParams, - AgentsUpdateRunOptionalParams, - AgentsSubmitToolOutputsToRunOptionalParams, - AgentsCancelRunOptionalParams, - AgentsCreateThreadAndRunOptionalParams, - AgentsGetRunStepOptionalParams, - AgentsListRunStepsOptionalParams, - AgentsListFilesOptionalParams, - AgentsUploadFileOptionalParams, - AgentsDeleteFileOptionalParams, - AgentsGetFileOptionalParams, - AgentsGetFileContentOptionalParams, - AgentsListVectorStoresOptionalParams, - AgentsCreateVectorStoreOptionalParams, - AgentsGetVectorStoreOptionalParams, - AgentsModifyVectorStoreOptionalParams, - AgentsDeleteVectorStoreOptionalParams, - AgentsListVectorStoreFilesOptionalParams, - AgentsCreateVectorStoreFileOptionalParams, - AgentsGetVectorStoreFileOptionalParams, - AgentsDeleteVectorStoreFileOptionalParams, - AgentsCreateVectorStoreFileBatchOptionalParams, - AgentsGetVectorStoreFileBatchOptionalParams, - AgentsCancelVectorStoreFileBatchOptionalParams, - AgentsListVectorStoreFileBatchFilesOptionalParams, - ConnectionsListOptionalParams, - ConnectionsGetOptionalParams, - ConnectionsListSecretsOptionalParams, - EvaluationsGetOptionalParams, - EvaluationsCreateOptionalParams, - EvaluationsListOptionalParams, - EvaluationsUpdateOptionalParams, - EvaluationsGetScheduleOptionalParams, - EvaluationsCreateOrReplaceScheduleOptionalParams, - EvaluationsListScheduleOptionalParams, EvaluationsDeleteScheduleOptionalParams, + EvaluationsListScheduleOptionalParams, + EvaluationsCreateOrReplaceScheduleOptionalParams, + EvaluationsGetScheduleOptionalParams, + EvaluationsUpdateOptionalParams, + EvaluationsListOptionalParams, + EvaluationsCreateOptionalParams, + EvaluationsGetOptionalParams, + ConnectionsListSecretsOptionalParams, + ConnectionsGetOptionalParams, + ConnectionsListOptionalParams, + AgentsListVectorStoreFileBatchFilesOptionalParams, + AgentsCancelVectorStoreFileBatchOptionalParams, + AgentsGetVectorStoreFileBatchOptionalParams, + AgentsCreateVectorStoreFileBatchOptionalParams, + AgentsDeleteVectorStoreFileOptionalParams, + AgentsGetVectorStoreFileOptionalParams, + AgentsCreateVectorStoreFileOptionalParams, + AgentsListVectorStoreFilesOptionalParams, + AgentsDeleteVectorStoreOptionalParams, + AgentsModifyVectorStoreOptionalParams, + AgentsGetVectorStoreOptionalParams, + AgentsCreateVectorStoreOptionalParams, + AgentsListVectorStoresOptionalParams, + AgentsGetFileContentOptionalParams, + AgentsGetFileOptionalParams, + AgentsDeleteFileOptionalParams, + AgentsUploadFileOptionalParams, + AgentsListFilesOptionalParams, + AgentsListRunStepsOptionalParams, + AgentsGetRunStepOptionalParams, + AgentsCreateThreadAndRunOptionalParams, + AgentsCancelRunOptionalParams, + AgentsSubmitToolOutputsToRunOptionalParams, + AgentsUpdateRunOptionalParams, + AgentsGetRunOptionalParams, + AgentsListRunsOptionalParams, + AgentsCreateRunOptionalParams, + AgentsUpdateMessageOptionalParams, + AgentsGetMessageOptionalParams, + AgentsListMessagesOptionalParams, + AgentsCreateMessageOptionalParams, + AgentsDeleteThreadOptionalParams, + AgentsUpdateThreadOptionalParams, + AgentsGetThreadOptionalParams, + AgentsCreateThreadOptionalParams, + AgentsDeleteAgentOptionalParams, + AgentsUpdateAgentOptionalParams, + AgentsGetAgentOptionalParams, + AgentsListAgentsOptionalParams, + AgentsCreateAgentOptionalParams, } from "./api/index.js"; export { AgentsOperations, diff --git a/packages/typespec-test/test/ai/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/ai/generated/typespec-ts/src/models/models.ts index 8a0a293009..3e63658359 100644 --- a/packages/typespec-test/test/ai/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/ai/generated/typespec-ts/src/models/models.ts @@ -1395,12 +1395,14 @@ export function agentDeserializer(item: any): Agent { model: item["model"], instructions: item["instructions"], tools: toolDefinitionUnionArrayDeserializer(item["tools"]), - toolResources: item["tool_resources"], + toolResources: !item["tool_resources"] + ? item["tool_resources"] + : toolResourcesDeserializer(item["tool_resources"]), temperature: item["temperature"], topP: item["top_p"], responseFormat: !item["response_format"] ? item["response_format"] - : (item["response_format"] as any), + : agentsApiResponseFormatOptionDeserializer(item["response_format"]), metadata: item["metadata"], }; } @@ -1485,9 +1487,7 @@ export function threadMessageOptionsSerializer( content: item["content"], attachments: !item["attachments"] ? item["attachments"] - : item["attachments"].map((p: any) => { - return messageAttachmentSerializer(p); - }), + : messageAttachmentArraySerializer(item["attachments"]), metadata: item["metadata"], }; } @@ -1614,7 +1614,9 @@ export function agentThreadDeserializer(item: any): AgentThread { id: item["id"], object: item["object"], createdAt: new Date(item["created_at"] * 1000), - toolResources: item["tool_resources"], + toolResources: !item["tool_resources"] + ? item["tool_resources"] + : toolResourcesDeserializer(item["tool_resources"]), metadata: item["metadata"], }; } @@ -1678,7 +1680,9 @@ export function threadMessageSerializer(item: ThreadMessage): any { created_at: (item["createdAt"].getTime() / 1000) | 0, thread_id: item["threadId"], status: item["status"], - incomplete_details: item["incompleteDetails"], + incomplete_details: !item["incompleteDetails"] + ? item["incompleteDetails"] + : messageIncompleteDetailsSerializer(item["incompleteDetails"]), completed_at: !item["completedAt"] ? item["completedAt"] : (item["completedAt"].getTime() / 1000) | 0, @@ -1691,9 +1695,7 @@ export function threadMessageSerializer(item: ThreadMessage): any { run_id: item["runId"], attachments: !item["attachments"] ? item["attachments"] - : item["attachments"].map((p: any) => { - return messageAttachmentSerializer(p); - }), + : messageAttachmentArraySerializer(item["attachments"]), metadata: item["metadata"], }; } @@ -1705,28 +1707,22 @@ export function threadMessageDeserializer(item: any): ThreadMessage { createdAt: new Date(item["created_at"] * 1000), threadId: item["thread_id"], status: item["status"], - incompleteDetails: item["incomplete_details"], + incompleteDetails: !item["incomplete_details"] + ? item["incomplete_details"] + : messageIncompleteDetailsDeserializer(item["incomplete_details"]), completedAt: !item["completed_at"] ? item["completed_at"] - : !item["completed_at"] - ? item["completed_at"] - : new Date(item["completed_at"] * 1000), + : new Date(item["completed_at"] * 1000), incompleteAt: !item["incomplete_at"] ? item["incomplete_at"] - : !item["incomplete_at"] - ? item["incomplete_at"] - : new Date(item["incomplete_at"] * 1000), + : new Date(item["incomplete_at"] * 1000), role: item["role"], content: messageContentUnionArrayDeserializer(item["content"]), assistantId: item["assistant_id"], runId: item["run_id"], attachments: !item["attachments"] ? item["attachments"] - : !item["attachments"] - ? item["attachments"] - : item["attachments"].map((p: any) => { - return messageAttachmentDeserializer(p); - }), + : messageAttachmentArrayDeserializer(item["attachments"]), metadata: item["metadata"], }; } @@ -2345,52 +2341,52 @@ export function threadRunDeserializer(item: any): ThreadRun { threadId: item["thread_id"], assistantId: item["assistant_id"], status: item["status"], - requiredAction: item["required_action"], - lastError: item["last_error"], + requiredAction: !item["required_action"] + ? item["required_action"] + : requiredActionUnionDeserializer(item["required_action"]), + lastError: !item["last_error"] + ? item["last_error"] + : runErrorDeserializer(item["last_error"]), model: item["model"], instructions: item["instructions"], tools: toolDefinitionUnionArrayDeserializer(item["tools"]), createdAt: new Date(item["created_at"] * 1000), expiresAt: !item["expires_at"] ? item["expires_at"] - : !item["expires_at"] - ? item["expires_at"] - : new Date(item["expires_at"] * 1000), + : new Date(item["expires_at"] * 1000), startedAt: !item["started_at"] ? item["started_at"] - : !item["started_at"] - ? item["started_at"] - : new Date(item["started_at"] * 1000), + : new Date(item["started_at"] * 1000), completedAt: !item["completed_at"] ? item["completed_at"] - : !item["completed_at"] - ? item["completed_at"] - : new Date(item["completed_at"] * 1000), + : new Date(item["completed_at"] * 1000), cancelledAt: !item["cancelled_at"] ? item["cancelled_at"] - : !item["cancelled_at"] - ? item["cancelled_at"] - : new Date(item["cancelled_at"] * 1000), + : new Date(item["cancelled_at"] * 1000), failedAt: !item["failed_at"] ? item["failed_at"] - : !item["failed_at"] - ? item["failed_at"] - : new Date(item["failed_at"] * 1000), + : new Date(item["failed_at"] * 1000), incompleteDetails: item["incomplete_details"], - usage: item["usage"], + usage: !item["usage"] + ? item["usage"] + : runCompletionUsageDeserializer(item["usage"]), temperature: item["temperature"], topP: item["top_p"], maxPromptTokens: item["max_prompt_tokens"], maxCompletionTokens: item["max_completion_tokens"], - truncationStrategy: item["truncation_strategy"], + truncationStrategy: !item["truncation_strategy"] + ? item["truncation_strategy"] + : truncationObjectDeserializer(item["truncation_strategy"]), toolChoice: !item["tool_choice"] ? item["tool_choice"] - : (item["tool_choice"] as any), + : agentsApiToolChoiceOptionDeserializer(item["tool_choice"]), responseFormat: !item["response_format"] ? item["response_format"] - : (item["response_format"] as any), + : agentsApiResponseFormatOptionDeserializer(item["response_format"]), metadata: item["metadata"], - toolResources: item["tool_resources"], + toolResources: !item["tool_resources"] + ? item["tool_resources"] + : updateToolResourcesOptionsDeserializer(item["tool_resources"]), parallelToolCalls: item["parallelToolCalls"], }; } @@ -2791,7 +2787,9 @@ export function agentThreadCreationOptionsSerializer( messages: !item["messages"] ? item["messages"] : threadMessageOptionsArraySerializer(item["messages"]), - tool_resources: item["toolResources"], + tool_resources: !item["toolResources"] + ? item["toolResources"] + : toolResourcesSerializer(item["toolResources"]), metadata: item["metadata"], }; } @@ -2842,29 +2840,25 @@ export function runStepDeserializer(item: any): RunStep { runId: item["run_id"], status: item["status"], stepDetails: runStepDetailsUnionDeserializer(item["step_details"]), - lastError: item["last_error"], + lastError: !item["last_error"] + ? item["last_error"] + : runStepErrorDeserializer(item["last_error"]), createdAt: new Date(item["created_at"] * 1000), expiredAt: !item["expired_at"] ? item["expired_at"] - : !item["expired_at"] - ? item["expired_at"] - : new Date(item["expired_at"] * 1000), + : new Date(item["expired_at"] * 1000), completedAt: !item["completed_at"] ? item["completed_at"] - : !item["completed_at"] - ? item["completed_at"] - : new Date(item["completed_at"] * 1000), + : new Date(item["completed_at"] * 1000), cancelledAt: !item["cancelled_at"] ? item["cancelled_at"] - : !item["cancelled_at"] - ? item["cancelled_at"] - : new Date(item["cancelled_at"] * 1000), + : new Date(item["cancelled_at"] * 1000), failedAt: !item["failed_at"] ? item["failed_at"] - : !item["failed_at"] - ? item["failed_at"] - : new Date(item["failed_at"] * 1000), - usage: item["usage"], + : new Date(item["failed_at"] * 1000), + usage: !item["usage"] + ? item["usage"] + : runStepCompletionUsageDeserializer(item["usage"]), metadata: item["metadata"], }; } @@ -3582,14 +3576,10 @@ export function vectorStoreDeserializer(item: any): VectorStore { : vectorStoreExpirationPolicyDeserializer(item["expires_after"]), expiresAt: !item["expires_at"] ? item["expires_at"] - : !item["expires_at"] - ? item["expires_at"] - : new Date(item["expires_at"] * 1000), + : new Date(item["expires_at"] * 1000), lastActiveAt: !item["last_active_at"] ? item["last_active_at"] - : !item["last_active_at"] - ? item["last_active_at"] - : new Date(item["last_active_at"] * 1000), + : new Date(item["last_active_at"] * 1000), metadata: item["metadata"], }; } @@ -3835,7 +3825,9 @@ export function vectorStoreFileDeserializer(item: any): VectorStoreFile { createdAt: new Date(item["created_at"] * 1000), vectorStoreId: item["vector_store_id"], status: item["status"], - lastError: item["last_error"], + lastError: !item["last_error"] + ? item["last_error"] + : vectorStoreFileErrorDeserializer(item["last_error"]), chunkingStrategy: vectorStoreChunkingStrategyResponseUnionDeserializer( item["chunking_strategy"], ), diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json index a8ae41ceeb..93b4b445e6 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/package.json @@ -13,8 +13,8 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/univariate": "./src/api/univariate/index.ts", - "./api/multivariate": "./src/api/multivariate/index.ts" + "./api/multivariate": "./src/api/multivariate/index.ts", + "./api/univariate": "./src/api/univariate/index.ts" }, "dialects": [ "esm", @@ -142,24 +142,6 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/univariate": { - "browser": { - "types": "./dist/browser/api/univariate/index.d.ts", - "default": "./dist/browser/api/univariate/index.js" - }, - "react-native": { - "types": "./dist/react-native/api/univariate/index.d.ts", - "default": "./dist/react-native/api/univariate/index.js" - }, - "import": { - "types": "./dist/esm/api/univariate/index.d.ts", - "default": "./dist/esm/api/univariate/index.js" - }, - "require": { - "types": "./dist/commonjs/api/univariate/index.d.ts", - "default": "./dist/commonjs/api/univariate/index.js" - } - }, "./api/multivariate": { "browser": { "types": "./dist/browser/api/multivariate/index.d.ts", @@ -177,6 +159,24 @@ "types": "./dist/commonjs/api/multivariate/index.d.ts", "default": "./dist/commonjs/api/multivariate/index.js" } + }, + "./api/univariate": { + "browser": { + "types": "./dist/browser/api/univariate/index.d.ts", + "default": "./dist/browser/api/univariate/index.js" + }, + "react-native": { + "types": "./dist/react-native/api/univariate/index.d.ts", + "default": "./dist/react-native/api/univariate/index.js" + }, + "import": { + "types": "./dist/esm/api/univariate/index.d.ts", + "default": "./dist/esm/api/univariate/index.js" + }, + "require": { + "types": "./dist/commonjs/api/univariate/index.d.ts", + "default": "./dist/commonjs/api/univariate/index.js" + } } }, "main": "./dist/commonjs/index.js", diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts index 9796b46486..ae8edb2927 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/anomalyDetectorClient.ts @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { - getUnivariateOperations, - UnivariateOperations, -} from "./classic/univariate/index.js"; import { getMultivariateOperations, MultivariateOperations, } from "./classic/multivariate/index.js"; +import { + getUnivariateOperations, + UnivariateOperations, +} from "./classic/univariate/index.js"; import { createAnomalyDetector, AnomalyDetectorContext, @@ -56,12 +56,12 @@ export class AnomalyDetectorClient { userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; - this.univariate = getUnivariateOperations(this._client); this.multivariate = getMultivariateOperations(this._client); + this.univariate = getUnivariateOperations(this._client); } - /** The operation groups for Univariate */ - public readonly univariate: UnivariateOperations; - /** The operation groups for Multivariate */ + /** The operation groups for multivariate */ public readonly multivariate: MultivariateOperations; + /** The operation groups for univariate */ + public readonly univariate: UnivariateOperations; } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts index 6ee0ba4e67..88bd23e8a1 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/anomalyDetectorContext.ts @@ -24,7 +24,11 @@ import { KeyCredential } from "@azure/core-auth"; * a set of time series. By using anomaly detector service, business customers can * discover incidents and establish a logic flow for root cause analysis. */ -export interface AnomalyDetectorContext extends Client {} +export interface AnomalyDetectorContext extends Client { + /** Api Version */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface AnomalyDetectorClientOptionalParams extends ClientOptions { @@ -77,5 +81,5 @@ export function createAnomalyDetector( }; const clientContext = getClient(endpointUrl, credential, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - return clientContext; + return { ...clientContext, apiVersion } as AnomalyDetectorContext; } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts index 113a94ebf7..9161609ded 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/index.ts @@ -7,14 +7,14 @@ export { AnomalyDetectorClientOptionalParams, } from "./anomalyDetectorContext.js"; export { - UnivariateDetectUnivariateEntireSeriesOptionalParams, - UnivariateDetectUnivariateLastPointOptionalParams, - UnivariateDetectUnivariateChangePointOptionalParams, - MultivariateGetMultivariateBatchDetectionResultOptionalParams, - MultivariateTrainMultivariateModelOptionalParams, - MultivariateListMultivariateModelsOptionalParams, - MultivariateDeleteMultivariateModelOptionalParams, - MultivariateGetMultivariateModelOptionalParams, - MultivariateDetectMultivariateBatchAnomalyOptionalParams, MultivariateDetectMultivariateLastAnomalyOptionalParams, + MultivariateDetectMultivariateBatchAnomalyOptionalParams, + MultivariateGetMultivariateModelOptionalParams, + MultivariateDeleteMultivariateModelOptionalParams, + MultivariateListMultivariateModelsOptionalParams, + MultivariateTrainMultivariateModelOptionalParams, + MultivariateGetMultivariateBatchDetectionResultOptionalParams, + UnivariateDetectUnivariateChangePointOptionalParams, + UnivariateDetectUnivariateLastPointOptionalParams, + UnivariateDetectUnivariateEntireSeriesOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts index 8ee761c9ca..f513ba5159 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/multivariate/index.ts @@ -38,133 +38,160 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _getMultivariateBatchDetectionResultSend( +export function _detectMultivariateLastAnomalySend( context: Client, - resultId: string, - options: MultivariateGetMultivariateBatchDetectionResultOptionalParams = { + modelId: string, + options: MultivariateMultivariateLastDetectionOptions, + optionalParams: MultivariateDetectMultivariateLastAnomalyOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/multivariate/detect-batch/{resultId}", resultId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/multivariate/models/{modelId}:detect-last", modelId) + .post({ + ...operationOptionsToRequestParameters(optionalParams), + contentType: "application/json", + headers: { + accept: "application/json", + ...optionalParams.requestOptions?.headers, + }, + body: multivariateMultivariateLastDetectionOptionsSerializer(options), + }); } -export async function _getMultivariateBatchDetectionResultDeserialize( +export async function _detectMultivariateLastAnomalyDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return multivariateMultivariateDetectionResultDeserializer(result.body); + return multivariateMultivariateLastDetectionResultDeserializer(result.body); } /** - * For asynchronous inference, get multivariate anomaly detection result based on - * resultId returned by the BatchDetectAnomaly api. + * Submit multivariate anomaly detection task with the modelId of trained model + * and inference data, and the inference data should be put into request body in a + * JSON format. The request will complete synchronously and return the detection + * immediately in the response body. */ -export async function getMultivariateBatchDetectionResult( +export async function detectMultivariateLastAnomaly( context: Client, - resultId: string, - options: MultivariateGetMultivariateBatchDetectionResultOptionalParams = { + modelId: string, + options: MultivariateMultivariateLastDetectionOptions, + optionalParams: MultivariateDetectMultivariateLastAnomalyOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _getMultivariateBatchDetectionResultSend( +): Promise { + const result = await _detectMultivariateLastAnomalySend( context, - resultId, + modelId, options, + optionalParams, ); - return _getMultivariateBatchDetectionResultDeserialize(result); + return _detectMultivariateLastAnomalyDeserialize(result); } -export function _trainMultivariateModelSend( +export function _detectMultivariateBatchAnomalySend( context: Client, - modelInfo: MultivariateModelInfo, - options: MultivariateTrainMultivariateModelOptionalParams = { + modelId: string, + options: MultivariateMultivariateBatchDetectionOptions, + optionalParams: MultivariateDetectMultivariateBatchAnomalyOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/multivariate/models") + .path("/multivariate/models/{modelId}:detect-batch", modelId) .post({ - ...operationOptionsToRequestParameters(options), - body: multivariateModelInfoSerializer(modelInfo), + ...operationOptionsToRequestParameters(optionalParams), + contentType: "application/json", + headers: { + accept: "application/json", + ...optionalParams.requestOptions?.headers, + }, + body: multivariateMultivariateBatchDetectionOptionsSerializer(options), }); } -export async function _trainMultivariateModelDeserialize( +export async function _detectMultivariateBatchAnomalyDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201"]; +): Promise { + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return multivariateAnomalyDetectionModelDeserializer(result.body); + return multivariateMultivariateDetectionResultDeserializer(result.body); } /** - * Create and train a multivariate anomaly detection model. The request must - * include a source parameter to indicate an externally accessible Azure blob - * storage URI.There are two types of data input: An URI pointed to an Azure blob - * storage folder which contains multiple CSV files, and each CSV file contains - * two columns, timestamp and variable. Another type of input is an URI pointed to - * a CSV file in Azure blob storage, which contains all the variables and a - * timestamp column. + * Submit multivariate anomaly detection task with the modelId of trained model + * and inference data, the input schema should be the same with the training + * request. The request will complete asynchronously and return a resultId to + * query the detection result.The request should be a source link to indicate an + * externally accessible Azure storage Uri, either pointed to an Azure blob + * storage folder, or pointed to a CSV file in Azure blob storage. */ -export async function trainMultivariateModel( +export async function detectMultivariateBatchAnomaly( context: Client, - modelInfo: MultivariateModelInfo, - options: MultivariateTrainMultivariateModelOptionalParams = { + modelId: string, + options: MultivariateMultivariateBatchDetectionOptions, + optionalParams: MultivariateDetectMultivariateBatchAnomalyOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _trainMultivariateModelSend(context, modelInfo, options); - return _trainMultivariateModelDeserialize(result); +): Promise { + const result = await _detectMultivariateBatchAnomalySend( + context, + modelId, + options, + optionalParams, + ); + return _detectMultivariateBatchAnomalyDeserialize(result); } -export function _listMultivariateModelsSend( +export function _getMultivariateModelSend( context: Client, - options: MultivariateListMultivariateModelsOptionalParams = { + modelId: string, + options: MultivariateGetMultivariateModelOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/multivariate/models") + .path("/multivariate/models/{modelId}", modelId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { skip: options?.skip, top: options?.top }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _listMultivariateModelsDeserialize( +export async function _getMultivariateModelDeserialize( result: PathUncheckedResponse, -): Promise<_MultivariateModelList> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _multivariateModelListDeserializer(result.body); + return multivariateAnomalyDetectionModelDeserializer(result.body); } -/** List models of a resource. */ -export function listMultivariateModels( +/** + * Get detailed information of multivariate model, including the training status + * and variables used in the model. + */ +export async function getMultivariateModel( context: Client, - options: MultivariateListMultivariateModelsOptionalParams = { + modelId: string, + options: MultivariateGetMultivariateModelOptionalParams = { requestOptions: {}, }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listMultivariateModelsSend(context, options), - _listMultivariateModelsDeserialize, - ["200"], - { itemName: "models", nextLinkName: "nextLink" }, - ); +): Promise { + const result = await _getMultivariateModelSend(context, modelId, options); + return _getMultivariateModelDeserialize(result); } export function _deleteMultivariateModelSend( @@ -176,7 +203,13 @@ export function _deleteMultivariateModelSend( ): StreamableMethod { return context .path("/multivariate/models/{modelId}", modelId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _deleteMultivariateModelDeserialize( @@ -202,142 +235,146 @@ export async function deleteMultivariateModel( return _deleteMultivariateModelDeserialize(result); } -export function _getMultivariateModelSend( +export function _listMultivariateModelsSend( context: Client, - modelId: string, - options: MultivariateGetMultivariateModelOptionalParams = { + options: MultivariateListMultivariateModelsOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/multivariate/models/{modelId}", modelId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/multivariate/models") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { skip: options?.skip, top: options?.top }, + }); } -export async function _getMultivariateModelDeserialize( +export async function _listMultivariateModelsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_MultivariateModelList> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return multivariateAnomalyDetectionModelDeserializer(result.body); + return _multivariateModelListDeserializer(result.body); } -/** - * Get detailed information of multivariate model, including the training status - * and variables used in the model. - */ -export async function getMultivariateModel( +/** List models of a resource. */ +export function listMultivariateModels( context: Client, - modelId: string, - options: MultivariateGetMultivariateModelOptionalParams = { + options: MultivariateListMultivariateModelsOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _getMultivariateModelSend(context, modelId, options); - return _getMultivariateModelDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listMultivariateModelsSend(context, options), + _listMultivariateModelsDeserialize, + ["200"], + { itemName: "models", nextLinkName: "nextLink" }, + ); } -export function _detectMultivariateBatchAnomalySend( +export function _trainMultivariateModelSend( context: Client, - modelId: string, - options: MultivariateMultivariateBatchDetectionOptions, - optionalParams: MultivariateDetectMultivariateBatchAnomalyOptionalParams = { + modelInfo: MultivariateModelInfo, + options: MultivariateTrainMultivariateModelOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/multivariate/models/{modelId}:detect-batch", modelId) + .path("/multivariate/models") .post({ - ...operationOptionsToRequestParameters(optionalParams), - body: multivariateMultivariateBatchDetectionOptionsSerializer(options), + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: multivariateModelInfoSerializer(modelInfo), }); } -export async function _detectMultivariateBatchAnomalyDeserialize( +export async function _trainMultivariateModelDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["202"]; +): Promise { + const expectedStatuses = ["201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return multivariateMultivariateDetectionResultDeserializer(result.body); + return multivariateAnomalyDetectionModelDeserializer(result.body); } /** - * Submit multivariate anomaly detection task with the modelId of trained model - * and inference data, the input schema should be the same with the training - * request. The request will complete asynchronously and return a resultId to - * query the detection result.The request should be a source link to indicate an - * externally accessible Azure storage Uri, either pointed to an Azure blob - * storage folder, or pointed to a CSV file in Azure blob storage. + * Create and train a multivariate anomaly detection model. The request must + * include a source parameter to indicate an externally accessible Azure blob + * storage URI.There are two types of data input: An URI pointed to an Azure blob + * storage folder which contains multiple CSV files, and each CSV file contains + * two columns, timestamp and variable. Another type of input is an URI pointed to + * a CSV file in Azure blob storage, which contains all the variables and a + * timestamp column. */ -export async function detectMultivariateBatchAnomaly( +export async function trainMultivariateModel( context: Client, - modelId: string, - options: MultivariateMultivariateBatchDetectionOptions, - optionalParams: MultivariateDetectMultivariateBatchAnomalyOptionalParams = { + modelInfo: MultivariateModelInfo, + options: MultivariateTrainMultivariateModelOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _detectMultivariateBatchAnomalySend( - context, - modelId, - options, - optionalParams, - ); - return _detectMultivariateBatchAnomalyDeserialize(result); +): Promise { + const result = await _trainMultivariateModelSend(context, modelInfo, options); + return _trainMultivariateModelDeserialize(result); } -export function _detectMultivariateLastAnomalySend( +export function _getMultivariateBatchDetectionResultSend( context: Client, - modelId: string, - options: MultivariateMultivariateLastDetectionOptions, - optionalParams: MultivariateDetectMultivariateLastAnomalyOptionalParams = { + resultId: string, + options: MultivariateGetMultivariateBatchDetectionResultOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/multivariate/models/{modelId}:detect-last", modelId) - .post({ - ...operationOptionsToRequestParameters(optionalParams), - body: multivariateMultivariateLastDetectionOptionsSerializer(options), + .path("/multivariate/detect-batch/{resultId}", resultId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _detectMultivariateLastAnomalyDeserialize( +export async function _getMultivariateBatchDetectionResultDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return multivariateMultivariateLastDetectionResultDeserializer(result.body); + return multivariateMultivariateDetectionResultDeserializer(result.body); } /** - * Submit multivariate anomaly detection task with the modelId of trained model - * and inference data, and the inference data should be put into request body in a - * JSON format. The request will complete synchronously and return the detection - * immediately in the response body. + * For asynchronous inference, get multivariate anomaly detection result based on + * resultId returned by the BatchDetectAnomaly api. */ -export async function detectMultivariateLastAnomaly( +export async function getMultivariateBatchDetectionResult( context: Client, - modelId: string, - options: MultivariateMultivariateLastDetectionOptions, - optionalParams: MultivariateDetectMultivariateLastAnomalyOptionalParams = { + resultId: string, + options: MultivariateGetMultivariateBatchDetectionResultOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _detectMultivariateLastAnomalySend( +): Promise { + const result = await _getMultivariateBatchDetectionResultSend( context, - modelId, + resultId, options, - optionalParams, ); - return _detectMultivariateLastAnomalyDeserialize(result); + return _getMultivariateBatchDetectionResultDeserialize(result); } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/options.ts index b157684474..b20c56015e 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/options.ts @@ -4,23 +4,19 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface UnivariateDetectUnivariateEntireSeriesOptionalParams - extends OperationOptions {} - -/** Optional parameters. */ -export interface UnivariateDetectUnivariateLastPointOptionalParams +export interface MultivariateDetectMultivariateLastAnomalyOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface UnivariateDetectUnivariateChangePointOptionalParams +export interface MultivariateDetectMultivariateBatchAnomalyOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface MultivariateGetMultivariateBatchDetectionResultOptionalParams +export interface MultivariateGetMultivariateModelOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface MultivariateTrainMultivariateModelOptionalParams +export interface MultivariateDeleteMultivariateModelOptionalParams extends OperationOptions {} /** Optional parameters. */ @@ -33,17 +29,21 @@ export interface MultivariateListMultivariateModelsOptionalParams } /** Optional parameters. */ -export interface MultivariateDeleteMultivariateModelOptionalParams +export interface MultivariateTrainMultivariateModelOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface MultivariateGetMultivariateModelOptionalParams +export interface MultivariateGetMultivariateBatchDetectionResultOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface MultivariateDetectMultivariateBatchAnomalyOptionalParams +export interface UnivariateDetectUnivariateChangePointOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface MultivariateDetectMultivariateLastAnomalyOptionalParams +export interface UnivariateDetectUnivariateLastPointOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface UnivariateDetectUnivariateEntireSeriesOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts index 044e0eee1c..a5501a1b74 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/api/univariate/index.ts @@ -26,51 +26,53 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _detectUnivariateEntireSeriesSend( +export function _detectUnivariateChangePointSend( context: Client, - options: UnivariateUnivariateDetectionOptions, - optionalParams: UnivariateDetectUnivariateEntireSeriesOptionalParams = { + options: UnivariateUnivariateChangePointDetectionOptions, + optionalParams: UnivariateDetectUnivariateChangePointOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/timeseries/entire/detect") + .path("/timeseries/changepoint/detect") .post({ ...operationOptionsToRequestParameters(optionalParams), - body: univariateUnivariateDetectionOptionsSerializer(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...optionalParams.requestOptions?.headers, + }, + body: univariateUnivariateChangePointDetectionOptionsSerializer(options), }); } -export async function _detectUnivariateEntireSeriesDeserialize( +export async function _detectUnivariateChangePointDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return univariateUnivariateEntireDetectionResultDeserializer(result.body); + return univariateUnivariateChangePointDetectionResultDeserializer( + result.body, + ); } -/** - * This operation generates a model with an entire series, each point is detected - * with the same model. With this method, points before and after a certain point - * are used to determine whether it is an anomaly. The entire detection can give - * user an overall status of the time series. - */ -export async function detectUnivariateEntireSeries( +/** Evaluate change point score of every series point */ +export async function detectUnivariateChangePoint( context: Client, - options: UnivariateUnivariateDetectionOptions, - optionalParams: UnivariateDetectUnivariateEntireSeriesOptionalParams = { + options: UnivariateUnivariateChangePointDetectionOptions, + optionalParams: UnivariateDetectUnivariateChangePointOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _detectUnivariateEntireSeriesSend( +): Promise { + const result = await _detectUnivariateChangePointSend( context, options, optionalParams, ); - return _detectUnivariateEntireSeriesDeserialize(result); + return _detectUnivariateChangePointDeserialize(result); } export function _detectUnivariateLastPointSend( @@ -84,6 +86,11 @@ export function _detectUnivariateLastPointSend( .path("/timeseries/last/detect") .post({ ...operationOptionsToRequestParameters(optionalParams), + contentType: "application/json", + headers: { + accept: "application/json", + ...optionalParams.requestOptions?.headers, + }, body: univariateUnivariateDetectionOptionsSerializer(options), }); } @@ -118,46 +125,54 @@ export async function detectUnivariateLastPoint( return _detectUnivariateLastPointDeserialize(result); } -export function _detectUnivariateChangePointSend( +export function _detectUnivariateEntireSeriesSend( context: Client, - options: UnivariateUnivariateChangePointDetectionOptions, - optionalParams: UnivariateDetectUnivariateChangePointOptionalParams = { + options: UnivariateUnivariateDetectionOptions, + optionalParams: UnivariateDetectUnivariateEntireSeriesOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/timeseries/changepoint/detect") + .path("/timeseries/entire/detect") .post({ ...operationOptionsToRequestParameters(optionalParams), - body: univariateUnivariateChangePointDetectionOptionsSerializer(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...optionalParams.requestOptions?.headers, + }, + body: univariateUnivariateDetectionOptionsSerializer(options), }); } -export async function _detectUnivariateChangePointDeserialize( +export async function _detectUnivariateEntireSeriesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return univariateUnivariateChangePointDetectionResultDeserializer( - result.body, - ); + return univariateUnivariateEntireDetectionResultDeserializer(result.body); } -/** Evaluate change point score of every series point */ -export async function detectUnivariateChangePoint( +/** + * This operation generates a model with an entire series, each point is detected + * with the same model. With this method, points before and after a certain point + * are used to determine whether it is an anomaly. The entire detection can give + * user an overall status of the time series. + */ +export async function detectUnivariateEntireSeries( context: Client, - options: UnivariateUnivariateChangePointDetectionOptions, - optionalParams: UnivariateDetectUnivariateChangePointOptionalParams = { + options: UnivariateUnivariateDetectionOptions, + optionalParams: UnivariateDetectUnivariateEntireSeriesOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _detectUnivariateChangePointSend( +): Promise { + const result = await _detectUnivariateEntireSeriesSend( context, options, optionalParams, ); - return _detectUnivariateChangePointDeserialize(result); + return _detectUnivariateEntireSeriesDeserialize(result); } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts index 62047c82d1..f0fbffcf2e 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/multivariate/index.ts @@ -3,22 +3,22 @@ import { AnomalyDetectorContext } from "../../api/anomalyDetectorContext.js"; import { - getMultivariateBatchDetectionResult, - trainMultivariateModel, - listMultivariateModels, - deleteMultivariateModel, - getMultivariateModel, - detectMultivariateBatchAnomaly, detectMultivariateLastAnomaly, + detectMultivariateBatchAnomaly, + getMultivariateModel, + deleteMultivariateModel, + listMultivariateModels, + trainMultivariateModel, + getMultivariateBatchDetectionResult, } from "../../api/multivariate/index.js"; import { - MultivariateGetMultivariateBatchDetectionResultOptionalParams, - MultivariateTrainMultivariateModelOptionalParams, - MultivariateListMultivariateModelsOptionalParams, - MultivariateDeleteMultivariateModelOptionalParams, - MultivariateGetMultivariateModelOptionalParams, - MultivariateDetectMultivariateBatchAnomalyOptionalParams, MultivariateDetectMultivariateLastAnomalyOptionalParams, + MultivariateDetectMultivariateBatchAnomalyOptionalParams, + MultivariateGetMultivariateModelOptionalParams, + MultivariateDeleteMultivariateModelOptionalParams, + MultivariateListMultivariateModelsOptionalParams, + MultivariateTrainMultivariateModelOptionalParams, + MultivariateGetMultivariateBatchDetectionResultOptionalParams, } from "../../api/options.js"; import { MultivariateMultivariateDetectionResult, @@ -33,43 +33,16 @@ import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.j /** Interface representing a Multivariate operations. */ export interface MultivariateOperations { /** - * For asynchronous inference, get multivariate anomaly detection result based on - * resultId returned by the BatchDetectAnomaly api. - */ - getMultivariateBatchDetectionResult: ( - resultId: string, - options?: MultivariateGetMultivariateBatchDetectionResultOptionalParams, - ) => Promise; - /** - * Create and train a multivariate anomaly detection model. The request must - * include a source parameter to indicate an externally accessible Azure blob - * storage URI.There are two types of data input: An URI pointed to an Azure blob - * storage folder which contains multiple CSV files, and each CSV file contains - * two columns, timestamp and variable. Another type of input is an URI pointed to - * a CSV file in Azure blob storage, which contains all the variables and a - * timestamp column. - */ - trainMultivariateModel: ( - modelInfo: MultivariateModelInfo, - options?: MultivariateTrainMultivariateModelOptionalParams, - ) => Promise; - /** List models of a resource. */ - listMultivariateModels: ( - options?: MultivariateListMultivariateModelsOptionalParams, - ) => PagedAsyncIterableIterator; - /** Delete an existing multivariate model according to the modelId */ - deleteMultivariateModel: ( - modelId: string, - options?: MultivariateDeleteMultivariateModelOptionalParams, - ) => Promise; - /** - * Get detailed information of multivariate model, including the training status - * and variables used in the model. + * Submit multivariate anomaly detection task with the modelId of trained model + * and inference data, and the inference data should be put into request body in a + * JSON format. The request will complete synchronously and return the detection + * immediately in the response body. */ - getMultivariateModel: ( + detectMultivariateLastAnomaly: ( modelId: string, - options?: MultivariateGetMultivariateModelOptionalParams, - ) => Promise; + options: MultivariateMultivariateLastDetectionOptions, + optionalParams?: MultivariateDetectMultivariateLastAnomalyOptionalParams, + ) => Promise; /** * Submit multivariate anomaly detection task with the modelId of trained model * and inference data, the input schema should be the same with the training @@ -84,51 +57,78 @@ export interface MultivariateOperations { optionalParams?: MultivariateDetectMultivariateBatchAnomalyOptionalParams, ) => Promise; /** - * Submit multivariate anomaly detection task with the modelId of trained model - * and inference data, and the inference data should be put into request body in a - * JSON format. The request will complete synchronously and return the detection - * immediately in the response body. + * Get detailed information of multivariate model, including the training status + * and variables used in the model. */ - detectMultivariateLastAnomaly: ( + getMultivariateModel: ( modelId: string, - options: MultivariateMultivariateLastDetectionOptions, - optionalParams?: MultivariateDetectMultivariateLastAnomalyOptionalParams, - ) => Promise; + options?: MultivariateGetMultivariateModelOptionalParams, + ) => Promise; + /** Delete an existing multivariate model according to the modelId */ + deleteMultivariateModel: ( + modelId: string, + options?: MultivariateDeleteMultivariateModelOptionalParams, + ) => Promise; + /** List models of a resource. */ + listMultivariateModels: ( + options?: MultivariateListMultivariateModelsOptionalParams, + ) => PagedAsyncIterableIterator; + /** + * Create and train a multivariate anomaly detection model. The request must + * include a source parameter to indicate an externally accessible Azure blob + * storage URI.There are two types of data input: An URI pointed to an Azure blob + * storage folder which contains multiple CSV files, and each CSV file contains + * two columns, timestamp and variable. Another type of input is an URI pointed to + * a CSV file in Azure blob storage, which contains all the variables and a + * timestamp column. + */ + trainMultivariateModel: ( + modelInfo: MultivariateModelInfo, + options?: MultivariateTrainMultivariateModelOptionalParams, + ) => Promise; + /** + * For asynchronous inference, get multivariate anomaly detection result based on + * resultId returned by the BatchDetectAnomaly api. + */ + getMultivariateBatchDetectionResult: ( + resultId: string, + options?: MultivariateGetMultivariateBatchDetectionResultOptionalParams, + ) => Promise; } export function getMultivariate(context: AnomalyDetectorContext) { return { - getMultivariateBatchDetectionResult: ( - resultId: string, - options?: MultivariateGetMultivariateBatchDetectionResultOptionalParams, - ) => getMultivariateBatchDetectionResult(context, resultId, options), - trainMultivariateModel: ( - modelInfo: MultivariateModelInfo, - options?: MultivariateTrainMultivariateModelOptionalParams, - ) => trainMultivariateModel(context, modelInfo, options), - listMultivariateModels: ( - options?: MultivariateListMultivariateModelsOptionalParams, - ) => listMultivariateModels(context, options), - deleteMultivariateModel: ( - modelId: string, - options?: MultivariateDeleteMultivariateModelOptionalParams, - ) => deleteMultivariateModel(context, modelId, options), - getMultivariateModel: ( + detectMultivariateLastAnomaly: ( modelId: string, - options?: MultivariateGetMultivariateModelOptionalParams, - ) => getMultivariateModel(context, modelId, options), + options: MultivariateMultivariateLastDetectionOptions, + optionalParams?: MultivariateDetectMultivariateLastAnomalyOptionalParams, + ) => + detectMultivariateLastAnomaly(context, modelId, options, optionalParams), detectMultivariateBatchAnomaly: ( modelId: string, options: MultivariateMultivariateBatchDetectionOptions, optionalParams?: MultivariateDetectMultivariateBatchAnomalyOptionalParams, ) => detectMultivariateBatchAnomaly(context, modelId, options, optionalParams), - detectMultivariateLastAnomaly: ( + getMultivariateModel: ( modelId: string, - options: MultivariateMultivariateLastDetectionOptions, - optionalParams?: MultivariateDetectMultivariateLastAnomalyOptionalParams, - ) => - detectMultivariateLastAnomaly(context, modelId, options, optionalParams), + options?: MultivariateGetMultivariateModelOptionalParams, + ) => getMultivariateModel(context, modelId, options), + deleteMultivariateModel: ( + modelId: string, + options?: MultivariateDeleteMultivariateModelOptionalParams, + ) => deleteMultivariateModel(context, modelId, options), + listMultivariateModels: ( + options?: MultivariateListMultivariateModelsOptionalParams, + ) => listMultivariateModels(context, options), + trainMultivariateModel: ( + modelInfo: MultivariateModelInfo, + options?: MultivariateTrainMultivariateModelOptionalParams, + ) => trainMultivariateModel(context, modelInfo, options), + getMultivariateBatchDetectionResult: ( + resultId: string, + options?: MultivariateGetMultivariateBatchDetectionResultOptionalParams, + ) => getMultivariateBatchDetectionResult(context, resultId, options), }; } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts index d8ccd2ab9d..27a096e462 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/classic/univariate/index.ts @@ -3,14 +3,14 @@ import { AnomalyDetectorContext } from "../../api/anomalyDetectorContext.js"; import { - UnivariateDetectUnivariateEntireSeriesOptionalParams, - UnivariateDetectUnivariateLastPointOptionalParams, UnivariateDetectUnivariateChangePointOptionalParams, + UnivariateDetectUnivariateLastPointOptionalParams, + UnivariateDetectUnivariateEntireSeriesOptionalParams, } from "../../api/options.js"; import { - detectUnivariateEntireSeries, - detectUnivariateLastPoint, detectUnivariateChangePoint, + detectUnivariateLastPoint, + detectUnivariateEntireSeries, } from "../../api/univariate/index.js"; import { UnivariateUnivariateDetectionOptions, @@ -22,6 +22,19 @@ import { /** Interface representing a Univariate operations. */ export interface UnivariateOperations { + /** Evaluate change point score of every series point */ + detectUnivariateChangePoint: ( + options: UnivariateUnivariateChangePointDetectionOptions, + optionalParams?: UnivariateDetectUnivariateChangePointOptionalParams, + ) => Promise; + /** + * This operation generates a model using the points that you sent into the API, + * and based on all data to determine whether the last point is anomalous. + */ + detectUnivariateLastPoint: ( + options: UnivariateUnivariateDetectionOptions, + optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams, + ) => Promise; /** * This operation generates a model with an entire series, each point is detected * with the same model. With this method, points before and after a certain point @@ -32,35 +45,22 @@ export interface UnivariateOperations { options: UnivariateUnivariateDetectionOptions, optionalParams?: UnivariateDetectUnivariateEntireSeriesOptionalParams, ) => Promise; - /** - * This operation generates a model using the points that you sent into the API, - * and based on all data to determine whether the last point is anomalous. - */ - detectUnivariateLastPoint: ( - options: UnivariateUnivariateDetectionOptions, - optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams, - ) => Promise; - /** Evaluate change point score of every series point */ - detectUnivariateChangePoint: ( - options: UnivariateUnivariateChangePointDetectionOptions, - optionalParams?: UnivariateDetectUnivariateChangePointOptionalParams, - ) => Promise; } export function getUnivariate(context: AnomalyDetectorContext) { return { - detectUnivariateEntireSeries: ( - options: UnivariateUnivariateDetectionOptions, - optionalParams?: UnivariateDetectUnivariateEntireSeriesOptionalParams, - ) => detectUnivariateEntireSeries(context, options, optionalParams), - detectUnivariateLastPoint: ( - options: UnivariateUnivariateDetectionOptions, - optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams, - ) => detectUnivariateLastPoint(context, options, optionalParams), detectUnivariateChangePoint: ( options: UnivariateUnivariateChangePointDetectionOptions, optionalParams?: UnivariateDetectUnivariateChangePointOptionalParams, ) => detectUnivariateChangePoint(context, options, optionalParams), + detectUnivariateLastPoint: ( + options: UnivariateUnivariateDetectionOptions, + optionalParams?: UnivariateDetectUnivariateLastPointOptionalParams, + ) => detectUnivariateLastPoint(context, options, optionalParams), + detectUnivariateEntireSeries: ( + options: UnivariateUnivariateDetectionOptions, + optionalParams?: UnivariateDetectUnivariateEntireSeriesOptionalParams, + ) => detectUnivariateEntireSeries(context, options, optionalParams), }; } diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts index d0a887e898..24ec34fda5 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/index.ts @@ -43,16 +43,16 @@ export { } from "./models/index.js"; export { AnomalyDetectorClientOptionalParams, - UnivariateDetectUnivariateEntireSeriesOptionalParams, - UnivariateDetectUnivariateLastPointOptionalParams, - UnivariateDetectUnivariateChangePointOptionalParams, - MultivariateGetMultivariateBatchDetectionResultOptionalParams, - MultivariateTrainMultivariateModelOptionalParams, - MultivariateListMultivariateModelsOptionalParams, - MultivariateDeleteMultivariateModelOptionalParams, - MultivariateGetMultivariateModelOptionalParams, - MultivariateDetectMultivariateBatchAnomalyOptionalParams, MultivariateDetectMultivariateLastAnomalyOptionalParams, + MultivariateDetectMultivariateBatchAnomalyOptionalParams, + MultivariateGetMultivariateModelOptionalParams, + MultivariateDeleteMultivariateModelOptionalParams, + MultivariateListMultivariateModelsOptionalParams, + MultivariateTrainMultivariateModelOptionalParams, + MultivariateGetMultivariateBatchDetectionResultOptionalParams, + UnivariateDetectUnivariateChangePointOptionalParams, + UnivariateDetectUnivariateLastPointOptionalParams, + UnivariateDetectUnivariateEntireSeriesOptionalParams, } from "./api/index.js"; export { MultivariateOperations, diff --git a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts index e9d6193152..d6773e2fa2 100644 --- a/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/anomalyDetector/generated/typespec-ts/src/models/models.ts @@ -124,8 +124,12 @@ export function multivariateVariableStateSerializer( variable: item["variable"], filledNARatio: item["filledNARatio"], effectiveCount: item["effectiveCount"], - firstTimestamp: item["firstTimestamp"]?.toISOString(), - lastTimestamp: item["lastTimestamp"]?.toISOString(), + firstTimestamp: !item["firstTimestamp"] + ? item["firstTimestamp"] + : item["firstTimestamp"].toISOString(), + lastTimestamp: !item["lastTimestamp"] + ? item["lastTimestamp"] + : item["lastTimestamp"].toISOString(), }; } @@ -783,7 +787,12 @@ export interface UnivariateTimeSeriesPoint { export function univariateTimeSeriesPointSerializer( item: UnivariateTimeSeriesPoint, ): any { - return { timestamp: item["timestamp"]?.toISOString(), value: item["value"] }; + return { + timestamp: !item["timestamp"] + ? item["timestamp"] + : item["timestamp"].toISOString(), + value: item["value"], + }; } /** Type of UnivariateTimeGranularity */ diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md b/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md index f0f729f4fb..05bd62b29c 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/review/batch.api.md @@ -580,7 +580,9 @@ export type CachingType = "none" | "readonly" | "readwrite"; // @public export interface CancelCertificateDeletionOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -648,50 +650,57 @@ export type ContinuablePage = TPage & { // @public export interface CreateCertificateOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface CreateJobOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface CreateJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface CreateNodeUserOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface CreatePoolOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface CreateTaskCollectionOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface CreateTaskOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -712,67 +721,83 @@ export interface DeleteCertificateError { // @public export interface DeleteCertificateOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeleteJobOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeleteJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeleteNodeFileOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; recursive?: boolean; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeleteNodeUserOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeletePoolOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeleteTaskFileOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; recursive?: boolean; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DeleteTaskOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -795,36 +820,42 @@ export type DisableJobOption = "requeue" | "terminate" | "wait"; // @public export interface DisableJobOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DisableJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DisableNodeSchedulingOptionalParams extends OperationOptions { - apiVersion?: string; body?: NodeDisableSchedulingOptions; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface DisablePoolAutoScaleOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -844,38 +875,45 @@ export type ElevationLevel = "nonadmin" | "admin"; // @public export interface EnableJobOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface EnableJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface EnableNodeSchedulingOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface EnablePoolAutoScaleOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -896,8 +934,9 @@ export interface ErrorMessage { // @public export interface EvaluatePoolAutoScaleOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -940,14 +979,18 @@ export interface FileProperties { // @public export interface GetApplicationOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetCertificateOptionalParams extends OperationOptions { $select?: string[]; - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -955,11 +998,13 @@ export interface GetCertificateOptionalParams extends OperationOptions { export interface GetJobOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -967,60 +1012,76 @@ export interface GetJobOptionalParams extends OperationOptions { export interface GetJobScheduleOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetJobTaskCountsOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetNodeExtensionOptionalParams extends OperationOptions { $select?: string[]; - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetNodeFileOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifModifiedSince?: Date; ifUnmodifiedSince?: Date; + ocpDate?: Date; ocpRange?: string; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifModifiedSince?: Date; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetNodeOptionalParams extends OperationOptions { $select?: string[]; - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetNodeRemoteDesktopFileOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetNodeRemoteLoginSettingsOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1028,28 +1089,34 @@ export interface GetNodeRemoteLoginSettingsOptionalParams extends OperationOptio export interface GetPoolOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetTaskFileOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifModifiedSince?: Date; ifUnmodifiedSince?: Date; + ocpDate?: Date; ocpRange?: string; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifModifiedSince?: Date; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1057,11 +1124,13 @@ export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { export interface GetTaskOptionalParams extends OperationOptions { $expand?: string[]; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1245,11 +1314,13 @@ export interface JobScheduleExecutionInformation { // @public export interface JobScheduleExistsOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1336,8 +1407,10 @@ export interface LinuxUserConfiguration { // @public export interface ListApplicationsOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1345,8 +1418,10 @@ export interface ListApplicationsOptionalParams extends OperationOptions { export interface ListCertificatesOptionalParams extends OperationOptions { $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1354,7 +1429,10 @@ export interface ListCertificatesOptionalParams extends OperationOptions { export interface ListJobPreparationAndReleaseTaskStatusOptionalParams extends OperationOptions { $filter?: string; $select?: string[]; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1363,8 +1441,10 @@ export interface ListJobSchedulesOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1373,8 +1453,10 @@ export interface ListJobsFromScheduleOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1383,24 +1465,31 @@ export interface ListJobsOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ListNodeExtensionsOptionalParams extends OperationOptions { $select?: string[]; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ListNodeFilesOptionalParams extends OperationOptions { $filter?: string; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; recursive?: boolean; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1408,16 +1497,20 @@ export interface ListNodeFilesOptionalParams extends OperationOptions { export interface ListNodesOptionalParams extends OperationOptions { $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ListPoolNodeCountsOptionalParams extends OperationOptions { $filter?: string; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1426,17 +1519,21 @@ export interface ListPoolsOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { $filter?: string; - apiVersion?: string; + clientRequestId?: string; endtime?: Date; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; starttime?: Date; timeOutInSeconds?: number; } @@ -1444,23 +1541,30 @@ export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { // @public export interface ListSubTasksOptionalParams extends OperationOptions { $select?: string[]; - apiVersion?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ListSupportedImagesOptionalParams extends OperationOptions { $filter?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ListTaskFilesOptionalParams extends OperationOptions { $filter?: string; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; recursive?: boolean; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1469,8 +1573,10 @@ export interface ListTasksOptionalParams extends OperationOptions { $expand?: string[]; $filter?: string; $select?: string[]; - apiVersion?: string; + clientRequestId?: string; maxresults?: number; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1664,11 +1770,13 @@ export interface PoolEndpointConfiguration { // @public export interface PoolExistsOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1746,19 +1854,22 @@ export interface PublicIpAddressConfiguration { // @public export interface ReactivateTaskOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface RebootNodeOptionalParams extends OperationOptions { - apiVersion?: string; body?: NodeRebootOptions; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1770,67 +1881,74 @@ export interface RecentJob { // @public export interface ReimageNodeOptionalParams extends OperationOptions { - apiVersion?: string; body?: NodeReimageOptions; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface RemoveNodesOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ReplaceJobOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ReplaceJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ReplaceNodeUserOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ReplacePoolPropertiesOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface ReplaceTaskOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1843,12 +1961,13 @@ export interface ResizeError { // @public export interface ResizePoolOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -1923,11 +2042,13 @@ export type StatusLevelTypes = "Error" | "Info" | "Warning"; // @public export interface StopPoolResizeOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -2089,66 +2210,74 @@ export interface TaskStatistics { // @public export interface TerminateJobOptionalParams extends OperationOptions { - apiVersion?: string; body?: BatchJobTerminateOptions; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface TerminateJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface TerminateTaskOptionalParams extends OperationOptions { - apiVersion?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface UpdateJobOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface UpdateJobScheduleOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } // @public export interface UpdatePoolOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; ifMatch?: string; ifModifiedSince?: Date; ifNoneMatch?: string; ifUnmodifiedSince?: Date; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } @@ -2168,8 +2297,9 @@ export interface UploadBatchServiceLogsResult { // @public export interface UploadNodeLogsOptionalParams extends OperationOptions { - apiVersion?: string; - contentType?: string; + clientRequestId?: string; + ocpDate?: Date; + returnClientRequestId?: boolean; timeOutInSeconds?: number; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts index 3d8f800f44..489548bb57 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/batchContext.ts @@ -7,7 +7,11 @@ import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; /** Azure Batch provides Cloud-scale job scheduling and compute management. */ -export interface BatchContext extends Client {} +export interface BatchContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface BatchClientOptionalParams extends ClientOptions { @@ -22,7 +26,8 @@ export function createBatch( credential: TokenCredential, options: BatchClientOptionalParams = {}, ): BatchContext { - const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-batch/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -40,10 +45,21 @@ export function createBatch( }; const clientContext = getClient(endpointUrl, credential, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - if (options.apiVersion) { - logger.warning( - "This client does not support client api-version, please change it at the operation level", - ); - } - return clientContext; + const apiVersion = options.apiVersion ?? "2023-05-01.17.0"; + 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, apiVersion } as BatchContext; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts index 6ae19d1894..b54875d01d 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/index.ts @@ -7,158 +7,158 @@ export { BatchClientOptionalParams, } from "./batchContext.js"; export { - listApplications, - getApplication, - listPoolUsageMetrics, - createPool, - listPools, - deletePool, - poolExists, - getPool, - updatePool, - disablePoolAutoScale, - enablePoolAutoScale, - evaluatePoolAutoScale, - resizePool, - stopPoolResize, - replacePoolProperties, - removeNodes, - listSupportedImages, - listPoolNodeCounts, - deleteJob, - getJob, - updateJob, - replaceJob, - disableJob, - enableJob, - terminateJob, - createJob, - listJobs, - listJobsFromSchedule, - listJobPreparationAndReleaseTaskStatus, - getJobTaskCounts, - createCertificate, - listCertificates, - cancelCertificateDeletion, - deleteCertificate, - getCertificate, - jobScheduleExists, - deleteJobSchedule, - getJobSchedule, - updateJobSchedule, - replaceJobSchedule, - disableJobSchedule, - enableJobSchedule, - terminateJobSchedule, - createJobSchedule, - listJobSchedules, - createTask, - listTasks, - createTaskCollection, - deleteTask, - getTask, - replaceTask, - listSubTasks, - terminateTask, - reactivateTask, - deleteTaskFile, - getTaskFile, - getTaskFileProperties, - listTaskFiles, - createNodeUser, - deleteNodeUser, - replaceNodeUser, - getNode, - rebootNode, - reimageNode, - disableNodeScheduling, - enableNodeScheduling, - getNodeRemoteLoginSettings, - getNodeRemoteDesktopFile, - uploadNodeLogs, - listNodes, - getNodeExtension, - listNodeExtensions, - deleteNodeFile, - getNodeFile, - getNodeFileProperties, listNodeFiles, + getNodeFileProperties, + getNodeFile, + deleteNodeFile, + listNodeExtensions, + getNodeExtension, + listNodes, + uploadNodeLogs, + getNodeRemoteDesktopFile, + getNodeRemoteLoginSettings, + enableNodeScheduling, + disableNodeScheduling, + reimageNode, + rebootNode, + getNode, + replaceNodeUser, + deleteNodeUser, + createNodeUser, + listTaskFiles, + getTaskFileProperties, + getTaskFile, + deleteTaskFile, + reactivateTask, + terminateTask, + listSubTasks, + replaceTask, + getTask, + deleteTask, + createTaskCollection, + listTasks, + createTask, + listJobSchedules, + createJobSchedule, + terminateJobSchedule, + enableJobSchedule, + disableJobSchedule, + replaceJobSchedule, + updateJobSchedule, + getJobSchedule, + deleteJobSchedule, + jobScheduleExists, + getCertificate, + deleteCertificate, + cancelCertificateDeletion, + listCertificates, + createCertificate, + getJobTaskCounts, + listJobPreparationAndReleaseTaskStatus, + listJobsFromSchedule, + listJobs, + createJob, + terminateJob, + enableJob, + disableJob, + replaceJob, + updateJob, + getJob, + deleteJob, + listPoolNodeCounts, + listSupportedImages, + removeNodes, + replacePoolProperties, + stopPoolResize, + resizePool, + evaluatePoolAutoScale, + enablePoolAutoScale, + disablePoolAutoScale, + updatePool, + getPool, + poolExists, + deletePool, + listPools, + createPool, + listPoolUsageMetrics, + getApplication, + listApplications, } from "./operations.js"; export { - ListApplicationsOptionalParams, - GetApplicationOptionalParams, - ListPoolUsageMetricsOptionalParams, - CreatePoolOptionalParams, - ListPoolsOptionalParams, - DeletePoolOptionalParams, - PoolExistsOptionalParams, - GetPoolOptionalParams, - UpdatePoolOptionalParams, - DisablePoolAutoScaleOptionalParams, - EnablePoolAutoScaleOptionalParams, - EvaluatePoolAutoScaleOptionalParams, - ResizePoolOptionalParams, - StopPoolResizeOptionalParams, - ReplacePoolPropertiesOptionalParams, - RemoveNodesOptionalParams, - ListSupportedImagesOptionalParams, - ListPoolNodeCountsOptionalParams, - DeleteJobOptionalParams, - GetJobOptionalParams, - UpdateJobOptionalParams, - ReplaceJobOptionalParams, - DisableJobOptionalParams, - EnableJobOptionalParams, - TerminateJobOptionalParams, - CreateJobOptionalParams, - ListJobsOptionalParams, - ListJobsFromScheduleOptionalParams, - ListJobPreparationAndReleaseTaskStatusOptionalParams, - GetJobTaskCountsOptionalParams, - CreateCertificateOptionalParams, - ListCertificatesOptionalParams, - CancelCertificateDeletionOptionalParams, - DeleteCertificateOptionalParams, - GetCertificateOptionalParams, - JobScheduleExistsOptionalParams, - DeleteJobScheduleOptionalParams, - GetJobScheduleOptionalParams, - UpdateJobScheduleOptionalParams, - ReplaceJobScheduleOptionalParams, - DisableJobScheduleOptionalParams, - EnableJobScheduleOptionalParams, - TerminateJobScheduleOptionalParams, - CreateJobScheduleOptionalParams, - ListJobSchedulesOptionalParams, - CreateTaskOptionalParams, - ListTasksOptionalParams, - CreateTaskCollectionOptionalParams, - DeleteTaskOptionalParams, - GetTaskOptionalParams, - ReplaceTaskOptionalParams, - ListSubTasksOptionalParams, - TerminateTaskOptionalParams, - ReactivateTaskOptionalParams, - DeleteTaskFileOptionalParams, - GetTaskFileOptionalParams, - GetTaskFilePropertiesOptionalParams, - ListTaskFilesOptionalParams, - CreateNodeUserOptionalParams, - DeleteNodeUserOptionalParams, - ReplaceNodeUserOptionalParams, - GetNodeOptionalParams, - RebootNodeOptionalParams, - ReimageNodeOptionalParams, - DisableNodeSchedulingOptionalParams, - EnableNodeSchedulingOptionalParams, - GetNodeRemoteLoginSettingsOptionalParams, - GetNodeRemoteDesktopFileOptionalParams, - UploadNodeLogsOptionalParams, - ListNodesOptionalParams, - GetNodeExtensionOptionalParams, - ListNodeExtensionsOptionalParams, - DeleteNodeFileOptionalParams, - GetNodeFileOptionalParams, - GetNodeFilePropertiesOptionalParams, ListNodeFilesOptionalParams, + GetNodeFilePropertiesOptionalParams, + GetNodeFileOptionalParams, + DeleteNodeFileOptionalParams, + ListNodeExtensionsOptionalParams, + GetNodeExtensionOptionalParams, + ListNodesOptionalParams, + UploadNodeLogsOptionalParams, + GetNodeRemoteDesktopFileOptionalParams, + GetNodeRemoteLoginSettingsOptionalParams, + EnableNodeSchedulingOptionalParams, + DisableNodeSchedulingOptionalParams, + ReimageNodeOptionalParams, + RebootNodeOptionalParams, + GetNodeOptionalParams, + ReplaceNodeUserOptionalParams, + DeleteNodeUserOptionalParams, + CreateNodeUserOptionalParams, + ListTaskFilesOptionalParams, + GetTaskFilePropertiesOptionalParams, + GetTaskFileOptionalParams, + DeleteTaskFileOptionalParams, + ReactivateTaskOptionalParams, + TerminateTaskOptionalParams, + ListSubTasksOptionalParams, + ReplaceTaskOptionalParams, + GetTaskOptionalParams, + DeleteTaskOptionalParams, + CreateTaskCollectionOptionalParams, + ListTasksOptionalParams, + CreateTaskOptionalParams, + ListJobSchedulesOptionalParams, + CreateJobScheduleOptionalParams, + TerminateJobScheduleOptionalParams, + EnableJobScheduleOptionalParams, + DisableJobScheduleOptionalParams, + ReplaceJobScheduleOptionalParams, + UpdateJobScheduleOptionalParams, + GetJobScheduleOptionalParams, + DeleteJobScheduleOptionalParams, + JobScheduleExistsOptionalParams, + GetCertificateOptionalParams, + DeleteCertificateOptionalParams, + CancelCertificateDeletionOptionalParams, + ListCertificatesOptionalParams, + CreateCertificateOptionalParams, + GetJobTaskCountsOptionalParams, + ListJobPreparationAndReleaseTaskStatusOptionalParams, + ListJobsFromScheduleOptionalParams, + ListJobsOptionalParams, + CreateJobOptionalParams, + TerminateJobOptionalParams, + EnableJobOptionalParams, + DisableJobOptionalParams, + ReplaceJobOptionalParams, + UpdateJobOptionalParams, + GetJobOptionalParams, + DeleteJobOptionalParams, + ListPoolNodeCountsOptionalParams, + ListSupportedImagesOptionalParams, + RemoveNodesOptionalParams, + ReplacePoolPropertiesOptionalParams, + StopPoolResizeOptionalParams, + ResizePoolOptionalParams, + EvaluatePoolAutoScaleOptionalParams, + EnablePoolAutoScaleOptionalParams, + DisablePoolAutoScaleOptionalParams, + UpdatePoolOptionalParams, + GetPoolOptionalParams, + PoolExistsOptionalParams, + DeletePoolOptionalParams, + ListPoolsOptionalParams, + CreatePoolOptionalParams, + ListPoolUsageMetricsOptionalParams, + GetApplicationOptionalParams, + ListApplicationsOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts index 30f6aae1d0..f9bfb9bd4b 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/operations.ts @@ -195,171 +195,286 @@ import { } from "@azure-rest/core-client"; import { stringToUint8Array } from "@azure/core-util"; -export function _listApplicationsSend( +export function _listNodeFilesSend( context: Client, - options: ListApplicationsOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + options: ListNodeFilesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/applications") + .path("/pools/{poolId}/nodes/{nodeId}/files", poolId, nodeId) .get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + recursive: options?.recursive, }, }); } -export async function _listApplicationsDeserialize( +export async function _listNodeFilesDeserialize( result: PathUncheckedResponse, -): Promise<_ApplicationListResult> { +): Promise<_NodeFileListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _applicationListResultDeserializer(result.body); + return _nodeFileListResultDeserializer(result.body); } -/** - * This operation returns only Applications and versions that are available for - * use on Compute Nodes; that is, that can be used in an Package reference. For - * administrator information about applications and versions that are not yet - * available to Compute Nodes, use the Azure portal or the Azure Resource Manager - * API. - */ -export function listApplications( +/** Lists all of the files in Task directories on the specified Compute Node. */ +export function listNodeFiles( context: Client, - options: ListApplicationsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + poolId: string, + nodeId: string, + options: ListNodeFilesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listApplicationsSend(context, options), - _listApplicationsDeserialize, + () => _listNodeFilesSend(context, poolId, nodeId, options), + _listNodeFilesDeserialize, ["200"], { itemName: "value", nextLinkName: "odata.nextLink" }, ); } -export function _getApplicationSend( +export function _getNodeFilePropertiesSend( context: Client, - applicationId: string, - options: GetApplicationOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + filePath: string, + options: GetNodeFilePropertiesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/applications/{applicationId}", applicationId) - .get({ + .path( + "/pools/{poolId}/nodes/{nodeId}/files/{filePath}", + poolId, + nodeId, + filePath, + ) + .head({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _getApplicationDeserialize( +export async function _getNodeFilePropertiesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return batchApplicationDeserializer(result.body); + return; } -/** - * This operation returns only Applications and versions that are available for - * use on Compute Nodes; that is, that can be used in an Package reference. For - * administrator information about Applications and versions that are not yet - * available to Compute Nodes, use the Azure portal or the Azure Resource Manager - * API. - */ -export async function getApplication( +/** Gets the properties of the specified Compute Node file. */ +export async function getNodeFileProperties( context: Client, - applicationId: string, - options: GetApplicationOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getApplicationSend(context, applicationId, options); - return _getApplicationDeserialize(result); + poolId: string, + nodeId: string, + filePath: string, + options: GetNodeFilePropertiesOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getNodeFilePropertiesSend( + context, + poolId, + nodeId, + filePath, + options, + ); + return _getNodeFilePropertiesDeserialize(result); } -export function _listPoolUsageMetricsSend( +export function _getNodeFileSend( context: Client, - options: ListPoolUsageMetricsOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + filePath: string, + options: GetNodeFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/poolusagemetrics") + .path( + "/pools/{poolId}/nodes/{nodeId}/files/{filePath}", + poolId, + nodeId, + filePath, + ) .get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + ...(options?.ocpRange !== undefined + ? { "ocp-range": options?.ocpRange } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - starttime: options?.starttime?.toISOString(), - endtime: options?.endtime?.toISOString(), - $filter: options?.$filter, }, }); } -export async function _listPoolUsageMetricsDeserialize( +export async function _getNodeFileDeserialize( result: PathUncheckedResponse, -): Promise<_PoolListUsageMetricsResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _poolListUsageMetricsResultDeserializer(result.body); + return typeof result.body === "string" + ? stringToUint8Array(result.body, "base64") + : result.body; } -/** - * If you do not specify a $filter clause including a poolId, the response - * includes all Pools that existed in the Account in the time range of the - * returned aggregation intervals. If you do not specify a $filter clause - * including a startTime or endTime these filters default to the start and end - * times of the last aggregation interval currently available; that is, only the - * last aggregation interval is returned. - */ -export function listPoolUsageMetrics( +/** Returns the content of the specified Compute Node file. */ +export async function getNodeFile( context: Client, - options: ListPoolUsageMetricsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + poolId: string, + nodeId: string, + filePath: string, + options: GetNodeFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getNodeFileSend( context, - () => _listPoolUsageMetricsSend(context, options), - _listPoolUsageMetricsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, + poolId, + nodeId, + filePath, + options, ); + return _getNodeFileDeserialize(result); } -export function _createPoolSend( +export function _deleteNodeFileSend( context: Client, - body: BatchPoolCreateOptions, - options: CreatePoolOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + filePath: string, + options: DeleteNodeFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools") - .post({ + .path( + "/pools/{poolId}/nodes/{nodeId}/files/{filePath}", + poolId, + nodeId, + filePath, + ) + .delete({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, + recursive: options?.recursive, }, - body: batchPoolCreateOptionsSerializer(body), }); } -export async function _createPoolDeserialize( +export async function _deleteNodeFileDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["201"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -367,545 +482,545 @@ export async function _createPoolDeserialize( return; } -/** - * When naming Pools, avoid including sensitive information such as user names or - * secret project names. This information may appear in telemetry logs accessible - * to Microsoft Support engineers. - */ -export async function createPool( +/** Deletes the specified file from the Compute Node. */ +export async function deleteNodeFile( context: Client, - body: BatchPoolCreateOptions, - options: CreatePoolOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + filePath: string, + options: DeleteNodeFileOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createPoolSend(context, body, options); - return _createPoolDeserialize(result); + const result = await _deleteNodeFileSend( + context, + poolId, + nodeId, + filePath, + options, + ); + return _deleteNodeFileDeserialize(result); } -export function _listPoolsSend( +export function _listNodeExtensionsSend( context: Client, - options: ListPoolsOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/pools").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _listPoolsDeserialize( - result: PathUncheckedResponse, -): Promise<_BatchPoolListResult> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return _batchPoolListResultDeserializer(result.body); -} - -/** Lists all of the Pools in the specified Account. */ -export function listPools( - context: Client, - options: ListPoolsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listPoolsSend(context, options), - _listPoolsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); -} - -export function _deletePoolSend( - context: Client, - poolId: string, - options: DeletePoolOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + options: ListNodeExtensionsOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/pools/{poolId}", poolId) - .delete({ + .path("/pools/{poolId}/nodes/{nodeId}/extensions", poolId, nodeId) + .get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), - } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } -export async function _deletePoolDeserialize( +export async function _listNodeExtensionsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["202"]; +): Promise<_NodeVMExtensionList> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return _nodeVMExtensionListDeserializer(result.body); } -/** - * When you request that a Pool be deleted, the following actions occur: the Pool - * state is set to deleting; any ongoing resize operation on the Pool are stopped; - * the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks - * running on existing Compute Nodes are terminated and requeued (as if a resize - * Pool operation had been requested with the default requeue option); finally, - * the Pool is removed from the system. Because running Tasks are requeued, the - * user can rerun these Tasks by updating their Job to target a different Pool. - * The Tasks can then run on the new Pool. If you want to override the requeue - * behavior, then you should call resize Pool explicitly to shrink the Pool to - * zero size before deleting the Pool. If you call an Update, Patch or Delete API - * on a Pool in the deleting state, it will fail with HTTP status code 409 with - * error code PoolBeingDeleted. - */ -export async function deletePool( +/** Lists the Compute Nodes Extensions in the specified Pool. */ +export function listNodeExtensions( context: Client, poolId: string, - options: DeletePoolOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deletePoolSend(context, poolId, options); - return _deletePoolDeserialize(result); + nodeId: string, + options: ListNodeExtensionsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listNodeExtensionsSend(context, poolId, nodeId, options), + _listNodeExtensionsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); } -export function _poolExistsSend( +export function _getNodeExtensionSend( context: Client, poolId: string, - options: PoolExistsOptionalParams = { requestOptions: {} }, + nodeId: string, + extensionName: string, + options: GetNodeExtensionOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}", poolId) - .head({ + .path( + "/pools/{poolId}/nodes/{nodeId}/extensions/{extensionName}", + poolId, + nodeId, + extensionName, + ) + .get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, }); } -export async function _poolExistsDeserialize( +export async function _getNodeExtensionDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "404"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return nodeVMExtensionDeserializer(result.body); } -/** Gets basic properties of a Pool. */ -export async function poolExists( +/** Gets information about the specified Compute Node Extension. */ +export async function getNodeExtension( context: Client, poolId: string, - options: PoolExistsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _poolExistsSend(context, poolId, options); - return _poolExistsDeserialize(result); + nodeId: string, + extensionName: string, + options: GetNodeExtensionOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getNodeExtensionSend( + context, + poolId, + nodeId, + extensionName, + options, + ); + return _getNodeExtensionDeserialize(result); } -export function _getPoolSend( +export function _listNodesSend( context: Client, poolId: string, - options: GetPoolOptionalParams = { requestOptions: {} }, + options: ListNodesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/pools/{poolId}", poolId).get({ + return context.path("/pools/{poolId}/nodes", poolId).get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), - } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, $select: !options?.$select ? options?.$select : options?.$select.map((p: any) => { return p; }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), }, }); } -export async function _getPoolDeserialize( +export async function _listNodesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_BatchNodeListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return batchPoolDeserializer(result.body); + return _batchNodeListResultDeserializer(result.body); } -/** Gets information about the specified Pool. */ -export async function getPool( +/** Lists the Compute Nodes in the specified Pool. */ +export function listNodes( context: Client, poolId: string, - options: GetPoolOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getPoolSend(context, poolId, options); - return _getPoolDeserialize(result); + options: ListNodesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listNodesSend(context, poolId, options), + _listNodesDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); } -export function _updatePoolSend( +export function _uploadNodeLogsSend( context: Client, poolId: string, - body: BatchPoolUpdateOptions, - options: UpdatePoolOptionalParams = { requestOptions: {} }, + nodeId: string, + body: UploadBatchServiceLogsOptions, + options: UploadNodeLogsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}", poolId) - .patch({ + .path( + "/pools/{poolId}/nodes/{nodeId}/uploadbatchservicelogs", + poolId, + nodeId, + ) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchPoolUpdateOptionsSerializer(body), + body: uploadBatchServiceLogsOptionsSerializer(body), }); } -export async function _updatePoolDeserialize( +export async function _uploadNodeLogsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return uploadBatchServiceLogsResultDeserializer(result.body); } /** - * This only replaces the Pool properties specified in the request. For example, - * if the Pool has a StartTask associated with it, and a request does not specify - * a StartTask element, then the Pool keeps the existing StartTask. + * This is for gathering Azure Batch service log files in an automated fashion + * from Compute Nodes if you are experiencing an error and wish to escalate to + * Azure support. The Azure Batch service log files should be shared with Azure + * support to aid in debugging issues with the Batch service. */ -export async function updatePool( +export async function uploadNodeLogs( context: Client, poolId: string, - body: BatchPoolUpdateOptions, - options: UpdatePoolOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updatePoolSend(context, poolId, body, options); - return _updatePoolDeserialize(result); + nodeId: string, + body: UploadBatchServiceLogsOptions, + options: UploadNodeLogsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _uploadNodeLogsSend( + context, + poolId, + nodeId, + body, + options, + ); + return _uploadNodeLogsDeserialize(result); } -export function _disablePoolAutoScaleSend( +export function _getNodeRemoteDesktopFileSend( context: Client, poolId: string, - options: DisablePoolAutoScaleOptionalParams = { requestOptions: {} }, + nodeId: string, + options: GetNodeRemoteDesktopFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/disableautoscale", poolId) - .post({ + .path("/pools/{poolId}/nodes/{nodeId}/rdp", poolId, nodeId) + .get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _disablePoolAutoScaleDeserialize( +export async function _getNodeRemoteDesktopFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return typeof result.body === "string" + ? stringToUint8Array(result.body, "base64") + : result.body; } -/** Disables automatic scaling for a Pool. */ -export async function disablePoolAutoScale( +/** + * Before you can access a Compute Node by using the RDP file, you must create a + * user Account on the Compute Node. This API can only be invoked on Pools created + * with a cloud service configuration. For Pools created with a virtual machine + * configuration, see the GetRemoteLoginSettings API. + */ +export async function getNodeRemoteDesktopFile( context: Client, poolId: string, - options: DisablePoolAutoScaleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _disablePoolAutoScaleSend(context, poolId, options); - return _disablePoolAutoScaleDeserialize(result); + nodeId: string, + options: GetNodeRemoteDesktopFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getNodeRemoteDesktopFileSend( + context, + poolId, + nodeId, + options, + ); + return _getNodeRemoteDesktopFileDeserialize(result); } -export function _enablePoolAutoScaleSend( +export function _getNodeRemoteLoginSettingsSend( context: Client, poolId: string, - body: BatchPoolEnableAutoScaleOptions, - options: EnablePoolAutoScaleOptionalParams = { requestOptions: {} }, + nodeId: string, + options: GetNodeRemoteLoginSettingsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/enableautoscale", poolId) - .post({ + .path("/pools/{poolId}/nodes/{nodeId}/remoteloginsettings", poolId, nodeId) + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchPoolEnableAutoScaleOptionsSerializer(body), }); } -export async function _enablePoolAutoScaleDeserialize( +export async function _getNodeRemoteLoginSettingsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return batchNodeRemoteLoginSettingsResultDeserializer(result.body); } /** - * You cannot enable automatic scaling on a Pool if a resize operation is in - * progress on the Pool. If automatic scaling of the Pool is currently disabled, - * you must specify a valid autoscale formula as part of the request. If automatic - * scaling of the Pool is already enabled, you may specify a new autoscale formula - * and/or a new evaluation interval. You cannot call this API for the same Pool - * more than once every 30 seconds. + * Before you can remotely login to a Compute Node using the remote login + * settings, you must create a user Account on the Compute Node. This API can be + * invoked only on Pools created with the virtual machine configuration property. + * For Pools created with a cloud service configuration, see the GetRemoteDesktop + * API. */ -export async function enablePoolAutoScale( +export async function getNodeRemoteLoginSettings( context: Client, poolId: string, - body: BatchPoolEnableAutoScaleOptions, - options: EnablePoolAutoScaleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _enablePoolAutoScaleSend(context, poolId, body, options); - return _enablePoolAutoScaleDeserialize(result); + nodeId: string, + options: GetNodeRemoteLoginSettingsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getNodeRemoteLoginSettingsSend( + context, + poolId, + nodeId, + options, + ); + return _getNodeRemoteLoginSettingsDeserialize(result); } -export function _evaluatePoolAutoScaleSend( +export function _enableNodeSchedulingSend( context: Client, poolId: string, - body: BatchPoolEvaluateAutoScaleOptions, - options: EvaluatePoolAutoScaleOptionalParams = { requestOptions: {} }, + nodeId: string, + options: EnableNodeSchedulingOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/evaluateautoscale", poolId) + .path("/pools/{poolId}/nodes/{nodeId}/enablescheduling", poolId, nodeId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchPoolEvaluateAutoScaleOptionsSerializer(body), }); } -export async function _evaluatePoolAutoScaleDeserialize( +export async function _enableNodeSchedulingDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return autoScaleRunDeserializer(result.body); + return; } /** - * This API is primarily for validating an autoscale formula, as it simply returns - * the result without applying the formula to the Pool. The Pool must have auto - * scaling enabled in order to evaluate a formula. + * You can enable Task scheduling on a Compute Node only if its current scheduling + * state is disabled */ -export async function evaluatePoolAutoScale( +export async function enableNodeScheduling( context: Client, poolId: string, - body: BatchPoolEvaluateAutoScaleOptions, - options: EvaluatePoolAutoScaleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _evaluatePoolAutoScaleSend( + nodeId: string, + options: EnableNodeSchedulingOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _enableNodeSchedulingSend( context, poolId, - body, + nodeId, options, ); - return _evaluatePoolAutoScaleDeserialize(result); + return _enableNodeSchedulingDeserialize(result); } -export function _resizePoolSend( +export function _disableNodeSchedulingSend( context: Client, poolId: string, - body: BatchPoolResizeOptions, - options: ResizePoolOptionalParams = { requestOptions: {} }, + nodeId: string, + options: DisableNodeSchedulingOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/resize", poolId) + .path("/pools/{poolId}/nodes/{nodeId}/disablescheduling", poolId, nodeId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchPoolResizeOptionsSerializer(body), + body: !options["body"] + ? options["body"] + : nodeDisableSchedulingOptionsSerializer(options["body"]), }); } -export async function _resizePoolDeserialize( +export async function _disableNodeSchedulingDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -914,63 +1029,63 @@ export async function _resizePoolDeserialize( } /** - * You can only resize a Pool when its allocation state is steady. If the Pool is - * already resizing, the request fails with status code 409. When you resize a - * Pool, the Pool's allocation state changes from steady to resizing. You cannot - * resize Pools which are configured for automatic scaling. If you try to do this, - * the Batch service returns an error 409. If you resize a Pool downwards, the - * Batch service chooses which Compute Nodes to remove. To remove specific Compute - * Nodes, use the Pool remove Compute Nodes API instead. + * You can disable Task scheduling on a Compute Node only if its current + * scheduling state is enabled. */ -export async function resizePool( +export async function disableNodeScheduling( context: Client, poolId: string, - body: BatchPoolResizeOptions, - options: ResizePoolOptionalParams = { requestOptions: {} }, + nodeId: string, + options: DisableNodeSchedulingOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _resizePoolSend(context, poolId, body, options); - return _resizePoolDeserialize(result); + const result = await _disableNodeSchedulingSend( + context, + poolId, + nodeId, + options, + ); + return _disableNodeSchedulingDeserialize(result); } -export function _stopPoolResizeSend( +export function _reimageNodeSend( context: Client, poolId: string, - options: StopPoolResizeOptionalParams = { requestOptions: {} }, + nodeId: string, + options: ReimageNodeOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/stopresize", poolId) + .path("/pools/{poolId}/nodes/{nodeId}/reimage", poolId, nodeId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: !options["body"] + ? options["body"] + : nodeReimageOptionsSerializer(options["body"]), }); } -export async function _stopPoolResizeDeserialize( +export async function _reimageNodeDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["202"]; @@ -982,48 +1097,62 @@ export async function _stopPoolResizeDeserialize( } /** - * This does not restore the Pool to its previous state before the resize - * operation: it only stops any further changes being made, and the Pool maintains - * its current state. After stopping, the Pool stabilizes at the number of Compute - * Nodes it was at when the stop operation was done. During the stop operation, - * the Pool allocation state changes first to stopping and then to steady. A - * resize operation need not be an explicit resize Pool request; this API can also - * be used to halt the initial sizing of the Pool when it is created. + * You can reinstall the operating system on a Compute Node only if it is in an + * idle or running state. This API can be invoked only on Pools created with the + * cloud service configuration property. */ -export async function stopPoolResize( +export async function reimageNode( context: Client, poolId: string, - options: StopPoolResizeOptionalParams = { requestOptions: {} }, + nodeId: string, + options: ReimageNodeOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopPoolResizeSend(context, poolId, options); - return _stopPoolResizeDeserialize(result); + const result = await _reimageNodeSend(context, poolId, nodeId, options); + return _reimageNodeDeserialize(result); } -export function _replacePoolPropertiesSend( +export function _rebootNodeSend( context: Client, poolId: string, - body: BatchPoolReplaceOptions, - options: ReplacePoolPropertiesOptionalParams = { requestOptions: {} }, + nodeId: string, + options: RebootNodeOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/updateproperties", poolId) + .path("/pools/{poolId}/nodes/{nodeId}/reboot", poolId, nodeId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchPoolReplaceOptionsSerializer(body), + body: !options["body"] + ? options["body"] + : nodeRebootOptionsSerializer(options["body"]), }); } -export async function _replacePoolPropertiesDeserialize( +export async function _rebootNodeDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -1031,73 +1160,123 @@ export async function _replacePoolPropertiesDeserialize( return; } -/** - * This fully replaces all the updatable properties of the Pool. For example, if - * the Pool has a StartTask associated with it and if StartTask is not specified - * with this request, then the Batch service will remove the existing StartTask. - */ -export async function replacePoolProperties( +/** You can restart a Compute Node only if it is in an idle or running state. */ +export async function rebootNode( context: Client, poolId: string, - body: BatchPoolReplaceOptions, - options: ReplacePoolPropertiesOptionalParams = { requestOptions: {} }, + nodeId: string, + options: RebootNodeOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _replacePoolPropertiesSend( - context, - poolId, - body, - options, - ); - return _replacePoolPropertiesDeserialize(result); + const result = await _rebootNodeSend(context, poolId, nodeId, options); + return _rebootNodeDeserialize(result); } -export function _removeNodesSend( +export function _getNodeSend( context: Client, poolId: string, - body: NodeRemoveOptions, - options: RemoveNodesOptionalParams = { requestOptions: {} }, + nodeId: string, + options: GetNodeOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _getNodeDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return batchNodeDeserializer(result.body); +} + +/** Gets information about the specified Compute Node. */ +export async function getNode( + context: Client, + poolId: string, + nodeId: string, + options: GetNodeOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getNodeSend(context, poolId, nodeId, options); + return _getNodeDeserialize(result); +} + +export function _replaceNodeUserSend( + context: Client, + poolId: string, + nodeId: string, + userName: string, + body: BatchNodeUserUpdateOptions, + options: ReplaceNodeUserOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/removenodes", poolId) - .post({ + .path( + "/pools/{poolId}/nodes/{nodeId}/users/{userName}", + poolId, + nodeId, + userName, + ) + .put({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: nodeRemoveOptionsSerializer(body), + body: batchNodeUserUpdateOptionsSerializer(body), }); } -export async function _removeNodesDeserialize( +export async function _replaceNodeUserDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -1106,261 +1285,264 @@ export async function _removeNodesDeserialize( } /** - * This operation can only run when the allocation state of the Pool is steady. - * When this operation runs, the allocation state changes from steady to resizing. - * Each request may remove up to 100 nodes. + * This operation replaces of all the updatable properties of the Account. For + * example, if the expiryTime element is not specified, the current value is + * replaced with the default value, not left unmodified. You can update a user + * Account on a Compute Node only when it is in the idle or running state. */ -export async function removeNodes( +export async function replaceNodeUser( context: Client, poolId: string, - body: NodeRemoveOptions, - options: RemoveNodesOptionalParams = { requestOptions: {} }, + nodeId: string, + userName: string, + body: BatchNodeUserUpdateOptions, + options: ReplaceNodeUserOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _removeNodesSend(context, poolId, body, options); - return _removeNodesDeserialize(result); + const result = await _replaceNodeUserSend( + context, + poolId, + nodeId, + userName, + body, + options, + ); + return _replaceNodeUserDeserialize(result); } -export function _listSupportedImagesSend( +export function _deleteNodeUserSend( context: Client, - options: ListSupportedImagesOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + userName: string, + options: DeleteNodeUserOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/supportedimages") - .get({ + .path( + "/pools/{poolId}/nodes/{nodeId}/users/{userName}", + poolId, + nodeId, + userName, + ) + .delete({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - maxresults: options?.maxresults, + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, }, }); } -export async function _listSupportedImagesDeserialize( +export async function _deleteNodeUserDeserialize( result: PathUncheckedResponse, -): Promise<_AccountListSupportedImagesResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _accountListSupportedImagesResultDeserializer(result.body); + return; } -/** Lists all Virtual Machine Images supported by the Azure Batch service. */ -export function listSupportedImages( +/** + * You can delete a user Account to a Compute Node only when it is in the idle or + * running state. + */ +export async function deleteNodeUser( context: Client, - options: ListSupportedImagesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + poolId: string, + nodeId: string, + userName: string, + options: DeleteNodeUserOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteNodeUserSend( context, - () => _listSupportedImagesSend(context, options), - _listSupportedImagesDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, + poolId, + nodeId, + userName, + options, ); + return _deleteNodeUserDeserialize(result); } -export function _listPoolNodeCountsSend( +export function _createNodeUserSend( context: Client, - options: ListPoolNodeCountsOptionalParams = { requestOptions: {} }, + poolId: string, + nodeId: string, + body: BatchNodeUserCreateOptions, + options: CreateNodeUserOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/nodecounts") - .get({ + .path("/pools/{poolId}/nodes/{nodeId}/users", poolId, nodeId) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, }, + body: batchNodeUserCreateOptionsSerializer(body), }); } -export async function _listPoolNodeCountsDeserialize( +export async function _createNodeUserDeserialize( result: PathUncheckedResponse, -): Promise<_PoolNodeCountsListResult> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _poolNodeCountsListResultDeserializer(result.body); + return; } /** - * Gets the number of Compute Nodes in each state, grouped by Pool. Note that the - * numbers returned may not always be up to date. If you need exact node counts, - * use a list query. + * You can add a user Account to a Compute Node only when it is in the idle or + * running state. */ -export function listPoolNodeCounts( +export async function createNodeUser( context: Client, - options: ListPoolNodeCountsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + poolId: string, + nodeId: string, + body: BatchNodeUserCreateOptions, + options: CreateNodeUserOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createNodeUserSend( context, - () => _listPoolNodeCountsSend(context, options), - _listPoolNodeCountsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, + poolId, + nodeId, + body, + options, ); + return _createNodeUserDeserialize(result); } -export function _deleteJobSend( +export function _listTaskFilesSend( context: Client, jobId: string, - options: DeleteJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: ListTaskFilesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}", jobId) - .delete({ + .path("/jobs/{jobId}/tasks/{taskId}/files", jobId, taskId) + .get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), - } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + recursive: options?.recursive, }, }); } -export async function _deleteJobDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["202"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return; -} - -/** - * Deleting a Job also deletes all Tasks that are part of that Job, and all Job - * statistics. This also overrides the retention period for Task data; that is, if - * the Job contains Tasks which are still retained on Compute Nodes, the Batch - * services deletes those Tasks' working directories and all their contents. When - * a Delete Job request is received, the Batch service sets the Job to the - * deleting state. All update operations on a Job that is in deleting state will - * fail with status code 409 (Conflict), with additional information indicating - * that the Job is being deleted. - */ -export async function deleteJob( - context: Client, - jobId: string, - options: DeleteJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteJobSend(context, jobId, options); - return _deleteJobDeserialize(result); -} - -export function _getJobSend( - context: Client, - jobId: string, - options: GetJobOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/jobs/{jobId}", jobId).get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), - } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _getJobDeserialize( +export async function _listTaskFilesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_NodeFileListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return batchJobDeserializer(result.body); + return _nodeFileListResultDeserializer(result.body); } -/** Gets information about the specified Job. */ -export async function getJob( +/** Lists the files in a Task's directory on its Compute Node. */ +export function listTaskFiles( context: Client, jobId: string, - options: GetJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getJobSend(context, jobId, options); - return _getJobDeserialize(result); + taskId: string, + options: ListTaskFilesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTaskFilesSend(context, jobId, taskId, options), + _listTaskFilesDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); } -export function _updateJobSend( +export function _getTaskFilePropertiesSend( context: Client, jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: GetTaskFilePropertiesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}", jobId) - .patch({ + .path( + "/jobs/{jobId}/tasks/{taskId}/files/{filePath}", + jobId, + taskId, + filePath, + ) + .head({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } : {}), ...(options?.ifModifiedSince !== undefined ? { @@ -1376,16 +1558,17 @@ export function _updateJobSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchJobUpdateOptionsSerializer(body), }); } -export async function _updateJobDeserialize( +export async function _getTaskFilePropertiesDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -1396,40 +1579,53 @@ export async function _updateJobDeserialize( return; } -/** - * This replaces only the Job properties specified in the request. For example, if - * the Job has constraints, and a request does not specify the constraints - * element, then the Job keeps the existing constraints. - */ -export async function updateJob( +/** Gets the properties of the specified Task file. */ +export async function getTaskFileProperties( context: Client, jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: GetTaskFilePropertiesOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _updateJobSend(context, jobId, body, options); - return _updateJobDeserialize(result); + const result = await _getTaskFilePropertiesSend( + context, + jobId, + taskId, + filePath, + options, + ); + return _getTaskFilePropertiesDeserialize(result); } -export function _replaceJobSend( +export function _getTaskFileSend( context: Client, jobId: string, - body: BatchJob, - options: ReplaceJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: GetTaskFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}", jobId) - .put({ + .path( + "/jobs/{jobId}/tasks/{taskId}/files/{filePath}", + jobId, + taskId, + filePath, + ) + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } : {}), ...(options?.ifModifiedSince !== undefined ? { @@ -1445,88 +1641,93 @@ export function _replaceJobSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + ...(options?.ocpRange !== undefined + ? { "ocp-range": options?.ocpRange } + : {}), + accept: "application/octet-stream", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchJobSerializer(body), }); } -export async function _replaceJobDeserialize( +export async function _getTaskFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return result.body; } -/** - * This fully replaces all the updatable properties of the Job. For example, if - * the Job has constraints associated with it and if constraints is not specified - * with this request, then the Batch service will remove the existing constraints. - */ -export async function replaceJob( +/** Returns the content of the specified Task file. */ +export async function getTaskFile( context: Client, jobId: string, - body: BatchJob, - options: ReplaceJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _replaceJobSend(context, jobId, body, options); - return _replaceJobDeserialize(result); + taskId: string, + filePath: string, + options: GetTaskFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTaskFileSend( + context, + jobId, + taskId, + filePath, + options, + ); + return _getTaskFileDeserialize(result); } -export function _disableJobSend( +export function _deleteTaskFileSend( context: Client, jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: DeleteTaskFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/disable", jobId) - .post({ + .path( + "/jobs/{jobId}/tasks/{taskId}/files/{filePath}", + jobId, + taskId, + filePath, + ) + .delete({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, + recursive: options?.recursive, }, - body: batchJobDisableOptionsSerializer(body), }); } -export async function _disableJobDeserialize( +export async function _deleteTaskFileDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -1534,36 +1735,48 @@ export async function _disableJobDeserialize( return; } -/** - * The Batch Service immediately moves the Job to the disabling state. Batch then - * uses the disableTasks parameter to determine what to do with the currently - * running Tasks of the Job. The Job remains in the disabling state until the - * disable operation is completed and all Tasks have been dealt with according to - * the disableTasks option; the Job then moves to the disabled state. No new Tasks - * are started under the Job until it moves back to active state. If you try to - * disable a Job that is in any state other than active, disabling, or disabled, - * the request fails with status code 409. - */ -export async function disableJob( +/** Deletes the specified Task file from the Compute Node where the Task ran. */ +export async function deleteTaskFile( context: Client, jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: DeleteTaskFileOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _disableJobSend(context, jobId, body, options); - return _disableJobDeserialize(result); + const result = await _deleteTaskFileSend( + context, + jobId, + taskId, + filePath, + options, + ); + return _deleteTaskFileDeserialize(result); } -export function _enableJobSend( +export function _reactivateTaskSend( context: Client, jobId: string, - options: EnableJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: ReactivateTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/enable", jobId) + .path("/jobs/{jobId}/tasks/{taskId}/reactivate", jobId, taskId) .post({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -1584,18 +1797,20 @@ export function _enableJobSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _enableJobDeserialize( +export async function _reactivateTaskDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -1604,35 +1819,48 @@ export async function _enableJobDeserialize( } /** - * When you call this API, the Batch service sets a disabled Job to the enabling - * state. After the this operation is completed, the Job moves to the active - * state, and scheduling of new Tasks under the Job resumes. The Batch service - * does not allow a Task to remain in the active state for more than 180 days. - * Therefore, if you enable a Job containing active Tasks which were added more - * than 180 days ago, those Tasks will not run. + * Reactivation makes a Task eligible to be retried again up to its maximum retry + * count. The Task's state is changed to active. As the Task is no longer in the + * completed state, any previous exit code or failure information is no longer + * available after reactivation. Each time a Task is reactivated, its retry count + * is reset to 0. Reactivation will fail for Tasks that are not completed or that + * previously completed successfully (with an exit code of 0). Additionally, it + * will fail if the Job has completed (or is terminating or deleting). */ -export async function enableJob( +export async function reactivateTask( context: Client, jobId: string, - options: EnableJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: ReactivateTaskOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _enableJobSend(context, jobId, options); - return _enableJobDeserialize(result); + const result = await _reactivateTaskSend(context, jobId, taskId, options); + return _reactivateTaskDeserialize(result); } -export function _terminateJobSend( +export function _terminateTaskSend( context: Client, jobId: string, - options: TerminateJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: TerminateTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/terminate", jobId) + .path("/jobs/{jobId}/tasks/{taskId}/terminate", jobId, taskId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -1653,21 +1881,20 @@ export function _terminateJobSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: !options["body"] - ? options["body"] - : batchJobTerminateOptionsSerializer(options["body"]), }); } -export async function _terminateJobDeserialize( +export async function _terminateTaskDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -1676,135 +1903,209 @@ export async function _terminateJobDeserialize( } /** - * When a Terminate Job request is received, the Batch service sets the Job to the - * terminating state. The Batch service then terminates any running Tasks - * associated with the Job and runs any required Job release Tasks. Then the Job - * moves into the completed state. If there are any Tasks in the Job in the active - * state, they will remain in the active state. Once a Job is terminated, new - * Tasks cannot be added and any remaining active Tasks will not be scheduled. + * When the Task has been terminated, it moves to the completed state. For + * multi-instance Tasks, the terminate Task operation applies synchronously to the + * primary task; subtasks are then terminated asynchronously in the background. */ -export async function terminateJob( +export async function terminateTask( context: Client, jobId: string, - options: TerminateJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: TerminateTaskOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _terminateJobSend(context, jobId, options); - return _terminateJobDeserialize(result); + const result = await _terminateTaskSend(context, jobId, taskId, options); + return _terminateTaskDeserialize(result); } -export function _createJobSend( +export function _listSubTasksSend( context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptionalParams = { requestOptions: {} }, + jobId: string, + taskId: string, + options: ListSubTasksOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs") - .post({ + .path("/jobs/{jobId}/tasks/{taskId}/subtasksinfo", jobId, taskId) + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, - body: batchJobCreateOptionsSerializer(body), }); } -export async function _createJobDeserialize( +export async function _listSubTasksDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return batchTaskListSubtasksResultDeserializer(result.body); } -/** - * The Batch service supports two ways to control the work done as part of a Job. - * In the first approach, the user specifies a Job Manager Task. The Batch service - * launches this Task when it is ready to start the Job. The Job Manager Task - * controls all other Tasks that run under this Job, by using the Task APIs. In - * the second approach, the user directly controls the execution of Tasks under an - * active Job, by using the Task APIs. Also note: when naming Jobs, avoid - * including sensitive information such as user names or secret project names. - * This information may appear in telemetry logs accessible to Microsoft Support - * engineers. - */ -export async function createJob( +/** If the Task is not a multi-instance Task then this returns an empty collection. */ +export async function listSubTasks( context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createJobSend(context, body, options); - return _createJobDeserialize(result); + jobId: string, + taskId: string, + options: ListSubTasksOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSubTasksSend(context, jobId, taskId, options); + return _listSubTasksDeserialize(result); } -export function _listJobsSend( +export function _replaceTaskSend( context: Client, - options: ListJobsOptionalParams = { requestOptions: {} }, + jobId: string, + taskId: string, + body: BatchTask, + options: ReplaceTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/jobs").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _listJobsDeserialize( - result: PathUncheckedResponse, -): Promise<_BatchJobListResult> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return _batchJobListResultDeserializer(result.body); -} + return context + .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) + .put({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, + }, + body: batchTaskSerializer(body), + }); +} -/** Lists all of the Jobs in the specified Account. */ -export function listJobs( +export async function _replaceTaskDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return; +} + +/** Updates the properties of the specified Task. */ +export async function replaceTask( context: Client, - options: ListJobsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listJobsSend(context, options), - _listJobsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); + jobId: string, + taskId: string, + body: BatchTask, + options: ReplaceTaskOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _replaceTaskSend(context, jobId, taskId, body, options); + return _replaceTaskDeserialize(result); } -export function _listJobsFromScheduleSend( +export function _getTaskSend( context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, + jobId: string, + taskId: string, + options: GetTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId).get({ + return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, $select: !options?.$select ? options?.$select : options?.$select.map((p: any) => { @@ -1819,156 +2120,302 @@ export function _listJobsFromScheduleSend( }); } -export async function _listJobsFromScheduleDeserialize( +export async function _getTaskDeserialize( result: PathUncheckedResponse, -): Promise<_BatchJobListResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _batchJobListResultDeserializer(result.body); + return batchTaskDeserializer(result.body); } -/** Lists the Jobs that have been created under the specified Job Schedule. */ -export function listJobsFromSchedule( +/** + * For multi-instance Tasks, information such as affinityId, executionInfo and + * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve + * information about subtasks. + */ +export async function getTask( context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listJobsFromScheduleSend(context, jobScheduleId, options), - _listJobsFromScheduleDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); + jobId: string, + taskId: string, + options: GetTaskOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTaskSend(context, jobId, taskId, options); + return _getTaskDeserialize(result); } -export function _listJobPreparationAndReleaseTaskStatusSend( +export function _deleteTaskSend( context: Client, jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { - requestOptions: {}, - }, + taskId: string, + options: DeleteTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) - .get({ + .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) + .delete({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - maxresults: options?.maxresults, + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), }, }); } -export async function _listJobPreparationAndReleaseTaskStatusDeserialize( +export async function _deleteTaskDeserialize( result: PathUncheckedResponse, -): Promise<_BatchJobListPreparationAndReleaseTaskStatusResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _batchJobListPreparationAndReleaseTaskStatusResultDeserializer( - result.body, - ); + return; } /** - * This API returns the Job Preparation and Job Release Task status on all Compute - * Nodes that have run the Job Preparation or Job Release Task. This includes - * Compute Nodes which have since been removed from the Pool. If this API is - * invoked on a Job which has no Job Preparation or Job Release Task, the Batch - * service returns HTTP status code 409 (Conflict) with an error code of - * JobPreparationTaskNotSpecified. + * When a Task is deleted, all of the files in its directory on the Compute Node + * where it ran are also deleted (regardless of the retention time). For + * multi-instance Tasks, the delete Task operation applies synchronously to the + * primary task; subtasks and their files are then deleted asynchronously in the + * background. */ -export function listJobPreparationAndReleaseTaskStatus( +export async function deleteTask( context: Client, jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { - requestOptions: {}, - }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listJobPreparationAndReleaseTaskStatusSend(context, jobId, options), - _listJobPreparationAndReleaseTaskStatusDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); + taskId: string, + options: DeleteTaskOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTaskSend(context, jobId, taskId, options); + return _deleteTaskDeserialize(result); } -export function _getJobTaskCountsSend( +export function _createTaskCollectionSend( context: Client, jobId: string, - options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, + collection: BatchTaskCollection, + options: CreateTaskCollectionOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/taskcounts", jobId) - .get({ + .path("/jobs/{jobId}/addtaskcollection", jobId) + .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchTaskCollectionSerializer(collection), }); } -export async function _getJobTaskCountsDeserialize( +export async function _createTaskCollectionDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return taskCountsResultDeserializer(result.body); + return taskAddCollectionResultDeserializer(result.body); } /** - * Task counts provide a count of the Tasks by active, running or completed Task - * state, and a count of Tasks which succeeded or failed. Tasks in the preparing - * state are counted as running. Note that the numbers returned may not always be - * up to date. If you need exact task counts, use a list query. - */ -export async function getJobTaskCounts( - context: Client, - jobId: string, - options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getJobTaskCountsSend(context, jobId, options); - return _getJobTaskCountsDeserialize(result); -} - -export function _createCertificateSend( + * Note that each Task must have a unique ID. The Batch service may not return the + * results for each Task in the same order the Tasks were submitted in this + * request. If the server times out or the connection is closed during the + * request, the request may have been partially or fully processed, or not at all. + * In such cases, the user should re-issue the request. Note that it is up to the + * user to correctly handle failures when re-issuing a request. For example, you + * should use the same Task IDs during a retry so that if the prior operation + * succeeded, the retry will not create extra Tasks unexpectedly. If the response + * contains any Tasks which failed to add, a client can retry the request. In a + * retry, it is most efficient to resubmit only Tasks that failed to add, and to + * omit Tasks that were successfully added on the first attempt. The maximum + * lifetime of a Task from addition to completion is 180 days. If a Task has not + * completed within 180 days of being added it will be terminated by the Batch + * service and left in whatever state it was in at that time. + */ +export async function createTaskCollection( context: Client, - body: BatchCertificate, - options: CreateCertificateOptionalParams = { requestOptions: {} }, + jobId: string, + collection: BatchTaskCollection, + options: CreateTaskCollectionOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createTaskCollectionSend( + context, + jobId, + collection, + options, + ); + return _createTaskCollectionDeserialize(result); +} + +export function _listTasksSend( + context: Client, + jobId: string, + options: ListTasksOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/jobs/{jobId}/tasks", jobId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _listTasksDeserialize( + result: PathUncheckedResponse, +): Promise<_BatchTaskListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _batchTaskListResultDeserializer(result.body); +} + +/** + * For multi-instance Tasks, information such as affinityId, executionInfo and + * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve + * information about subtasks. + */ +export function listTasks( + context: Client, + jobId: string, + options: ListTasksOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTasksSend(context, jobId, options), + _listTasksDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _createTaskSend( + context: Client, + jobId: string, + body: BatchTaskCreateOptions, + options: CreateTaskOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/certificates") + .path("/jobs/{jobId}/tasks", jobId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchCertificateSerializer(body), + body: batchTaskCreateOptionsSerializer(body), }); } -export async function _createCertificateDeserialize( +export async function _createTaskDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["201"]; @@ -1979,24 +2426,46 @@ export async function _createCertificateDeserialize( return; } -/** Creates a Certificate to the specified Account. */ -export async function createCertificate( +/** + * The maximum lifetime of a Task from addition to completion is 180 days. If a + * Task has not completed within 180 days of being added it will be terminated by + * the Batch service and left in whatever state it was in at that time. + */ +export async function createTask( context: Client, - body: BatchCertificate, - options: CreateCertificateOptionalParams = { requestOptions: {} }, + jobId: string, + body: BatchTaskCreateOptions, + options: CreateTaskOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createCertificateSend(context, body, options); - return _createCertificateDeserialize(result); + const result = await _createTaskSend(context, jobId, body, options); + return _createTaskDeserialize(result); } -export function _listCertificatesSend( +export function _listJobSchedulesSend( context: Client, - options: ListCertificatesOptionalParams = { requestOptions: {} }, + options: ListJobSchedulesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/certificates").get({ + return context.path("/jobschedules").get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, $filter: options?.$filter, @@ -2005,60 +2474,79 @@ export function _listCertificatesSend( : options?.$select.map((p: any) => { return p; }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), }, }); } -export async function _listCertificatesDeserialize( +export async function _listJobSchedulesDeserialize( result: PathUncheckedResponse, -): Promise<_CertificateListResult> { +): Promise<_BatchJobScheduleListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _certificateListResultDeserializer(result.body); + return _batchJobScheduleListResultDeserializer(result.body); } -/** Lists all of the Certificates that have been added to the specified Account. */ -export function listCertificates( +/** Lists all of the Job Schedules in the specified Account. */ +export function listJobSchedules( context: Client, - options: ListCertificatesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: ListJobSchedulesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listCertificatesSend(context, options), - _listCertificatesDeserialize, + () => _listJobSchedulesSend(context, options), + _listJobSchedulesDeserialize, ["200"], { itemName: "value", nextLinkName: "odata.nextLink" }, ); } -export function _cancelCertificateDeletionSend( +export function _createJobScheduleSend( context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, + body: BatchJobScheduleCreateOptions, + options: CreateJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", - thumbprintAlgorithm, - thumbprint, - ) + .path("/jobschedules") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchJobScheduleCreateOptionsSerializer(body), }); } -export async function _cancelCertificateDeletionDeserialize( +export async function _createJobScheduleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2066,151 +2554,39 @@ export async function _cancelCertificateDeletionDeserialize( return; } -/** - * If you try to delete a Certificate that is being used by a Pool or Compute - * Node, the status of the Certificate changes to deleteFailed. If you decide that - * you want to continue using the Certificate, you can use this operation to set - * the status of the Certificate back to active. If you intend to delete the - * Certificate, you do not need to run this operation after the deletion failed. - * You must make sure that the Certificate is not being used by any resources, and - * then you can try again to delete the Certificate. - */ -export async function cancelCertificateDeletion( +/** Creates a Job Schedule to the specified Account. */ +export async function createJobSchedule( context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, + body: BatchJobScheduleCreateOptions, + options: CreateJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _cancelCertificateDeletionSend( - context, - thumbprintAlgorithm, - thumbprint, - options, - ); - return _cancelCertificateDeletionDeserialize(result); + const result = await _createJobScheduleSend(context, body, options); + return _createJobScheduleDeserialize(result); } -export function _deleteCertificateSend( +export function _terminateJobScheduleSend( context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptionalParams = { requestOptions: {} }, + jobScheduleId: string, + options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint, - ) - .delete({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - }); -} - -export async function _deleteCertificateDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["202"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return; -} - -/** - * You cannot delete a Certificate if a resource (Pool or Compute Node) is using - * it. Before you can delete a Certificate, you must therefore make sure that the - * Certificate is not associated with any existing Pools, the Certificate is not - * installed on any Nodes (even if you remove a Certificate from a Pool, it is not - * removed from existing Compute Nodes in that Pool until they restart), and no - * running Tasks depend on the Certificate. If you try to delete a Certificate - * that is in use, the deletion fails. The Certificate status changes to - * deleteFailed. You can use Cancel Delete Certificate to set the status back to - * active if you decide that you want to continue using the Certificate. - */ -export async function deleteCertificate( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options, - ); - return _deleteCertificateDeserialize(result); -} - -export function _getCertificateSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint, - ) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _getCertificateDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return batchCertificateDeserializer(result.body); -} - -/** Gets information about the specified Certificate. */ -export async function getCertificate( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options, - ); - return _getCertificateDeserialize(result); -} - -export function _jobScheduleExistsSend( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .head({ + .path("/jobschedules/{jobScheduleId}/terminate", jobScheduleId) + .post({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -2231,18 +2607,20 @@ export function _jobScheduleExistsSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _jobScheduleExistsDeserialize( +export async function _terminateJobScheduleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200", "404"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2250,26 +2628,43 @@ export async function _jobScheduleExistsDeserialize( return; } -/** Checks the specified Job Schedule exists. */ -export async function jobScheduleExists( +/** Terminates a Job Schedule. */ +export async function terminateJobSchedule( context: Client, jobScheduleId: string, - options: JobScheduleExistsOptionalParams = { requestOptions: {} }, + options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _jobScheduleExistsSend(context, jobScheduleId, options); - return _jobScheduleExistsDeserialize(result); + const result = await _terminateJobScheduleSend( + context, + jobScheduleId, + options, + ); + return _terminateJobScheduleDeserialize(result); } -export function _deleteJobScheduleSend( +export function _enableJobScheduleSend( context: Client, jobScheduleId: string, - options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, + options: EnableJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .delete({ + .path("/jobschedules/{jobScheduleId}/enable", jobScheduleId) + .post({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -2290,18 +2685,20 @@ export function _deleteJobScheduleSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _deleteJobScheduleDeserialize( +export async function _enableJobScheduleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2309,103 +2706,39 @@ export async function _deleteJobScheduleDeserialize( return; } -/** - * When you delete a Job Schedule, this also deletes all Jobs and Tasks under that - * schedule. When Tasks are deleted, all the files in their working directories on - * the Compute Nodes are also deleted (the retention period is ignored). The Job - * Schedule statistics are no longer accessible once the Job Schedule is deleted, - * though they are still counted towards Account lifetime statistics. - */ -export async function deleteJobSchedule( +/** Enables a Job Schedule. */ +export async function enableJobSchedule( context: Client, jobScheduleId: string, - options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, + options: EnableJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _deleteJobScheduleSend(context, jobScheduleId, options); - return _deleteJobScheduleDeserialize(result); -} - -export function _getJobScheduleSend( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).get({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), - } - : {}), - }, - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _getJobScheduleDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return batchJobScheduleDeserializer(result.body); -} - -/** Gets information about the specified Job Schedule. */ -export async function getJobSchedule( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getJobScheduleSend(context, jobScheduleId, options); - return _getJobScheduleDeserialize(result); + const result = await _enableJobScheduleSend(context, jobScheduleId, options); + return _enableJobScheduleDeserialize(result); } -export function _updateJobScheduleSend( +export function _disableJobScheduleSend( context: Client, jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, + options: DisableJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .patch({ + .path("/jobschedules/{jobScheduleId}/disable", jobScheduleId) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -2426,19 +2759,20 @@ export function _updateJobScheduleSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchJobScheduleUpdateOptionsSerializer(body), }); } -export async function _updateJobScheduleDeserialize( +export async function _disableJobScheduleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2446,26 +2780,14 @@ export async function _updateJobScheduleDeserialize( return; } -/** - * This replaces only the Job Schedule properties specified in the request. For - * example, if the schedule property is not specified with this request, then the - * Batch service will keep the existing schedule. Changes to a Job Schedule only - * impact Jobs created by the schedule after the update has taken place; currently - * running Jobs are unaffected. - */ -export async function updateJobSchedule( +/** No new Jobs will be created until the Job Schedule is enabled again. */ +export async function disableJobSchedule( context: Client, jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, + options: DisableJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _updateJobScheduleSend( - context, - jobScheduleId, - body, - options, - ); - return _updateJobScheduleDeserialize(result); + const result = await _disableJobScheduleSend(context, jobScheduleId, options); + return _disableJobScheduleDeserialize(result); } export function _replaceJobScheduleSend( @@ -2478,10 +2800,21 @@ export function _replaceJobScheduleSend( .path("/jobschedules/{jobScheduleId}", jobScheduleId) .put({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -2502,9 +2835,11 @@ export function _replaceJobScheduleSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, body: batchJobScheduleSerializer(body), @@ -2544,17 +2879,32 @@ export async function replaceJobSchedule( return _replaceJobScheduleDeserialize(result); } -export function _disableJobScheduleSend( +export function _updateJobScheduleSend( context: Client, jobScheduleId: string, - options: DisableJobScheduleOptionalParams = { requestOptions: {} }, + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobschedules/{jobScheduleId}/disable", jobScheduleId) - .post({ + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .patch({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", headers: { - ...(options?.ifMatch !== undefined + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), ...(options?.ifNoneMatch !== undefined @@ -2574,18 +2924,21 @@ export function _disableJobScheduleSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchJobScheduleUpdateOptionsSerializer(body), }); } -export async function _disableJobScheduleDeserialize( +export async function _updateJobScheduleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2593,26 +2946,133 @@ export async function _disableJobScheduleDeserialize( return; } -/** No new Jobs will be created until the Job Schedule is enabled again. */ -export async function disableJobSchedule( +/** + * This replaces only the Job Schedule properties specified in the request. For + * example, if the schedule property is not specified with this request, then the + * Batch service will keep the existing schedule. Changes to a Job Schedule only + * impact Jobs created by the schedule after the update has taken place; currently + * running Jobs are unaffected. + */ +export async function updateJobSchedule( context: Client, jobScheduleId: string, - options: DisableJobScheduleOptionalParams = { requestOptions: {} }, + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _disableJobScheduleSend(context, jobScheduleId, options); - return _disableJobScheduleDeserialize(result); + const result = await _updateJobScheduleSend( + context, + jobScheduleId, + body, + options, + ); + return _updateJobScheduleDeserialize(result); } -export function _enableJobScheduleSend( +export function _getJobScheduleSend( context: Client, jobScheduleId: string, - options: EnableJobScheduleOptionalParams = { requestOptions: {} }, + options: GetJobScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _getJobScheduleDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return batchJobScheduleDeserializer(result.body); +} + +/** Gets information about the specified Job Schedule. */ +export async function getJobSchedule( + context: Client, + jobScheduleId: string, + options: GetJobScheduleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getJobScheduleSend(context, jobScheduleId, options); + return _getJobScheduleDeserialize(result); +} + +export function _deleteJobScheduleSend( + context: Client, + jobScheduleId: string, + options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobschedules/{jobScheduleId}/enable", jobScheduleId) - .post({ + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .delete({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -2633,18 +3093,20 @@ export function _enableJobScheduleSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _enableJobScheduleDeserialize( +export async function _deleteJobScheduleDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2652,26 +3114,45 @@ export async function _enableJobScheduleDeserialize( return; } -/** Enables a Job Schedule. */ -export async function enableJobSchedule( +/** + * When you delete a Job Schedule, this also deletes all Jobs and Tasks under that + * schedule. When Tasks are deleted, all the files in their working directories on + * the Compute Nodes are also deleted (the retention period is ignored). The Job + * Schedule statistics are no longer accessible once the Job Schedule is deleted, + * though they are still counted towards Account lifetime statistics. + */ +export async function deleteJobSchedule( context: Client, jobScheduleId: string, - options: EnableJobScheduleOptionalParams = { requestOptions: {} }, + options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _enableJobScheduleSend(context, jobScheduleId, options); - return _enableJobScheduleDeserialize(result); + const result = await _deleteJobScheduleSend(context, jobScheduleId, options); + return _deleteJobScheduleDeserialize(result); } -export function _terminateJobScheduleSend( +export function _jobScheduleExistsSend( context: Client, jobScheduleId: string, - options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, + options: JobScheduleExistsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobschedules/{jobScheduleId}/terminate", jobScheduleId) - .post({ + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .head({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -2692,18 +3173,20 @@ export function _terminateJobScheduleSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _terminateJobScheduleDeserialize( +export async function _jobScheduleExistsDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["202"]; + const expectedStatuses = ["200", "404"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2711,136 +3194,203 @@ export async function _terminateJobScheduleDeserialize( return; } -/** Terminates a Job Schedule. */ -export async function terminateJobSchedule( +/** Checks the specified Job Schedule exists. */ +export async function jobScheduleExists( context: Client, jobScheduleId: string, - options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, + options: JobScheduleExistsOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _terminateJobScheduleSend( - context, - jobScheduleId, - options, - ); - return _terminateJobScheduleDeserialize(result); + const result = await _jobScheduleExistsSend(context, jobScheduleId, options); + return _jobScheduleExistsDeserialize(result); } -export function _createJobScheduleSend( +export function _getCertificateSend( context: Client, - body: BatchJobScheduleCreateOptions, - options: CreateJobScheduleOptionalParams = { requestOptions: {} }, + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobschedules") - .post({ + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint, + ) + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), }, - body: batchJobScheduleCreateOptionsSerializer(body), }); } -export async function _createJobScheduleDeserialize( +export async function _getCertificateDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return batchCertificateDeserializer(result.body); } -/** Creates a Job Schedule to the specified Account. */ -export async function createJobSchedule( +/** Gets information about the specified Certificate. */ +export async function getCertificate( context: Client, - body: BatchJobScheduleCreateOptions, - options: CreateJobScheduleOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createJobScheduleSend(context, body, options); - return _createJobScheduleDeserialize(result); + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getCertificateSend( + context, + thumbprintAlgorithm, + thumbprint, + options, + ); + return _getCertificateDeserialize(result); } -export function _listJobSchedulesSend( +export function _deleteCertificateSend( context: Client, - options: ListJobSchedulesOptionalParams = { requestOptions: {} }, + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/jobschedules").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, - timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _listJobSchedulesDeserialize( - result: PathUncheckedResponse, -): Promise<_BatchJobScheduleListResult> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint, + ) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, + }, + }); +} + +export async function _deleteCertificateDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); } - return _batchJobScheduleListResultDeserializer(result.body); + return; } -/** Lists all of the Job Schedules in the specified Account. */ -export function listJobSchedules( +/** + * You cannot delete a Certificate if a resource (Pool or Compute Node) is using + * it. Before you can delete a Certificate, you must therefore make sure that the + * Certificate is not associated with any existing Pools, the Certificate is not + * installed on any Nodes (even if you remove a Certificate from a Pool, it is not + * removed from existing Compute Nodes in that Pool until they restart), and no + * running Tasks depend on the Certificate. If you try to delete a Certificate + * that is in use, the deletion fails. The Certificate status changes to + * deleteFailed. You can use Cancel Delete Certificate to set the status back to + * active if you decide that you want to continue using the Certificate. + */ +export async function deleteCertificate( context: Client, - options: ListJobSchedulesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteCertificateSend( context, - () => _listJobSchedulesSend(context, options), - _listJobSchedulesDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, + thumbprintAlgorithm, + thumbprint, + options, ); + return _deleteCertificateDeserialize(result); } -export function _createTaskSend( +export function _cancelCertificateDeletionSend( context: Client, - jobId: string, - body: BatchTaskCreateOptions, - options: CreateTaskOptionalParams = { requestOptions: {} }, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/tasks", jobId) + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", + thumbprintAlgorithm, + thumbprint, + ) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchTaskCreateOptionsSerializer(body), }); } -export async function _createTaskDeserialize( +export async function _cancelCertificateDeletionDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["201"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -2849,29 +3399,54 @@ export async function _createTaskDeserialize( } /** - * The maximum lifetime of a Task from addition to completion is 180 days. If a - * Task has not completed within 180 days of being added it will be terminated by - * the Batch service and left in whatever state it was in at that time. + * If you try to delete a Certificate that is being used by a Pool or Compute + * Node, the status of the Certificate changes to deleteFailed. If you decide that + * you want to continue using the Certificate, you can use this operation to set + * the status of the Certificate back to active. If you intend to delete the + * Certificate, you do not need to run this operation after the deletion failed. + * You must make sure that the Certificate is not being used by any resources, and + * then you can try again to delete the Certificate. */ -export async function createTask( +export async function cancelCertificateDeletion( context: Client, - jobId: string, - body: BatchTaskCreateOptions, - options: CreateTaskOptionalParams = { requestOptions: {} }, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createTaskSend(context, jobId, body, options); - return _createTaskDeserialize(result); + const result = await _cancelCertificateDeletionSend( + context, + thumbprintAlgorithm, + thumbprint, + options, + ); + return _cancelCertificateDeletionDeserialize(result); } -export function _listTasksSend( +export function _listCertificatesSend( context: Client, - jobId: string, - options: ListTasksOptionalParams = { requestOptions: {} }, + options: ListCertificatesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks", jobId).get({ + return context.path("/certificates").get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, $filter: options?.$filter, @@ -2880,208 +3455,326 @@ export function _listTasksSend( : options?.$select.map((p: any) => { return p; }), - $expand: !options?.$expand - ? options?.$expand - : options?.$expand.map((p: any) => { - return p; - }), }, }); } -export async function _listTasksDeserialize( +export async function _listCertificatesDeserialize( result: PathUncheckedResponse, -): Promise<_BatchTaskListResult> { +): Promise<_CertificateListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _batchTaskListResultDeserializer(result.body); + return _certificateListResultDeserializer(result.body); } -/** - * For multi-instance Tasks, information such as affinityId, executionInfo and - * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve - * information about subtasks. - */ -export function listTasks( +/** Lists all of the Certificates that have been added to the specified Account. */ +export function listCertificates( context: Client, - jobId: string, - options: ListTasksOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: ListCertificatesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listTasksSend(context, jobId, options), - _listTasksDeserialize, + () => _listCertificatesSend(context, options), + _listCertificatesDeserialize, ["200"], { itemName: "value", nextLinkName: "odata.nextLink" }, ); } -export function _createTaskCollectionSend( +export function _createCertificateSend( context: Client, - jobId: string, - collection: BatchTaskCollection, - options: CreateTaskCollectionOptionalParams = { requestOptions: {} }, + body: BatchCertificate, + options: CreateCertificateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/addtaskcollection", jobId) + .path("/certificates") .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchTaskCollectionSerializer(collection), + body: batchCertificateSerializer(body), }); } -export async function _createTaskCollectionDeserialize( +export async function _createCertificateDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return taskAddCollectionResultDeserializer(result.body); + return; } -/** - * Note that each Task must have a unique ID. The Batch service may not return the - * results for each Task in the same order the Tasks were submitted in this - * request. If the server times out or the connection is closed during the - * request, the request may have been partially or fully processed, or not at all. - * In such cases, the user should re-issue the request. Note that it is up to the - * user to correctly handle failures when re-issuing a request. For example, you - * should use the same Task IDs during a retry so that if the prior operation - * succeeded, the retry will not create extra Tasks unexpectedly. If the response - * contains any Tasks which failed to add, a client can retry the request. In a - * retry, it is most efficient to resubmit only Tasks that failed to add, and to - * omit Tasks that were successfully added on the first attempt. The maximum - * lifetime of a Task from addition to completion is 180 days. If a Task has not - * completed within 180 days of being added it will be terminated by the Batch - * service and left in whatever state it was in at that time. - */ -export async function createTaskCollection( +/** Creates a Certificate to the specified Account. */ +export async function createCertificate( context: Client, - jobId: string, - collection: BatchTaskCollection, - options: CreateTaskCollectionOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createTaskCollectionSend( - context, - jobId, - collection, - options, - ); - return _createTaskCollectionDeserialize(result); + body: BatchCertificate, + options: CreateCertificateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createCertificateSend(context, body, options); + return _createCertificateDeserialize(result); } -export function _deleteTaskSend( +export function _getJobTaskCountsSend( context: Client, jobId: string, - taskId: string, - options: DeleteTaskOptionalParams = { requestOptions: {} }, + options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) - .delete({ + .path("/jobs/{jobId}/taskcounts", jobId) + .get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _deleteTaskDeserialize( +export async function _getJobTaskCountsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return taskCountsResultDeserializer(result.body); } /** - * When a Task is deleted, all of the files in its directory on the Compute Node - * where it ran are also deleted (regardless of the retention time). For - * multi-instance Tasks, the delete Task operation applies synchronously to the - * primary task; subtasks and their files are then deleted asynchronously in the - * background. + * Task counts provide a count of the Tasks by active, running or completed Task + * state, and a count of Tasks which succeeded or failed. Tasks in the preparing + * state are counted as running. Note that the numbers returned may not always be + * up to date. If you need exact task counts, use a list query. */ -export async function deleteTask( +export async function getJobTaskCounts( context: Client, jobId: string, - taskId: string, - options: DeleteTaskOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteTaskSend(context, jobId, taskId, options); - return _deleteTaskDeserialize(result); + options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getJobTaskCountsSend(context, jobId, options); + return _getJobTaskCountsDeserialize(result); } -export function _getTaskSend( +export function _listJobPreparationAndReleaseTaskStatusSend( context: Client, jobId: string, - taskId: string, - options: GetTaskOptionalParams = { requestOptions: {} }, + options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).get({ + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); + return context + .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _listJobPreparationAndReleaseTaskStatusDeserialize( + result: PathUncheckedResponse, +): Promise<_BatchJobListPreparationAndReleaseTaskStatusResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _batchJobListPreparationAndReleaseTaskStatusResultDeserializer( + result.body, + ); +} + +/** + * This API returns the Job Preparation and Job Release Task status on all Compute + * Nodes that have run the Job Preparation or Job Release Task. This includes + * Compute Nodes which have since been removed from the Pool. If this API is + * invoked on a Job which has no Job Preparation or Job Release Task, the Batch + * service returns HTTP status code 409 (Conflict) with an error code of + * JobPreparationTaskNotSpecified. + */ +export function listJobPreparationAndReleaseTaskStatus( + context: Client, + jobId: string, + options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { + requestOptions: {}, + }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listJobPreparationAndReleaseTaskStatusSend(context, jobId, options), + _listJobPreparationAndReleaseTaskStatusDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _listJobsFromScheduleSend( + context: Client, + jobScheduleId: string, + options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId).get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifMatch !== undefined - ? { "if-match": options?.ifMatch } - : {}), - ...(options?.ifNoneMatch !== undefined - ? { "if-none-match": options?.ifNoneMatch } - : {}), - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _listJobsFromScheduleDeserialize( + result: PathUncheckedResponse, +): Promise<_BatchJobListResult> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _batchJobListResultDeserializer(result.body); +} + +/** Lists the Jobs that have been created under the specified Job Schedule. */ +export function listJobsFromSchedule( + context: Client, + jobScheduleId: string, + options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listJobsFromScheduleSend(context, jobScheduleId, options), + _listJobsFromScheduleDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _listJobsSend( + context: Client, + options: ListJobsOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/jobs").get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, $select: !options?.$select ? options?.$select : options?.$select.map((p: any) => { @@ -3096,47 +3789,121 @@ export function _getTaskSend( }); } -export async function _getTaskDeserialize( +export async function _listJobsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_BatchJobListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return batchTaskDeserializer(result.body); + return _batchJobListResultDeserializer(result.body); +} + +/** Lists all of the Jobs in the specified Account. */ +export function listJobs( + context: Client, + options: ListJobsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listJobsSend(context, options), + _listJobsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, + ); +} + +export function _createJobSend( + context: Client, + body: BatchJobCreateOptions, + options: CreateJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/jobs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, + }, + body: batchJobCreateOptionsSerializer(body), + }); +} + +export async function _createJobDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["201"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return; } /** - * For multi-instance Tasks, information such as affinityId, executionInfo and - * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve - * information about subtasks. + * The Batch service supports two ways to control the work done as part of a Job. + * In the first approach, the user specifies a Job Manager Task. The Batch service + * launches this Task when it is ready to start the Job. The Job Manager Task + * controls all other Tasks that run under this Job, by using the Task APIs. In + * the second approach, the user directly controls the execution of Tasks under an + * active Job, by using the Task APIs. Also note: when naming Jobs, avoid + * including sensitive information such as user names or secret project names. + * This information may appear in telemetry logs accessible to Microsoft Support + * engineers. */ -export async function getTask( +export async function createJob( context: Client, - jobId: string, - taskId: string, - options: GetTaskOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTaskSend(context, jobId, taskId, options); - return _getTaskDeserialize(result); + body: BatchJobCreateOptions, + options: CreateJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createJobSend(context, body, options); + return _createJobDeserialize(result); } -export function _replaceTaskSend( +export function _terminateJobSend( context: Client, jobId: string, - taskId: string, - body: BatchTask, - options: ReplaceTaskOptionalParams = { requestOptions: {} }, + options: TerminateJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) - .put({ + .path("/jobs/{jobId}/terminate", jobId) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -3157,19 +3924,23 @@ export function _replaceTaskSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchTaskSerializer(body), + body: !options["body"] + ? options["body"] + : batchJobTerminateOptionsSerializer(options["body"]), }); } -export async function _replaceTaskDeserialize( +export async function _terminateJobDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -3177,73 +3948,46 @@ export async function _replaceTaskDeserialize( return; } -/** Updates the properties of the specified Task. */ -export async function replaceTask( +/** + * When a Terminate Job request is received, the Batch service sets the Job to the + * terminating state. The Batch service then terminates any running Tasks + * associated with the Job and runs any required Job release Tasks. Then the Job + * moves into the completed state. If there are any Tasks in the Job in the active + * state, they will remain in the active state. Once a Job is terminated, new + * Tasks cannot be added and any remaining active Tasks will not be scheduled. + */ +export async function terminateJob( context: Client, jobId: string, - taskId: string, - body: BatchTask, - options: ReplaceTaskOptionalParams = { requestOptions: {} }, + options: TerminateJobOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _replaceTaskSend(context, jobId, taskId, body, options); - return _replaceTaskDeserialize(result); -} - -export function _listSubTasksSend( - context: Client, - jobId: string, - taskId: string, - options: ListSubTasksOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks/{taskId}/subtasksinfo", jobId, taskId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _listSubTasksDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return batchTaskListSubtasksResultDeserializer(result.body); -} - -/** If the Task is not a multi-instance Task then this returns an empty collection. */ -export async function listSubTasks( - context: Client, - jobId: string, - taskId: string, - options: ListSubTasksOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSubTasksSend(context, jobId, taskId, options); - return _listSubTasksDeserialize(result); + const result = await _terminateJobSend(context, jobId, options); + return _terminateJobDeserialize(result); } -export function _terminateTaskSend( +export function _enableJobSend( context: Client, jobId: string, - taskId: string, - options: TerminateTaskOptionalParams = { requestOptions: {} }, + options: EnableJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/tasks/{taskId}/terminate", jobId, taskId) + .path("/jobs/{jobId}/enable", jobId) .post({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -3264,18 +4008,20 @@ export function _terminateTaskSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _terminateTaskDeserialize( +export async function _enableJobDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -3284,31 +4030,47 @@ export async function _terminateTaskDeserialize( } /** - * When the Task has been terminated, it moves to the completed state. For - * multi-instance Tasks, the terminate Task operation applies synchronously to the - * primary task; subtasks are then terminated asynchronously in the background. + * When you call this API, the Batch service sets a disabled Job to the enabling + * state. After the this operation is completed, the Job moves to the active + * state, and scheduling of new Tasks under the Job resumes. The Batch service + * does not allow a Task to remain in the active state for more than 180 days. + * Therefore, if you enable a Job containing active Tasks which were added more + * than 180 days ago, those Tasks will not run. */ -export async function terminateTask( +export async function enableJob( context: Client, jobId: string, - taskId: string, - options: TerminateTaskOptionalParams = { requestOptions: {} }, + options: EnableJobOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _terminateTaskSend(context, jobId, taskId, options); - return _terminateTaskDeserialize(result); + const result = await _enableJobSend(context, jobId, options); + return _enableJobDeserialize(result); } -export function _reactivateTaskSend( +export function _disableJobSend( context: Client, jobId: string, - taskId: string, - options: ReactivateTaskOptionalParams = { requestOptions: {} }, + body: BatchJobDisableOptions, + options: DisableJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/tasks/{taskId}/reactivate", jobId, taskId) + .path("/jobs/{jobId}/disable", jobId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), ...(options?.ifMatch !== undefined ? { "if-match": options?.ifMatch } : {}), @@ -3329,18 +4091,21 @@ export function _reactivateTaskSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchJobDisableOptionsSerializer(body), }); } -export async function _reactivateTaskDeserialize( +export async function _disableJobDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["204"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -3349,49 +4114,82 @@ export async function _reactivateTaskDeserialize( } /** - * Reactivation makes a Task eligible to be retried again up to its maximum retry - * count. The Task's state is changed to active. As the Task is no longer in the - * completed state, any previous exit code or failure information is no longer - * available after reactivation. Each time a Task is reactivated, its retry count - * is reset to 0. Reactivation will fail for Tasks that are not completed or that - * previously completed successfully (with an exit code of 0). Additionally, it - * will fail if the Job has completed (or is terminating or deleting). + * The Batch Service immediately moves the Job to the disabling state. Batch then + * uses the disableTasks parameter to determine what to do with the currently + * running Tasks of the Job. The Job remains in the disabling state until the + * disable operation is completed and all Tasks have been dealt with according to + * the disableTasks option; the Job then moves to the disabled state. No new Tasks + * are started under the Job until it moves back to active state. If you try to + * disable a Job that is in any state other than active, disabling, or disabled, + * the request fails with status code 409. */ -export async function reactivateTask( +export async function disableJob( context: Client, jobId: string, - taskId: string, - options: ReactivateTaskOptionalParams = { requestOptions: {} }, + body: BatchJobDisableOptions, + options: DisableJobOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _reactivateTaskSend(context, jobId, taskId, options); - return _reactivateTaskDeserialize(result); + const result = await _disableJobSend(context, jobId, body, options); + return _disableJobDeserialize(result); } -export function _deleteTaskFileSend( +export function _replaceJobSend( context: Client, jobId: string, - taskId: string, - filePath: string, - options: DeleteTaskFileOptionalParams = { requestOptions: {} }, + body: BatchJob, + options: ReplaceJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/jobs/{jobId}/tasks/{taskId}/files/{filePath}", - jobId, - taskId, - filePath, - ) - .delete({ + .path("/jobs/{jobId}", jobId) + .put({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - recursive: options?.recursive, }, + body: batchJobSerializer(body), }); } -export async function _deleteTaskFileDeserialize( +export async function _replaceJobDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -3402,41 +4200,52 @@ export async function _deleteTaskFileDeserialize( return; } -/** Deletes the specified Task file from the Compute Node where the Task ran. */ -export async function deleteTaskFile( +/** + * This fully replaces all the updatable properties of the Job. For example, if + * the Job has constraints associated with it and if constraints is not specified + * with this request, then the Batch service will remove the existing constraints. + */ +export async function replaceJob( context: Client, jobId: string, - taskId: string, - filePath: string, - options: DeleteTaskFileOptionalParams = { requestOptions: {} }, + body: BatchJob, + options: ReplaceJobOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _deleteTaskFileSend( - context, - jobId, - taskId, - filePath, - options, - ); - return _deleteTaskFileDeserialize(result); + const result = await _replaceJobSend(context, jobId, body, options); + return _replaceJobDeserialize(result); } -export function _getTaskFileSend( +export function _updateJobSend( context: Client, jobId: string, - taskId: string, - filePath: string, - options: GetTaskFileOptionalParams = { requestOptions: {} }, + body: BatchJobUpdateOptions, + options: UpdateJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/jobs/{jobId}/tasks/{taskId}/files/{filePath}", - jobId, - taskId, - filePath, - ) - .get({ + .path("/jobs/{jobId}", jobId) + .patch({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), ...(options?.ifModifiedSince !== undefined ? { "if-modified-since": !options?.ifModifiedSince @@ -3451,63 +4260,154 @@ export function _getTaskFileSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), - ...(options?.ocpRange !== undefined - ? { "ocp-range": options?.ocpRange } - : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchJobUpdateOptionsSerializer(body), }); } -export async function _getTaskFileDeserialize( +export async function _updateJobDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body; + return; } -/** Returns the content of the specified Task file. */ -export async function getTaskFile( +/** + * This replaces only the Job properties specified in the request. For example, if + * the Job has constraints, and a request does not specify the constraints + * element, then the Job keeps the existing constraints. + */ +export async function updateJob( context: Client, jobId: string, - taskId: string, - filePath: string, - options: GetTaskFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTaskFileSend( - context, - jobId, - taskId, - filePath, - options, - ); - return _getTaskFileDeserialize(result); + body: BatchJobUpdateOptions, + options: UpdateJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateJobSend(context, jobId, body, options); + return _updateJobDeserialize(result); } -export function _getTaskFilePropertiesSend( +export function _getJobSend( context: Client, jobId: string, - taskId: string, - filePath: string, - options: GetTaskFilePropertiesOptionalParams = { requestOptions: {} }, + options: GetJobOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/jobs/{jobId}", jobId).get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + timeOut: options?.timeOutInSeconds, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _getJobDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return batchJobDeserializer(result.body); +} + +/** Gets information about the specified Job. */ +export async function getJob( + context: Client, + jobId: string, + options: GetJobOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getJobSend(context, jobId, options); + return _getJobDeserialize(result); +} + +export function _deleteJobSend( + context: Client, + jobId: string, + options: DeleteJobOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/jobs/{jobId}/tasks/{taskId}/files/{filePath}", - jobId, - taskId, - filePath, - ) - .head({ + .path("/jobs/{jobId}", jobId) + .delete({ ...operationOptionsToRequestParameters(options), headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), ...(options?.ifModifiedSince !== undefined ? { "if-modified-since": !options?.ifModifiedSince @@ -3522,18 +4422,20 @@ export function _getTaskFilePropertiesSend( : options?.ifUnmodifiedSince.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _getTaskFilePropertiesDeserialize( +export async function _deleteJobDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -3541,152 +4443,207 @@ export async function _getTaskFilePropertiesDeserialize( return; } -/** Gets the properties of the specified Task file. */ -export async function getTaskFileProperties( +/** + * Deleting a Job also deletes all Tasks that are part of that Job, and all Job + * statistics. This also overrides the retention period for Task data; that is, if + * the Job contains Tasks which are still retained on Compute Nodes, the Batch + * services deletes those Tasks' working directories and all their contents. When + * a Delete Job request is received, the Batch service sets the Job to the + * deleting state. All update operations on a Job that is in deleting state will + * fail with status code 409 (Conflict), with additional information indicating + * that the Job is being deleted. + */ +export async function deleteJob( context: Client, jobId: string, - taskId: string, - filePath: string, - options: GetTaskFilePropertiesOptionalParams = { requestOptions: {} }, + options: DeleteJobOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _getTaskFilePropertiesSend( - context, - jobId, - taskId, - filePath, - options, - ); - return _getTaskFilePropertiesDeserialize(result); + const result = await _deleteJobSend(context, jobId, options); + return _deleteJobDeserialize(result); } -export function _listTaskFilesSend( +export function _listPoolNodeCountsSend( context: Client, - jobId: string, - taskId: string, - options: ListTaskFilesOptionalParams = { requestOptions: {} }, + options: ListPoolNodeCountsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/jobs/{jobId}/tasks/{taskId}/files", jobId, taskId) + .path("/nodecounts") .get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, $filter: options?.$filter, - recursive: options?.recursive, }, }); } -export async function _listTaskFilesDeserialize( +export async function _listPoolNodeCountsDeserialize( result: PathUncheckedResponse, -): Promise<_NodeFileListResult> { +): Promise<_PoolNodeCountsListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _nodeFileListResultDeserializer(result.body); + return _poolNodeCountsListResultDeserializer(result.body); } -/** Lists the files in a Task's directory on its Compute Node. */ -export function listTaskFiles( +/** + * Gets the number of Compute Nodes in each state, grouped by Pool. Note that the + * numbers returned may not always be up to date. If you need exact node counts, + * use a list query. + */ +export function listPoolNodeCounts( context: Client, - jobId: string, - taskId: string, - options: ListTaskFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: ListPoolNodeCountsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listTaskFilesSend(context, jobId, taskId, options), - _listTaskFilesDeserialize, + () => _listPoolNodeCountsSend(context, options), + _listPoolNodeCountsDeserialize, ["200"], { itemName: "value", nextLinkName: "odata.nextLink" }, ); } -export function _createNodeUserSend( +export function _listSupportedImagesSend( context: Client, - poolId: string, - nodeId: string, - body: BatchNodeUserCreateOptions, - options: CreateNodeUserOptionalParams = { requestOptions: {} }, + options: ListSupportedImagesOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/pools/{poolId}/nodes/{nodeId}/users", poolId, nodeId) - .post({ + .path("/supportedimages") + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, }, - body: batchNodeUserCreateOptionsSerializer(body), }); } -export async function _createNodeUserDeserialize( +export async function _listSupportedImagesDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201"]; +): Promise<_AccountListSupportedImagesResult> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return _accountListSupportedImagesResultDeserializer(result.body); } -/** - * You can add a user Account to a Compute Node only when it is in the idle or - * running state. - */ -export async function createNodeUser( +/** Lists all Virtual Machine Images supported by the Azure Batch service. */ +export function listSupportedImages( context: Client, - poolId: string, - nodeId: string, - body: BatchNodeUserCreateOptions, - options: CreateNodeUserOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createNodeUserSend( + options: ListSupportedImagesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - poolId, - nodeId, - body, - options, + () => _listSupportedImagesSend(context, options), + _listSupportedImagesDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, ); - return _createNodeUserDeserialize(result); } -export function _deleteNodeUserSend( +export function _removeNodesSend( context: Client, poolId: string, - nodeId: string, - userName: string, - options: DeleteNodeUserOptionalParams = { requestOptions: {} }, + body: NodeRemoveOptions, + options: RemoveNodesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/pools/{poolId}/nodes/{nodeId}/users/{userName}", - poolId, - nodeId, - userName, - ) - .delete({ + .path("/pools/{poolId}/removenodes", poolId) + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: nodeRemoveOptionsSerializer(body), }); } -export async function _deleteNodeUserDeserialize( +export async function _removeNodesDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["202"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -3695,58 +4652,60 @@ export async function _deleteNodeUserDeserialize( } /** - * You can delete a user Account to a Compute Node only when it is in the idle or - * running state. + * This operation can only run when the allocation state of the Pool is steady. + * When this operation runs, the allocation state changes from steady to resizing. + * Each request may remove up to 100 nodes. */ -export async function deleteNodeUser( +export async function removeNodes( context: Client, poolId: string, - nodeId: string, - userName: string, - options: DeleteNodeUserOptionalParams = { requestOptions: {} }, + body: NodeRemoveOptions, + options: RemoveNodesOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _deleteNodeUserSend( - context, - poolId, - nodeId, - userName, - options, - ); - return _deleteNodeUserDeserialize(result); + const result = await _removeNodesSend(context, poolId, body, options); + return _removeNodesDeserialize(result); } -export function _replaceNodeUserSend( +export function _replacePoolPropertiesSend( context: Client, poolId: string, - nodeId: string, - userName: string, - body: BatchNodeUserUpdateOptions, - options: ReplaceNodeUserOptionalParams = { requestOptions: {} }, + body: BatchPoolReplaceOptions, + options: ReplacePoolPropertiesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/pools/{poolId}/nodes/{nodeId}/users/{userName}", - poolId, - nodeId, - userName, - ) - .put({ + .path("/pools/{poolId}/updateproperties", poolId) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: batchNodeUserUpdateOptionsSerializer(body), + body: batchPoolReplaceOptionsSerializer(body), }); } -export async function _replaceNodeUserDeserialize( +export async function _replacePoolPropertiesDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -3755,96 +4714,79 @@ export async function _replaceNodeUserDeserialize( } /** - * This operation replaces of all the updatable properties of the Account. For - * example, if the expiryTime element is not specified, the current value is - * replaced with the default value, not left unmodified. You can update a user - * Account on a Compute Node only when it is in the idle or running state. + * This fully replaces all the updatable properties of the Pool. For example, if + * the Pool has a StartTask associated with it and if StartTask is not specified + * with this request, then the Batch service will remove the existing StartTask. */ -export async function replaceNodeUser( +export async function replacePoolProperties( context: Client, poolId: string, - nodeId: string, - userName: string, - body: BatchNodeUserUpdateOptions, - options: ReplaceNodeUserOptionalParams = { requestOptions: {} }, + body: BatchPoolReplaceOptions, + options: ReplacePoolPropertiesOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _replaceNodeUserSend( + const result = await _replacePoolPropertiesSend( context, poolId, - nodeId, - userName, body, options, ); - return _replaceNodeUserDeserialize(result); -} - -export function _getNodeSend( - context: Client, - poolId: string, - nodeId: string, - options: GetNodeOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), - }, - }); -} - -export async function _getNodeDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return batchNodeDeserializer(result.body); -} - -/** Gets information about the specified Compute Node. */ -export async function getNode( - context: Client, - poolId: string, - nodeId: string, - options: GetNodeOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getNodeSend(context, poolId, nodeId, options); - return _getNodeDeserialize(result); + return _replacePoolPropertiesDeserialize(result); } -export function _rebootNodeSend( +export function _stopPoolResizeSend( context: Client, poolId: string, - nodeId: string, - options: RebootNodeOptionalParams = { requestOptions: {} }, + options: StopPoolResizeOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/reboot", poolId, nodeId) + .path("/pools/{poolId}/stopresize", poolId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: !options["body"] - ? options["body"] - : nodeRebootOptionsSerializer(options["body"]), }); } -export async function _rebootNodeDeserialize( +export async function _stopPoolResizeDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["202"]; @@ -3855,41 +4797,81 @@ export async function _rebootNodeDeserialize( return; } -/** You can restart a Compute Node only if it is in an idle or running state. */ -export async function rebootNode( +/** + * This does not restore the Pool to its previous state before the resize + * operation: it only stops any further changes being made, and the Pool maintains + * its current state. After stopping, the Pool stabilizes at the number of Compute + * Nodes it was at when the stop operation was done. During the stop operation, + * the Pool allocation state changes first to stopping and then to steady. A + * resize operation need not be an explicit resize Pool request; this API can also + * be used to halt the initial sizing of the Pool when it is created. + */ +export async function stopPoolResize( context: Client, poolId: string, - nodeId: string, - options: RebootNodeOptionalParams = { requestOptions: {} }, + options: StopPoolResizeOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _rebootNodeSend(context, poolId, nodeId, options); - return _rebootNodeDeserialize(result); + const result = await _stopPoolResizeSend(context, poolId, options); + return _stopPoolResizeDeserialize(result); } -export function _reimageNodeSend( +export function _resizePoolSend( context: Client, poolId: string, - nodeId: string, - options: ReimageNodeOptionalParams = { requestOptions: {} }, + body: BatchPoolResizeOptions, + options: ResizePoolOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/reimage", poolId, nodeId) + .path("/pools/{poolId}/resize", poolId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: !options["body"] - ? options["body"] - : nodeReimageOptionsSerializer(options["body"]), + body: batchPoolResizeOptionsSerializer(body), }); } -export async function _reimageNodeDeserialize( +export async function _resizePoolDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["202"]; @@ -3901,91 +4883,148 @@ export async function _reimageNodeDeserialize( } /** - * You can reinstall the operating system on a Compute Node only if it is in an - * idle or running state. This API can be invoked only on Pools created with the - * cloud service configuration property. + * You can only resize a Pool when its allocation state is steady. If the Pool is + * already resizing, the request fails with status code 409. When you resize a + * Pool, the Pool's allocation state changes from steady to resizing. You cannot + * resize Pools which are configured for automatic scaling. If you try to do this, + * the Batch service returns an error 409. If you resize a Pool downwards, the + * Batch service chooses which Compute Nodes to remove. To remove specific Compute + * Nodes, use the Pool remove Compute Nodes API instead. */ -export async function reimageNode( +export async function resizePool( context: Client, poolId: string, - nodeId: string, - options: ReimageNodeOptionalParams = { requestOptions: {} }, + body: BatchPoolResizeOptions, + options: ResizePoolOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _reimageNodeSend(context, poolId, nodeId, options); - return _reimageNodeDeserialize(result); + const result = await _resizePoolSend(context, poolId, body, options); + return _resizePoolDeserialize(result); } -export function _disableNodeSchedulingSend( +export function _evaluatePoolAutoScaleSend( context: Client, poolId: string, - nodeId: string, - options: DisableNodeSchedulingOptionalParams = { requestOptions: {} }, + body: BatchPoolEvaluateAutoScaleOptions, + options: EvaluatePoolAutoScaleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/disablescheduling", poolId, nodeId) + .path("/pools/{poolId}/evaluateautoscale", poolId) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, - body: !options["body"] - ? options["body"] - : nodeDisableSchedulingOptionsSerializer(options["body"]), + body: batchPoolEvaluateAutoScaleOptionsSerializer(body), }); } -export async function _disableNodeSchedulingDeserialize( +export async function _evaluatePoolAutoScaleDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return autoScaleRunDeserializer(result.body); } /** - * You can disable Task scheduling on a Compute Node only if its current - * scheduling state is enabled. + * This API is primarily for validating an autoscale formula, as it simply returns + * the result without applying the formula to the Pool. The Pool must have auto + * scaling enabled in order to evaluate a formula. */ -export async function disableNodeScheduling( +export async function evaluatePoolAutoScale( context: Client, poolId: string, - nodeId: string, - options: DisableNodeSchedulingOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _disableNodeSchedulingSend( + body: BatchPoolEvaluateAutoScaleOptions, + options: EvaluatePoolAutoScaleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _evaluatePoolAutoScaleSend( context, poolId, - nodeId, + body, options, ); - return _disableNodeSchedulingDeserialize(result); + return _evaluatePoolAutoScaleDeserialize(result); } -export function _enableNodeSchedulingSend( +export function _enablePoolAutoScaleSend( context: Client, poolId: string, - nodeId: string, - options: EnableNodeSchedulingOptionalParams = { requestOptions: {} }, + body: BatchPoolEnableAutoScaleOptions, + options: EnablePoolAutoScaleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/enablescheduling", poolId, nodeId) + .path("/pools/{poolId}/enableautoscale", poolId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchPoolEnableAutoScaleOptionsSerializer(body), }); } -export async function _enableNodeSchedulingDeserialize( +export async function _enablePoolAutoScaleDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -3997,366 +5036,508 @@ export async function _enableNodeSchedulingDeserialize( } /** - * You can enable Task scheduling on a Compute Node only if its current scheduling - * state is disabled + * You cannot enable automatic scaling on a Pool if a resize operation is in + * progress on the Pool. If automatic scaling of the Pool is currently disabled, + * you must specify a valid autoscale formula as part of the request. If automatic + * scaling of the Pool is already enabled, you may specify a new autoscale formula + * and/or a new evaluation interval. You cannot call this API for the same Pool + * more than once every 30 seconds. */ -export async function enableNodeScheduling( +export async function enablePoolAutoScale( context: Client, poolId: string, - nodeId: string, - options: EnableNodeSchedulingOptionalParams = { requestOptions: {} }, + body: BatchPoolEnableAutoScaleOptions, + options: EnablePoolAutoScaleOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _enableNodeSchedulingSend( - context, - poolId, - nodeId, - options, - ); - return _enableNodeSchedulingDeserialize(result); + const result = await _enablePoolAutoScaleSend(context, poolId, body, options); + return _enablePoolAutoScaleDeserialize(result); } -export function _getNodeRemoteLoginSettingsSend( +export function _disablePoolAutoScaleSend( context: Client, poolId: string, - nodeId: string, - options: GetNodeRemoteLoginSettingsOptionalParams = { requestOptions: {} }, + options: DisablePoolAutoScaleOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/remoteloginsettings", poolId, nodeId) - .get({ + .path("/pools/{poolId}/disableautoscale", poolId) + .post({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _getNodeRemoteLoginSettingsDeserialize( +export async function _disablePoolAutoScaleDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return batchNodeRemoteLoginSettingsResultDeserializer(result.body); + return; } -/** - * Before you can remotely login to a Compute Node using the remote login - * settings, you must create a user Account on the Compute Node. This API can be - * invoked only on Pools created with the virtual machine configuration property. - * For Pools created with a cloud service configuration, see the GetRemoteDesktop - * API. - */ -export async function getNodeRemoteLoginSettings( +/** Disables automatic scaling for a Pool. */ +export async function disablePoolAutoScale( context: Client, poolId: string, - nodeId: string, - options: GetNodeRemoteLoginSettingsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getNodeRemoteLoginSettingsSend( - context, - poolId, - nodeId, - options, - ); - return _getNodeRemoteLoginSettingsDeserialize(result); + options: DisablePoolAutoScaleOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _disablePoolAutoScaleSend(context, poolId, options); + return _disablePoolAutoScaleDeserialize(result); } -export function _getNodeRemoteDesktopFileSend( +export function _updatePoolSend( context: Client, poolId: string, - nodeId: string, - options: GetNodeRemoteDesktopFileOptionalParams = { requestOptions: {} }, + body: BatchPoolUpdateOptions, + options: UpdatePoolOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/rdp", poolId, nodeId) - .get({ + .path("/pools/{poolId}", poolId) + .patch({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, + body: batchPoolUpdateOptionsSerializer(body), }); } -export async function _getNodeRemoteDesktopFileDeserialize( +export async function _updatePoolDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return typeof result.body === "string" - ? stringToUint8Array(result.body, "base64") - : result.body; + return; } /** - * Before you can access a Compute Node by using the RDP file, you must create a - * user Account on the Compute Node. This API can only be invoked on Pools created - * with a cloud service configuration. For Pools created with a virtual machine - * configuration, see the GetRemoteLoginSettings API. + * This only replaces the Pool properties specified in the request. For example, + * if the Pool has a StartTask associated with it, and a request does not specify + * a StartTask element, then the Pool keeps the existing StartTask. */ -export async function getNodeRemoteDesktopFile( +export async function updatePool( context: Client, poolId: string, - nodeId: string, - options: GetNodeRemoteDesktopFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getNodeRemoteDesktopFileSend( - context, - poolId, - nodeId, - options, - ); - return _getNodeRemoteDesktopFileDeserialize(result); + body: BatchPoolUpdateOptions, + options: UpdatePoolOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updatePoolSend(context, poolId, body, options); + return _updatePoolDeserialize(result); } -export function _uploadNodeLogsSend( +export function _getPoolSend( context: Client, poolId: string, - nodeId: string, - body: UploadBatchServiceLogsOptions, - options: UploadNodeLogsOptionalParams = { requestOptions: {} }, + options: GetPoolOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path( - "/pools/{poolId}/nodes/{nodeId}/uploadbatchservicelogs", - poolId, - nodeId, - ) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - timeOut: options?.timeOutInSeconds, - }, - body: uploadBatchServiceLogsOptionsSerializer(body), - }); -} - -export async function _uploadNodeLogsDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return uploadBatchServiceLogsResultDeserializer(result.body); -} - -/** - * This is for gathering Azure Batch service log files in an automated fashion - * from Compute Nodes if you are experiencing an error and wish to escalate to - * Azure support. The Azure Batch service log files should be shared with Azure - * support to aid in debugging issues with the Batch service. - */ -export async function uploadNodeLogs( - context: Client, - poolId: string, - nodeId: string, - body: UploadBatchServiceLogsOptions, - options: UploadNodeLogsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _uploadNodeLogsSend( - context, - poolId, - nodeId, - body, - options, - ); - return _uploadNodeLogsDeserialize(result); -} - -export function _listNodesSend( - context: Client, - poolId: string, - options: ListNodesOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context.path("/pools/{poolId}/nodes", poolId).get({ + return context.path("/pools/{poolId}", poolId).get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", - maxresults: options?.maxresults, + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, $select: !options?.$select ? options?.$select : options?.$select.map((p: any) => { return p; }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), }, }); } -export async function _listNodesDeserialize( +export async function _getPoolDeserialize( result: PathUncheckedResponse, -): Promise<_BatchNodeListResult> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _batchNodeListResultDeserializer(result.body); + return batchPoolDeserializer(result.body); } -/** Lists the Compute Nodes in the specified Pool. */ -export function listNodes( +/** Gets information about the specified Pool. */ +export async function getPool( context: Client, poolId: string, - options: ListNodesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listNodesSend(context, poolId, options), - _listNodesDeserialize, - ["200"], - { itemName: "value", nextLinkName: "odata.nextLink" }, - ); + options: GetPoolOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getPoolSend(context, poolId, options); + return _getPoolDeserialize(result); } -export function _getNodeExtensionSend( +export function _poolExistsSend( context: Client, poolId: string, - nodeId: string, - extensionName: string, - options: GetNodeExtensionOptionalParams = { requestOptions: {} }, + options: PoolExistsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/pools/{poolId}/nodes/{nodeId}/extensions/{extensionName}", - poolId, - nodeId, - extensionName, - ) - .get({ + .path("/pools/{poolId}", poolId) + .head({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), }, }); } -export async function _getNodeExtensionDeserialize( +export async function _poolExistsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["404", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return nodeVMExtensionDeserializer(result.body); + return; } -/** Gets information about the specified Compute Node Extension. */ -export async function getNodeExtension( +/** Gets basic properties of a Pool. */ +export async function poolExists( context: Client, poolId: string, - nodeId: string, - extensionName: string, - options: GetNodeExtensionOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getNodeExtensionSend( - context, - poolId, - nodeId, - extensionName, - options, - ); - return _getNodeExtensionDeserialize(result); + options: PoolExistsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _poolExistsSend(context, poolId, options); + return _poolExistsDeserialize(result); } -export function _listNodeExtensionsSend( +export function _deletePoolSend( context: Client, poolId: string, - nodeId: string, - options: ListNodeExtensionsOptionalParams = { requestOptions: {} }, + options: DeletePoolOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/extensions", poolId, nodeId) - .get({ + .path("/pools/{poolId}", poolId) + .delete({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.ifMatch !== undefined + ? { "if-match": options?.ifMatch } + : {}), + ...(options?.ifNoneMatch !== undefined + ? { "if-none-match": options?.ifNoneMatch } + : {}), + ...(options?.ifModifiedSince !== undefined + ? { + "if-modified-since": !options?.ifModifiedSince + ? options?.ifModifiedSince + : options?.ifModifiedSince.toUTCString(), + } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { + "if-unmodified-since": !options?.ifUnmodifiedSince + ? options?.ifUnmodifiedSince + : options?.ifUnmodifiedSince.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - maxresults: options?.maxresults, + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - $select: !options?.$select - ? options?.$select - : options?.$select.map((p: any) => { - return p; - }), }, }); } -export async function _listNodeExtensionsDeserialize( +export async function _deletePoolDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["202"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return; +} + +/** + * When you request that a Pool be deleted, the following actions occur: the Pool + * state is set to deleting; any ongoing resize operation on the Pool are stopped; + * the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks + * running on existing Compute Nodes are terminated and requeued (as if a resize + * Pool operation had been requested with the default requeue option); finally, + * the Pool is removed from the system. Because running Tasks are requeued, the + * user can rerun these Tasks by updating their Job to target a different Pool. + * The Tasks can then run on the new Pool. If you want to override the requeue + * behavior, then you should call resize Pool explicitly to shrink the Pool to + * zero size before deleting the Pool. If you call an Update, Patch or Delete API + * on a Pool in the deleting state, it will fail with HTTP status code 409 with + * error code PoolBeingDeleted. + */ +export async function deletePool( + context: Client, + poolId: string, + options: DeletePoolOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deletePoolSend(context, poolId, options); + return _deletePoolDeserialize(result); +} + +export function _listPoolsSend( + context: Client, + options: ListPoolsOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/pools").get({ + ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + maxresults: options?.maxresults, + timeOut: options?.timeOutInSeconds, + $filter: options?.$filter, + $select: !options?.$select + ? options?.$select + : options?.$select.map((p: any) => { + return p; + }), + $expand: !options?.$expand + ? options?.$expand + : options?.$expand.map((p: any) => { + return p; + }), + }, + }); +} + +export async function _listPoolsDeserialize( result: PathUncheckedResponse, -): Promise<_NodeVMExtensionList> { +): Promise<_BatchPoolListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _nodeVMExtensionListDeserializer(result.body); + return _batchPoolListResultDeserializer(result.body); } -/** Lists the Compute Nodes Extensions in the specified Pool. */ -export function listNodeExtensions( +/** Lists all of the Pools in the specified Account. */ +export function listPools( context: Client, - poolId: string, - nodeId: string, - options: ListNodeExtensionsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: ListPoolsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listNodeExtensionsSend(context, poolId, nodeId, options), - _listNodeExtensionsDeserialize, + () => _listPoolsSend(context, options), + _listPoolsDeserialize, ["200"], { itemName: "value", nextLinkName: "odata.nextLink" }, ); } -export function _deleteNodeFileSend( +export function _createPoolSend( context: Client, - poolId: string, - nodeId: string, - filePath: string, - options: DeleteNodeFileOptionalParams = { requestOptions: {} }, + body: BatchPoolCreateOptions, + options: CreatePoolOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/pools/{poolId}/nodes/{nodeId}/files/{filePath}", - poolId, - nodeId, - filePath, - ) - .delete({ + .path("/pools") + .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json; odata=minimalmetadata", + headers: { + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, - recursive: options?.recursive, }, + body: batchPoolCreateOptionsSerializer(body), }); } -export async function _deleteNodeFileDeserialize( +export async function _createPoolDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -4364,207 +5545,211 @@ export async function _deleteNodeFileDeserialize( return; } -/** Deletes the specified file from the Compute Node. */ -export async function deleteNodeFile( +/** + * When naming Pools, avoid including sensitive information such as user names or + * secret project names. This information may appear in telemetry logs accessible + * to Microsoft Support engineers. + */ +export async function createPool( context: Client, - poolId: string, - nodeId: string, - filePath: string, - options: DeleteNodeFileOptionalParams = { requestOptions: {} }, + body: BatchPoolCreateOptions, + options: CreatePoolOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _deleteNodeFileSend( - context, - poolId, - nodeId, - filePath, - options, - ); - return _deleteNodeFileDeserialize(result); + const result = await _createPoolSend(context, body, options); + return _createPoolDeserialize(result); } -export function _getNodeFileSend( +export function _listPoolUsageMetricsSend( context: Client, - poolId: string, - nodeId: string, - filePath: string, - options: GetNodeFileOptionalParams = { requestOptions: {} }, + options: ListPoolUsageMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/pools/{poolId}/nodes/{nodeId}/files/{filePath}", - poolId, - nodeId, - filePath, - ) + .path("/poolusagemetrics") .get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifModifiedSince !== undefined + ...(options?.ocpDate !== undefined ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), - } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ocpRange !== undefined - ? { "ocp-range": options?.ocpRange } + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, + maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, + starttime: !options?.starttime + ? options?.starttime + : options?.starttime.toISOString(), + endtime: !options?.endtime + ? options?.endtime + : options?.endtime.toISOString(), + $filter: options?.$filter, }, }); } -export async function _getNodeFileDeserialize( +export async function _listPoolUsageMetricsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_PoolListUsageMetricsResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return typeof result.body === "string" - ? stringToUint8Array(result.body, "base64") - : result.body; + return _poolListUsageMetricsResultDeserializer(result.body); } -/** Returns the content of the specified Compute Node file. */ -export async function getNodeFile( +/** + * If you do not specify a $filter clause including a poolId, the response + * includes all Pools that existed in the Account in the time range of the + * returned aggregation intervals. If you do not specify a $filter clause + * including a startTime or endTime these filters default to the start and end + * times of the last aggregation interval currently available; that is, only the + * last aggregation interval is returned. + */ +export function listPoolUsageMetrics( context: Client, - poolId: string, - nodeId: string, - filePath: string, - options: GetNodeFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getNodeFileSend( + options: ListPoolUsageMetricsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - poolId, - nodeId, - filePath, - options, + () => _listPoolUsageMetricsSend(context, options), + _listPoolUsageMetricsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "odata.nextLink" }, ); - return _getNodeFileDeserialize(result); } -export function _getNodeFilePropertiesSend( +export function _getApplicationSend( context: Client, - poolId: string, - nodeId: string, - filePath: string, - options: GetNodeFilePropertiesOptionalParams = { requestOptions: {} }, + applicationId: string, + options: GetApplicationOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/pools/{poolId}/nodes/{nodeId}/files/{filePath}", - poolId, - nodeId, - filePath, - ) - .head({ + .path("/applications/{applicationId}", applicationId) + .get({ ...operationOptionsToRequestParameters(options), headers: { - ...(options?.ifModifiedSince !== undefined - ? { - "if-modified-since": !options?.ifModifiedSince - ? options?.ifModifiedSince - : options?.ifModifiedSince.toUTCString(), - } + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } : {}), - ...(options?.ifUnmodifiedSince !== undefined + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + ...(options?.ocpDate !== undefined ? { - "if-unmodified-since": !options?.ifUnmodifiedSince - ? options?.ifUnmodifiedSince - : options?.ifUnmodifiedSince.toUTCString(), + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), } : {}), + accept: "application/json", + ...options.requestOptions?.headers, }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, timeOut: options?.timeOutInSeconds, }, }); } -export async function _getNodeFilePropertiesDeserialize( +export async function _getApplicationDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return batchApplicationDeserializer(result.body); } -/** Gets the properties of the specified Compute Node file. */ -export async function getNodeFileProperties( +/** + * This operation returns only Applications and versions that are available for + * use on Compute Nodes; that is, that can be used in an Package reference. For + * administrator information about Applications and versions that are not yet + * available to Compute Nodes, use the Azure portal or the Azure Resource Manager + * API. + */ +export async function getApplication( context: Client, - poolId: string, - nodeId: string, - filePath: string, - options: GetNodeFilePropertiesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getNodeFilePropertiesSend( - context, - poolId, - nodeId, - filePath, - options, - ); - return _getNodeFilePropertiesDeserialize(result); + applicationId: string, + options: GetApplicationOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getApplicationSend(context, applicationId, options); + return _getApplicationDeserialize(result); } -export function _listNodeFilesSend( +export function _listApplicationsSend( context: Client, - poolId: string, - nodeId: string, - options: ListNodeFilesOptionalParams = { requestOptions: {} }, + options: ListApplicationsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/pools/{poolId}/nodes/{nodeId}/files", poolId, nodeId) + .path("/applications") .get({ ...operationOptionsToRequestParameters(options), + headers: { + ...(options?.ocpDate !== undefined + ? { + "ocp-date": !options?.ocpDate + ? options?.ocpDate + : options?.ocpDate.toUTCString(), + } + : {}), + ...(options?.clientRequestId !== undefined + ? { "client-request-id": options?.clientRequestId } + : {}), + ...(options?.returnClientRequestId !== undefined + ? { "return-client-request-id": options?.returnClientRequestId } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { - "api-version": options?.apiVersion ?? "2023-05-01.17.0", + "api-version": context.apiVersion, maxresults: options?.maxresults, timeOut: options?.timeOutInSeconds, - $filter: options?.$filter, - recursive: options?.recursive, }, }); } -export async function _listNodeFilesDeserialize( +export async function _listApplicationsDeserialize( result: PathUncheckedResponse, -): Promise<_NodeFileListResult> { +): Promise<_ApplicationListResult> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _nodeFileListResultDeserializer(result.body); + return _applicationListResultDeserializer(result.body); } -/** Lists all of the files in Task directories on the specified Compute Node. */ -export function listNodeFiles( +/** + * This operation returns only Applications and versions that are available for + * use on Compute Nodes; that is, that can be used in an Package reference. For + * administrator information about applications and versions that are not yet + * available to Compute Nodes, use the Azure portal or the Azure Resource Manager + * API. + */ +export function listApplications( context: Client, - poolId: string, - nodeId: string, - options: ListNodeFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { + options: ListApplicationsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - () => _listNodeFilesSend(context, poolId, nodeId, options), - _listNodeFilesDeserialize, + () => _listApplicationsSend(context, options), + _listApplicationsDeserialize, ["200"], { itemName: "value", nextLinkName: "odata.nextLink" }, ); diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/options.ts index 4347e9a5ea..e3272f4698 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/options.ts @@ -1,133 +1,68 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { OperationOptions } from "@azure-rest/core-client"; import { NodeRebootOptions, NodeReimageOptions, NodeDisableSchedulingOptions, BatchJobTerminateOptions, } from "../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface ListApplicationsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - maxresults?: number; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - timeOutInSeconds?: number; -} - -/** Optional parameters. */ -export interface GetApplicationOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - timeOutInSeconds?: number; -} - -/** Optional parameters. */ -export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListNodeFilesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - timeOutInSeconds?: number; - /** - * The earliest time from which to include metrics. This must be at least two and - * a half hours before the current time. If not specified this defaults to the - * start time of the last aggregation interval currently available. - */ - starttime?: Date; - /** - * The latest time from which to include metrics. This must be at least two hours - * before the current time. If not specified this defaults to the end time of the - * last aggregation interval currently available. - */ - endtime?: Date; - /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - $filter?: string; -} - -/** Optional parameters. */ -export interface CreatePoolOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; -} - -/** Optional parameters. */ -export interface ListPoolsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - maxresults?: number; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - timeOutInSeconds?: number; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-pools. + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. */ $filter?: string; - /** An OData $select clause. */ - $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; + /** Whether to list children of a directory. */ + recursive?: boolean; } /** Optional parameters. */ -export interface DeletePoolOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; /** * A timestamp indicating the last modified time of the resource known to the * client. The operation will be performed only if the resource on the service has @@ -143,26 +78,25 @@ export interface DeletePoolOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface PoolExistsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetNodeFileOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; /** * A timestamp indicating the last modified time of the resource known to the * client. The operation will be performed only if the resource on the service has @@ -175,328 +109,438 @@ export interface PoolExistsOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; + /** + * The byte range to be retrieved. The default is to retrieve the entire file. The + * format is bytes=startRange-endRange. + */ + ocpRange?: string; } /** Optional parameters. */ -export interface GetPoolOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteNodeFileOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. - */ - ifMatch?: string; - /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifNoneMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifModifiedSince?: Date; + ocpDate?: Date; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * Whether to delete children of a directory. If the filePath parameter represents + * a directory instead of a file, you can set recursive to true to delete the + * directory and all of the files and subdirectories in it. If recursive is false + * then the directory must be empty or deletion will fail. */ - ifUnmodifiedSince?: Date; - /** An OData $select clause. */ - $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; + recursive?: boolean; } /** Optional parameters. */ -export interface UpdatePoolOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListNodeExtensionsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ - timeOutInSeconds?: number; - /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. - */ - ifMatch?: string; + maxresults?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. */ - ifModifiedSince?: Date; + timeOutInSeconds?: number; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** An OData $select clause. */ + $select?: string[]; } /** Optional parameters. */ -export interface DisablePoolAutoScaleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetNodeExtensionOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** An OData $select clause. */ + $select?: string[]; } /** Optional parameters. */ -export interface EnablePoolAutoScaleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListNodesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ - timeOutInSeconds?: number; + maxresults?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifMatch?: string; + ocpDate?: Date; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. */ - ifNoneMatch?: string; + timeOutInSeconds?: number; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifModifiedSince?: Date; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. */ - ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; + $filter?: string; + /** An OData $select clause. */ + $select?: string[]; } /** Optional parameters. */ -export interface EvaluatePoolAutoScaleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface UploadNodeLogsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface ResizePoolOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetNodeRemoteDesktopFileOptionalParams + extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. - */ - ifMatch?: string; - /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. - */ - ifNoneMatch?: string; - /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifModifiedSince?: Date; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; + ocpDate?: Date; } /** Optional parameters. */ -export interface StopPoolResizeOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetNodeRemoteLoginSettingsOptionalParams + extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; +} + +/** Optional parameters. */ +export interface EnableNodeSchedulingOptionalParams extends OperationOptions { /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. */ - ifModifiedSince?: Date; + timeOutInSeconds?: number; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifUnmodifiedSince?: Date; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface ReplacePoolPropertiesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DisableNodeSchedulingOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** The options to use for disabling scheduling on the Compute Node. */ + body?: NodeDisableSchedulingOptions; } /** Optional parameters. */ -export interface RemoveNodesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ReimageNodeOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; + /** The options to use for reimaging the Compute Node. */ + body?: NodeReimageOptions; +} + +/** Optional parameters. */ +export interface RebootNodeOptionalParams extends OperationOptions { /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. */ - ifModifiedSince?: Date; + timeOutInSeconds?: number; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** The options to use for rebooting the Compute Node. */ + body?: NodeRebootOptions; } /** Optional parameters. */ -export interface ListSupportedImagesOptionalParams extends OperationOptions { +export interface GetNodeOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ - maxresults?: number; + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** An OData $select clause. */ + $select?: string[]; +} + +/** Optional parameters. */ +export interface ReplaceNodeUserOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - $filter?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface ListPoolNodeCountsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteNodeUserOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; +} + +/** Optional parameters. */ +export interface CreateNodeUserOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; +} + +/** Optional parameters. */ +export interface ListTaskFilesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-support-images. + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-task-files. */ $filter?: string; + /** + * Whether to list children of the Task directory. This parameter can be used in + * combination with the filter parameter to list specific type of files. + */ + recursive?: boolean; } /** Optional parameters. */ -export interface DeleteJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; /** * A timestamp indicating the last modified time of the resource known to the * client. The operation will be performed only if the resource on the service has @@ -512,26 +556,25 @@ export interface DeleteJobOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface GetJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetTaskFileOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service exactly matches the value specified by the client. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifMatch?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An ETag value associated with the version of the resource known to the client. - * The operation will be performed only if the resource's current ETag on the - * service does not match the value specified by the client. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifNoneMatch?: string; + ocpDate?: Date; /** * A timestamp indicating the last modified time of the resource known to the * client. The operation will be performed only if the resource on the service has @@ -544,21 +587,62 @@ export interface GetJobOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** An OData $select clause. */ - $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; + /** + * The byte range to be retrieved. The default is to retrieve the entire file. The + * format is bytes=startRange-endRange. + */ + ocpRange?: string; } /** Optional parameters. */ -export interface UpdateJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteTaskFileOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * Whether to delete children of a directory. If the filePath parameter represents + * a directory instead of a file, you can set recursive to true to delete the + * directory and all of the files and subdirectories in it. If recursive is false + * then the directory must be empty or deletion will fail. + */ + recursive?: boolean; +} + +/** Optional parameters. */ +export interface ReactivateTaskOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -583,19 +667,28 @@ export interface UpdateJobOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; } /** Optional parameters. */ -export interface ReplaceJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface TerminateTaskOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -620,19 +713,52 @@ export interface ReplaceJobOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; } /** Optional parameters. */ -export interface DisableJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListSubTasksOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** An OData $select clause. */ + $select?: string[]; +} + +/** Optional parameters. */ +export interface ReplaceTaskOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -657,19 +783,28 @@ export interface DisableJobOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; } /** Optional parameters. */ -export interface EnableJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetTaskOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -694,17 +829,32 @@ export interface EnableJobOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; + /** An OData $select clause. */ + $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; } /** Optional parameters. */ -export interface TerminateJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteTaskOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -729,42 +879,58 @@ export interface TerminateJobOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; - /** The options to use for terminating the Job. */ - body?: BatchJobTerminateOptions; } /** Optional parameters. */ -export interface CreateJobOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface CreateTaskCollectionOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface ListJobsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListTasksOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-jobs. + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-tasks. */ $filter?: string; /** An OData $select clause. */ @@ -774,144 +940,105 @@ export interface ListJobsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface ListJobsFromScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface CreateTaskOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ - maxresults?: number; + timeOutInSeconds?: number; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - timeOutInSeconds?: number; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - $filter?: string; - /** An OData $select clause. */ - $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; + ocpDate?: Date; } /** Optional parameters. */ -export interface ListJobPreparationAndReleaseTaskStatusOptionalParams - extends OperationOptions { +export interface ListJobSchedulesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. */ $filter?: string; /** An OData $select clause. */ $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; } /** Optional parameters. */ -export interface GetJobTaskCountsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface CreateJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; -} - -/** Optional parameters. */ -export interface CreateCertificateOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface ListCertificatesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - maxresults?: number; +export interface TerminateJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - $filter?: string; - /** An OData $select clause. */ - $select?: string[]; -} - -/** Optional parameters. */ -export interface CancelCertificateDeletionOptionalParams - extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - timeOutInSeconds?: number; -} - -/** Optional parameters. */ -export interface DeleteCertificateOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - timeOutInSeconds?: number; -} - -/** Optional parameters. */ -export interface GetCertificateOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - timeOutInSeconds?: number; - /** An OData $select clause. */ - $select?: string[]; -} - -/** Optional parameters. */ -export interface JobScheduleExistsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; - /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. - */ - timeOutInSeconds?: number; + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -939,14 +1066,25 @@ export interface JobScheduleExistsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface DeleteJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface EnableJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -974,14 +1112,25 @@ export interface DeleteJobScheduleOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface GetJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DisableJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1006,21 +1155,28 @@ export interface GetJobScheduleOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** An OData $select clause. */ - $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; } /** Optional parameters. */ -export interface UpdateJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ReplaceJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1045,19 +1201,28 @@ export interface UpdateJobScheduleOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; } /** Optional parameters. */ -export interface ReplaceJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface UpdateJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1082,19 +1247,28 @@ export interface ReplaceJobScheduleOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; } /** Optional parameters. */ -export interface DisableJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1119,17 +1293,32 @@ export interface DisableJobScheduleOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; + /** An OData $select clause. */ + $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; } /** Optional parameters. */ -export interface EnableJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteJobScheduleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1157,14 +1346,25 @@ export interface EnableJobScheduleOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface TerminateJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface JobScheduleExistsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1192,73 +1392,215 @@ export interface TerminateJobScheduleOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface CreateJobScheduleOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetCertificateOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** An OData $select clause. */ + $select?: string[]; } /** Optional parameters. */ -export interface ListJobSchedulesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteCertificateOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; +} + +/** Optional parameters. */ +export interface CancelCertificateDeletionOptionalParams + extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; +} + +/** Optional parameters. */ +export interface ListCertificatesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-job-schedules. + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates. */ $filter?: string; /** An OData $select clause. */ $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; } /** Optional parameters. */ -export interface CreateTaskOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface CreateCertificateOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; +} + +/** Optional parameters. */ +export interface GetJobTaskCountsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface ListTasksOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListJobPreparationAndReleaseTaskStatusOptionalParams + extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-tasks. + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status. + */ + $filter?: string; + /** An OData $select clause. */ + $select?: string[]; +} + +/** Optional parameters. */ +export interface ListJobsFromScheduleOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule. */ $filter?: string; /** An OData $select clause. */ @@ -1268,27 +1610,83 @@ export interface ListTasksOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface CreateTaskCollectionOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListJobsOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-jobs. + */ + $filter?: string; + /** An OData $select clause. */ + $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; +} + +/** Optional parameters. */ +export interface CreateJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface DeleteTaskOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface TerminateJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1313,17 +1711,30 @@ export interface DeleteTaskOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; + /** The options to use for terminating the Job. */ + body?: BatchJobTerminateOptions; } /** Optional parameters. */ -export interface GetTaskOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface EnableJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1348,21 +1759,28 @@ export interface GetTaskOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** An OData $select clause. */ - $select?: string[]; - /** An OData $expand clause. */ - $expand?: string[]; } /** Optional parameters. */ -export interface ReplaceTaskOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DisableJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1387,32 +1805,28 @@ export interface ReplaceTaskOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** Type of content */ - contentType?: string; } /** Optional parameters. */ -export interface ListSubTasksOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ReplaceJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** An OData $select clause. */ - $select?: string[]; -} - -/** Optional parameters. */ -export interface TerminateTaskOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - timeOutInSeconds?: number; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1440,14 +1854,25 @@ export interface TerminateTaskOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface ReactivateTaskOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface UpdateJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * An ETag value associated with the version of the resource known to the client. * The operation will be performed only if the resource's current ETag on the @@ -1475,32 +1900,37 @@ export interface ReactivateTaskOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface DeleteTaskFileOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * Whether to delete children of a directory. If the filePath parameter represents - * a directory instead of a file, you can set recursive to true to delete the - * directory and all of the files and subdirectories in it. If recursive is false - * then the directory must be empty or deletion will fail. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - recursive?: boolean; -} - -/** Optional parameters. */ -export interface GetTaskFileOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - timeOutInSeconds?: number; + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; /** * A timestamp indicating the last modified time of the resource known to the * client. The operation will be performed only if the resource on the service has @@ -1513,22 +1943,44 @@ export interface GetTaskFileOptionalParams extends OperationOptions { * not been modified since the specified time. */ ifUnmodifiedSince?: Date; - /** - * The byte range to be retrieved. The default is to retrieve the entire file. The - * format is bytes=startRange-endRange. - */ - ocpRange?: string; + /** An OData $select clause. */ + $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; } /** Optional parameters. */ -export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeleteJobOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; /** * A timestamp indicating the last modified time of the resource known to the * client. The operation will be performed only if the resource on the service has @@ -1544,314 +1996,654 @@ export interface GetTaskFilePropertiesOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface ListTaskFilesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListPoolNodeCountsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-task-files. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - $filter?: string; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * Whether to list children of the Task directory. This parameter can be used in - * combination with the filter parameter to list specific type of files. + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-support-images. */ - recursive?: boolean; + $filter?: string; } /** Optional parameters. */ -export interface CreateNodeUserOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListSupportedImagesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ - timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; -} - -/** Optional parameters. */ -export interface DeleteNodeUserOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; + maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-support-images. + */ + $filter?: string; } /** Optional parameters. */ -export interface ReplaceNodeUserOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface RemoveNodesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface GetNodeOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ReplacePoolPropertiesOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** An OData $select clause. */ - $select?: string[]; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface RebootNodeOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface StopPoolResizeOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; - /** The options to use for rebooting the Compute Node. */ - body?: NodeRebootOptions; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface ReimageNodeOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ResizePoolOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; - /** The options to use for reimaging the Compute Node. */ - body?: NodeReimageOptions; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface DisableNodeSchedulingOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface EvaluatePoolAutoScaleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; - /** The options to use for disabling scheduling on the Compute Node. */ - body?: NodeDisableSchedulingOptions; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface EnableNodeSchedulingOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface EnablePoolAutoScaleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface GetNodeRemoteLoginSettingsOptionalParams - extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DisablePoolAutoScaleOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface GetNodeRemoteDesktopFileOptionalParams - extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface UpdatePoolOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface UploadNodeLogsOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetPoolOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** Type of content */ - contentType?: string; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; + /** An OData $select clause. */ + $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; } /** Optional parameters. */ -export interface ListNodesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface PoolExistsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ - maxresults?: number; + timeOutInSeconds?: number; /** - * The maximum number of items to return in the response. A maximum of 1000 - * applications can be returned. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - timeOutInSeconds?: number; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-nodes-in-a-pool. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - $filter?: string; - /** An OData $select clause. */ - $select?: string[]; + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface GetNodeExtensionOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface DeletePoolOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; - /** An OData $select clause. */ - $select?: string[]; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service exactly matches the value specified by the client. + */ + ifMatch?: string; + /** + * An ETag value associated with the version of the resource known to the client. + * The operation will be performed only if the resource's current ETag on the + * service does not match the value specified by the client. + */ + ifNoneMatch?: string; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * been modified since the specified time. + */ + ifModifiedSince?: Date; + /** + * A timestamp indicating the last modified time of the resource known to the + * client. The operation will be performed only if the resource on the service has + * not been modified since the specified time. + */ + ifUnmodifiedSince?: Date; } /** Optional parameters. */ -export interface ListNodeExtensionsOptionalParams extends OperationOptions { +export interface ListPoolsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; + /** + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. + */ + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-pools. + */ + $filter?: string; /** An OData $select clause. */ $select?: string[]; + /** An OData $expand clause. */ + $expand?: string[]; } /** Optional parameters. */ -export interface DeleteNodeFileOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface CreatePoolOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * Whether to delete children of a directory. If the filePath parameter represents - * a directory instead of a file, you can set recursive to true to delete the - * directory and all of the files and subdirectories in it. If recursive is false - * then the directory must be empty or deletion will fail. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - recursive?: boolean; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; } /** Optional parameters. */ -export interface GetNodeFileOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListPoolUsageMetricsOptionalParams extends OperationOptions { + /** + * The maximum number of items to return in the response. A maximum of 1000 + * applications can be returned. + */ + maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifModifiedSince?: Date; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * The earliest time from which to include metrics. This must be at least two and + * a half hours before the current time. If not specified this defaults to the + * start time of the last aggregation interval currently available. */ - ifUnmodifiedSince?: Date; + starttime?: Date; /** - * The byte range to be retrieved. The default is to retrieve the entire file. The - * format is bytes=startRange-endRange. + * The latest time from which to include metrics. This must be at least two hours + * before the current time. If not specified this defaults to the end time of the + * last aggregation interval currently available. */ - ocpRange?: string; + endtime?: Date; + /** + * An OData $filter clause. For more information on constructing this filter, see + * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics. + */ + $filter?: string; } /** Optional parameters. */ -export interface GetNodeFilePropertiesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface GetApplicationOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * been modified since the specified time. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - ifModifiedSince?: Date; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; /** - * A timestamp indicating the last modified time of the resource known to the - * client. The operation will be performed only if the resource on the service has - * not been modified since the specified time. + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. */ - ifUnmodifiedSince?: Date; + ocpDate?: Date; } /** Optional parameters. */ -export interface ListNodeFilesOptionalParams extends OperationOptions { - /** The API version to use for this operation. */ - apiVersion?: string; +export interface ListApplicationsOptionalParams extends OperationOptions { /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ maxresults?: number; + /** + * The time the request was issued. Client libraries typically set this to the + * current system clock time; set it explicitly if you are calling the REST API + * directly. + */ + ocpDate?: Date; /** * The maximum number of items to return in the response. A maximum of 1000 * applications can be returned. */ timeOutInSeconds?: number; /** - * An OData $filter clause. For more information on constructing this filter, see - * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files. + * The caller-generated request identity, in the form of a GUID with no decoration + * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. */ - $filter?: string; - /** Whether to list children of a directory. */ - recursive?: boolean; + clientRequestId?: string; + /** Whether the server should return the client-request-id in the response. */ + returnClientRequestId?: boolean; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts index 33926738c5..fafb808c75 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/batchClient.ts @@ -5,158 +5,158 @@ import { createBatch, BatchContext, BatchClientOptionalParams, - listApplications, - getApplication, - listPoolUsageMetrics, - createPool, - listPools, - deletePool, - poolExists, - getPool, - updatePool, - disablePoolAutoScale, - enablePoolAutoScale, - evaluatePoolAutoScale, - resizePool, - stopPoolResize, - replacePoolProperties, - removeNodes, - listSupportedImages, - listPoolNodeCounts, - deleteJob, - getJob, - updateJob, - replaceJob, - disableJob, - enableJob, - terminateJob, - createJob, - listJobs, - listJobsFromSchedule, - listJobPreparationAndReleaseTaskStatus, - getJobTaskCounts, - createCertificate, - listCertificates, - cancelCertificateDeletion, - deleteCertificate, - getCertificate, - jobScheduleExists, - deleteJobSchedule, - getJobSchedule, - updateJobSchedule, - replaceJobSchedule, - disableJobSchedule, - enableJobSchedule, - terminateJobSchedule, - createJobSchedule, - listJobSchedules, - createTask, - listTasks, - createTaskCollection, - deleteTask, - getTask, - replaceTask, - listSubTasks, - terminateTask, - reactivateTask, - deleteTaskFile, - getTaskFile, - getTaskFileProperties, - listTaskFiles, - createNodeUser, - deleteNodeUser, - replaceNodeUser, - getNode, - rebootNode, - reimageNode, - disableNodeScheduling, - enableNodeScheduling, - getNodeRemoteLoginSettings, - getNodeRemoteDesktopFile, - uploadNodeLogs, - listNodes, - getNodeExtension, - listNodeExtensions, - deleteNodeFile, - getNodeFile, - getNodeFileProperties, listNodeFiles, - ListApplicationsOptionalParams, - GetApplicationOptionalParams, - ListPoolUsageMetricsOptionalParams, - CreatePoolOptionalParams, - ListPoolsOptionalParams, - DeletePoolOptionalParams, - PoolExistsOptionalParams, - GetPoolOptionalParams, - UpdatePoolOptionalParams, - DisablePoolAutoScaleOptionalParams, - EnablePoolAutoScaleOptionalParams, - EvaluatePoolAutoScaleOptionalParams, - ResizePoolOptionalParams, - StopPoolResizeOptionalParams, - ReplacePoolPropertiesOptionalParams, - RemoveNodesOptionalParams, - ListSupportedImagesOptionalParams, - ListPoolNodeCountsOptionalParams, - DeleteJobOptionalParams, - GetJobOptionalParams, - UpdateJobOptionalParams, - ReplaceJobOptionalParams, - DisableJobOptionalParams, - EnableJobOptionalParams, - TerminateJobOptionalParams, - CreateJobOptionalParams, - ListJobsOptionalParams, - ListJobsFromScheduleOptionalParams, - ListJobPreparationAndReleaseTaskStatusOptionalParams, - GetJobTaskCountsOptionalParams, - CreateCertificateOptionalParams, - ListCertificatesOptionalParams, - CancelCertificateDeletionOptionalParams, - DeleteCertificateOptionalParams, - GetCertificateOptionalParams, - JobScheduleExistsOptionalParams, - DeleteJobScheduleOptionalParams, - GetJobScheduleOptionalParams, - UpdateJobScheduleOptionalParams, - ReplaceJobScheduleOptionalParams, - DisableJobScheduleOptionalParams, - EnableJobScheduleOptionalParams, - TerminateJobScheduleOptionalParams, - CreateJobScheduleOptionalParams, - ListJobSchedulesOptionalParams, - CreateTaskOptionalParams, - ListTasksOptionalParams, - CreateTaskCollectionOptionalParams, - DeleteTaskOptionalParams, - GetTaskOptionalParams, - ReplaceTaskOptionalParams, - ListSubTasksOptionalParams, - TerminateTaskOptionalParams, - ReactivateTaskOptionalParams, - DeleteTaskFileOptionalParams, - GetTaskFileOptionalParams, - GetTaskFilePropertiesOptionalParams, - ListTaskFilesOptionalParams, - CreateNodeUserOptionalParams, - DeleteNodeUserOptionalParams, - ReplaceNodeUserOptionalParams, - GetNodeOptionalParams, - RebootNodeOptionalParams, - ReimageNodeOptionalParams, - DisableNodeSchedulingOptionalParams, - EnableNodeSchedulingOptionalParams, - GetNodeRemoteLoginSettingsOptionalParams, - GetNodeRemoteDesktopFileOptionalParams, - UploadNodeLogsOptionalParams, - ListNodesOptionalParams, - GetNodeExtensionOptionalParams, - ListNodeExtensionsOptionalParams, - DeleteNodeFileOptionalParams, - GetNodeFileOptionalParams, - GetNodeFilePropertiesOptionalParams, + getNodeFileProperties, + getNodeFile, + deleteNodeFile, + listNodeExtensions, + getNodeExtension, + listNodes, + uploadNodeLogs, + getNodeRemoteDesktopFile, + getNodeRemoteLoginSettings, + enableNodeScheduling, + disableNodeScheduling, + reimageNode, + rebootNode, + getNode, + replaceNodeUser, + deleteNodeUser, + createNodeUser, + listTaskFiles, + getTaskFileProperties, + getTaskFile, + deleteTaskFile, + reactivateTask, + terminateTask, + listSubTasks, + replaceTask, + getTask, + deleteTask, + createTaskCollection, + listTasks, + createTask, + listJobSchedules, + createJobSchedule, + terminateJobSchedule, + enableJobSchedule, + disableJobSchedule, + replaceJobSchedule, + updateJobSchedule, + getJobSchedule, + deleteJobSchedule, + jobScheduleExists, + getCertificate, + deleteCertificate, + cancelCertificateDeletion, + listCertificates, + createCertificate, + getJobTaskCounts, + listJobPreparationAndReleaseTaskStatus, + listJobsFromSchedule, + listJobs, + createJob, + terminateJob, + enableJob, + disableJob, + replaceJob, + updateJob, + getJob, + deleteJob, + listPoolNodeCounts, + listSupportedImages, + removeNodes, + replacePoolProperties, + stopPoolResize, + resizePool, + evaluatePoolAutoScale, + enablePoolAutoScale, + disablePoolAutoScale, + updatePool, + getPool, + poolExists, + deletePool, + listPools, + createPool, + listPoolUsageMetrics, + getApplication, + listApplications, ListNodeFilesOptionalParams, + GetNodeFilePropertiesOptionalParams, + GetNodeFileOptionalParams, + DeleteNodeFileOptionalParams, + ListNodeExtensionsOptionalParams, + GetNodeExtensionOptionalParams, + ListNodesOptionalParams, + UploadNodeLogsOptionalParams, + GetNodeRemoteDesktopFileOptionalParams, + GetNodeRemoteLoginSettingsOptionalParams, + EnableNodeSchedulingOptionalParams, + DisableNodeSchedulingOptionalParams, + ReimageNodeOptionalParams, + RebootNodeOptionalParams, + GetNodeOptionalParams, + ReplaceNodeUserOptionalParams, + DeleteNodeUserOptionalParams, + CreateNodeUserOptionalParams, + ListTaskFilesOptionalParams, + GetTaskFilePropertiesOptionalParams, + GetTaskFileOptionalParams, + DeleteTaskFileOptionalParams, + ReactivateTaskOptionalParams, + TerminateTaskOptionalParams, + ListSubTasksOptionalParams, + ReplaceTaskOptionalParams, + GetTaskOptionalParams, + DeleteTaskOptionalParams, + CreateTaskCollectionOptionalParams, + ListTasksOptionalParams, + CreateTaskOptionalParams, + ListJobSchedulesOptionalParams, + CreateJobScheduleOptionalParams, + TerminateJobScheduleOptionalParams, + EnableJobScheduleOptionalParams, + DisableJobScheduleOptionalParams, + ReplaceJobScheduleOptionalParams, + UpdateJobScheduleOptionalParams, + GetJobScheduleOptionalParams, + DeleteJobScheduleOptionalParams, + JobScheduleExistsOptionalParams, + GetCertificateOptionalParams, + DeleteCertificateOptionalParams, + CancelCertificateDeletionOptionalParams, + ListCertificatesOptionalParams, + CreateCertificateOptionalParams, + GetJobTaskCountsOptionalParams, + ListJobPreparationAndReleaseTaskStatusOptionalParams, + ListJobsFromScheduleOptionalParams, + ListJobsOptionalParams, + CreateJobOptionalParams, + TerminateJobOptionalParams, + EnableJobOptionalParams, + DisableJobOptionalParams, + ReplaceJobOptionalParams, + UpdateJobOptionalParams, + GetJobOptionalParams, + DeleteJobOptionalParams, + ListPoolNodeCountsOptionalParams, + ListSupportedImagesOptionalParams, + RemoveNodesOptionalParams, + ReplacePoolPropertiesOptionalParams, + StopPoolResizeOptionalParams, + ResizePoolOptionalParams, + EvaluatePoolAutoScaleOptionalParams, + EnablePoolAutoScaleOptionalParams, + DisablePoolAutoScaleOptionalParams, + UpdatePoolOptionalParams, + GetPoolOptionalParams, + PoolExistsOptionalParams, + DeletePoolOptionalParams, + ListPoolsOptionalParams, + CreatePoolOptionalParams, + ListPoolUsageMetricsOptionalParams, + GetApplicationOptionalParams, + ListApplicationsOptionalParams, } from "./api/index.js"; import { BatchNodeUserCreateOptions, @@ -224,510 +224,440 @@ export class BatchClient { this.pipeline = this._client.pipeline; } - /** - * This operation returns only Applications and versions that are available for - * use on Compute Nodes; that is, that can be used in an Package reference. For - * administrator information about applications and versions that are not yet - * available to Compute Nodes, use the Azure portal or the Azure Resource Manager - * API. - */ - listApplications( - options: ListApplicationsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listApplications(this._client, options); - } - - /** - * This operation returns only Applications and versions that are available for - * use on Compute Nodes; that is, that can be used in an Package reference. For - * administrator information about Applications and versions that are not yet - * available to Compute Nodes, use the Azure portal or the Azure Resource Manager - * API. - */ - getApplication( - applicationId: string, - options: GetApplicationOptionalParams = { requestOptions: {} }, - ): Promise { - return getApplication(this._client, applicationId, options); - } - - /** - * If you do not specify a $filter clause including a poolId, the response - * includes all Pools that existed in the Account in the time range of the - * returned aggregation intervals. If you do not specify a $filter clause - * including a startTime or endTime these filters default to the start and end - * times of the last aggregation interval currently available; that is, only the - * last aggregation interval is returned. - */ - listPoolUsageMetrics( - options: ListPoolUsageMetricsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listPoolUsageMetrics(this._client, options); + /** Lists all of the files in Task directories on the specified Compute Node. */ + listNodeFiles( + poolId: string, + nodeId: string, + options: ListNodeFilesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listNodeFiles(this._client, poolId, nodeId, options); } - /** - * When naming Pools, avoid including sensitive information such as user names or - * secret project names. This information may appear in telemetry logs accessible - * to Microsoft Support engineers. - */ - createPool( - body: BatchPoolCreateOptions, - options: CreatePoolOptionalParams = { requestOptions: {} }, + /** Gets the properties of the specified Compute Node file. */ + getNodeFileProperties( + poolId: string, + nodeId: string, + filePath: string, + options: GetNodeFilePropertiesOptionalParams = { requestOptions: {} }, ): Promise { - return createPool(this._client, body, options); + return getNodeFileProperties( + this._client, + poolId, + nodeId, + filePath, + options, + ); } - /** Lists all of the Pools in the specified Account. */ - listPools( - options: ListPoolsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listPools(this._client, options); + /** Returns the content of the specified Compute Node file. */ + getNodeFile( + poolId: string, + nodeId: string, + filePath: string, + options: GetNodeFileOptionalParams = { requestOptions: {} }, + ): Promise { + return getNodeFile(this._client, poolId, nodeId, filePath, options); } - /** - * When you request that a Pool be deleted, the following actions occur: the Pool - * state is set to deleting; any ongoing resize operation on the Pool are stopped; - * the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks - * running on existing Compute Nodes are terminated and requeued (as if a resize - * Pool operation had been requested with the default requeue option); finally, - * the Pool is removed from the system. Because running Tasks are requeued, the - * user can rerun these Tasks by updating their Job to target a different Pool. - * The Tasks can then run on the new Pool. If you want to override the requeue - * behavior, then you should call resize Pool explicitly to shrink the Pool to - * zero size before deleting the Pool. If you call an Update, Patch or Delete API - * on a Pool in the deleting state, it will fail with HTTP status code 409 with - * error code PoolBeingDeleted. - */ - deletePool( + /** Deletes the specified file from the Compute Node. */ + deleteNodeFile( poolId: string, - options: DeletePoolOptionalParams = { requestOptions: {} }, + nodeId: string, + filePath: string, + options: DeleteNodeFileOptionalParams = { requestOptions: {} }, ): Promise { - return deletePool(this._client, poolId, options); + return deleteNodeFile(this._client, poolId, nodeId, filePath, options); } - /** Gets basic properties of a Pool. */ - poolExists( + /** Lists the Compute Nodes Extensions in the specified Pool. */ + listNodeExtensions( poolId: string, - options: PoolExistsOptionalParams = { requestOptions: {} }, - ): Promise { - return poolExists(this._client, poolId, options); + nodeId: string, + options: ListNodeExtensionsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listNodeExtensions(this._client, poolId, nodeId, options); } - /** Gets information about the specified Pool. */ - getPool( + /** Gets information about the specified Compute Node Extension. */ + getNodeExtension( poolId: string, - options: GetPoolOptionalParams = { requestOptions: {} }, - ): Promise { - return getPool(this._client, poolId, options); + nodeId: string, + extensionName: string, + options: GetNodeExtensionOptionalParams = { requestOptions: {} }, + ): Promise { + return getNodeExtension( + this._client, + poolId, + nodeId, + extensionName, + options, + ); } - /** - * This only replaces the Pool properties specified in the request. For example, - * if the Pool has a StartTask associated with it, and a request does not specify - * a StartTask element, then the Pool keeps the existing StartTask. - */ - updatePool( + /** Lists the Compute Nodes in the specified Pool. */ + listNodes( poolId: string, - body: BatchPoolUpdateOptions, - options: UpdatePoolOptionalParams = { requestOptions: {} }, - ): Promise { - return updatePool(this._client, poolId, body, options); + options: ListNodesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listNodes(this._client, poolId, options); } - /** Disables automatic scaling for a Pool. */ - disablePoolAutoScale( + /** + * This is for gathering Azure Batch service log files in an automated fashion + * from Compute Nodes if you are experiencing an error and wish to escalate to + * Azure support. The Azure Batch service log files should be shared with Azure + * support to aid in debugging issues with the Batch service. + */ + uploadNodeLogs( poolId: string, - options: DisablePoolAutoScaleOptionalParams = { requestOptions: {} }, - ): Promise { - return disablePoolAutoScale(this._client, poolId, options); + nodeId: string, + body: UploadBatchServiceLogsOptions, + options: UploadNodeLogsOptionalParams = { requestOptions: {} }, + ): Promise { + return uploadNodeLogs(this._client, poolId, nodeId, body, options); } /** - * You cannot enable automatic scaling on a Pool if a resize operation is in - * progress on the Pool. If automatic scaling of the Pool is currently disabled, - * you must specify a valid autoscale formula as part of the request. If automatic - * scaling of the Pool is already enabled, you may specify a new autoscale formula - * and/or a new evaluation interval. You cannot call this API for the same Pool - * more than once every 30 seconds. + * Before you can access a Compute Node by using the RDP file, you must create a + * user Account on the Compute Node. This API can only be invoked on Pools created + * with a cloud service configuration. For Pools created with a virtual machine + * configuration, see the GetRemoteLoginSettings API. */ - enablePoolAutoScale( + getNodeRemoteDesktopFile( poolId: string, - body: BatchPoolEnableAutoScaleOptions, - options: EnablePoolAutoScaleOptionalParams = { requestOptions: {} }, - ): Promise { - return enablePoolAutoScale(this._client, poolId, body, options); + nodeId: string, + options: GetNodeRemoteDesktopFileOptionalParams = { requestOptions: {} }, + ): Promise { + return getNodeRemoteDesktopFile(this._client, poolId, nodeId, options); } /** - * This API is primarily for validating an autoscale formula, as it simply returns - * the result without applying the formula to the Pool. The Pool must have auto - * scaling enabled in order to evaluate a formula. + * Before you can remotely login to a Compute Node using the remote login + * settings, you must create a user Account on the Compute Node. This API can be + * invoked only on Pools created with the virtual machine configuration property. + * For Pools created with a cloud service configuration, see the GetRemoteDesktop + * API. */ - evaluatePoolAutoScale( + getNodeRemoteLoginSettings( poolId: string, - body: BatchPoolEvaluateAutoScaleOptions, - options: EvaluatePoolAutoScaleOptionalParams = { requestOptions: {} }, - ): Promise { - return evaluatePoolAutoScale(this._client, poolId, body, options); + nodeId: string, + options: GetNodeRemoteLoginSettingsOptionalParams = { requestOptions: {} }, + ): Promise { + return getNodeRemoteLoginSettings(this._client, poolId, nodeId, options); } /** - * You can only resize a Pool when its allocation state is steady. If the Pool is - * already resizing, the request fails with status code 409. When you resize a - * Pool, the Pool's allocation state changes from steady to resizing. You cannot - * resize Pools which are configured for automatic scaling. If you try to do this, - * the Batch service returns an error 409. If you resize a Pool downwards, the - * Batch service chooses which Compute Nodes to remove. To remove specific Compute - * Nodes, use the Pool remove Compute Nodes API instead. + * You can enable Task scheduling on a Compute Node only if its current scheduling + * state is disabled */ - resizePool( + enableNodeScheduling( poolId: string, - body: BatchPoolResizeOptions, - options: ResizePoolOptionalParams = { requestOptions: {} }, + nodeId: string, + options: EnableNodeSchedulingOptionalParams = { requestOptions: {} }, ): Promise { - return resizePool(this._client, poolId, body, options); + return enableNodeScheduling(this._client, poolId, nodeId, options); } /** - * This does not restore the Pool to its previous state before the resize - * operation: it only stops any further changes being made, and the Pool maintains - * its current state. After stopping, the Pool stabilizes at the number of Compute - * Nodes it was at when the stop operation was done. During the stop operation, - * the Pool allocation state changes first to stopping and then to steady. A - * resize operation need not be an explicit resize Pool request; this API can also - * be used to halt the initial sizing of the Pool when it is created. + * You can disable Task scheduling on a Compute Node only if its current + * scheduling state is enabled. */ - stopPoolResize( + disableNodeScheduling( poolId: string, - options: StopPoolResizeOptionalParams = { requestOptions: {} }, + nodeId: string, + options: DisableNodeSchedulingOptionalParams = { requestOptions: {} }, ): Promise { - return stopPoolResize(this._client, poolId, options); + return disableNodeScheduling(this._client, poolId, nodeId, options); } /** - * This fully replaces all the updatable properties of the Pool. For example, if - * the Pool has a StartTask associated with it and if StartTask is not specified - * with this request, then the Batch service will remove the existing StartTask. + * You can reinstall the operating system on a Compute Node only if it is in an + * idle or running state. This API can be invoked only on Pools created with the + * cloud service configuration property. */ - replacePoolProperties( + reimageNode( poolId: string, - body: BatchPoolReplaceOptions, - options: ReplacePoolPropertiesOptionalParams = { requestOptions: {} }, + nodeId: string, + options: ReimageNodeOptionalParams = { requestOptions: {} }, ): Promise { - return replacePoolProperties(this._client, poolId, body, options); + return reimageNode(this._client, poolId, nodeId, options); } - /** - * This operation can only run when the allocation state of the Pool is steady. - * When this operation runs, the allocation state changes from steady to resizing. - * Each request may remove up to 100 nodes. - */ - removeNodes( + /** You can restart a Compute Node only if it is in an idle or running state. */ + rebootNode( poolId: string, - body: NodeRemoveOptions, - options: RemoveNodesOptionalParams = { requestOptions: {} }, + nodeId: string, + options: RebootNodeOptionalParams = { requestOptions: {} }, ): Promise { - return removeNodes(this._client, poolId, body, options); + return rebootNode(this._client, poolId, nodeId, options); } - /** Lists all Virtual Machine Images supported by the Azure Batch service. */ - listSupportedImages( - options: ListSupportedImagesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listSupportedImages(this._client, options); + /** Gets information about the specified Compute Node. */ + getNode( + poolId: string, + nodeId: string, + options: GetNodeOptionalParams = { requestOptions: {} }, + ): Promise { + return getNode(this._client, poolId, nodeId, options); } /** - * Gets the number of Compute Nodes in each state, grouped by Pool. Note that the - * numbers returned may not always be up to date. If you need exact node counts, - * use a list query. + * This operation replaces of all the updatable properties of the Account. For + * example, if the expiryTime element is not specified, the current value is + * replaced with the default value, not left unmodified. You can update a user + * Account on a Compute Node only when it is in the idle or running state. */ - listPoolNodeCounts( - options: ListPoolNodeCountsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listPoolNodeCounts(this._client, options); + replaceNodeUser( + poolId: string, + nodeId: string, + userName: string, + body: BatchNodeUserUpdateOptions, + options: ReplaceNodeUserOptionalParams = { requestOptions: {} }, + ): Promise { + return replaceNodeUser( + this._client, + poolId, + nodeId, + userName, + body, + options, + ); } /** - * Deleting a Job also deletes all Tasks that are part of that Job, and all Job - * statistics. This also overrides the retention period for Task data; that is, if - * the Job contains Tasks which are still retained on Compute Nodes, the Batch - * services deletes those Tasks' working directories and all their contents. When - * a Delete Job request is received, the Batch service sets the Job to the - * deleting state. All update operations on a Job that is in deleting state will - * fail with status code 409 (Conflict), with additional information indicating - * that the Job is being deleted. + * You can delete a user Account to a Compute Node only when it is in the idle or + * running state. + */ + deleteNodeUser( + poolId: string, + nodeId: string, + userName: string, + options: DeleteNodeUserOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteNodeUser(this._client, poolId, nodeId, userName, options); + } + + /** + * You can add a user Account to a Compute Node only when it is in the idle or + * running state. */ - deleteJob( - jobId: string, - options: DeleteJobOptionalParams = { requestOptions: {} }, + createNodeUser( + poolId: string, + nodeId: string, + body: BatchNodeUserCreateOptions, + options: CreateNodeUserOptionalParams = { requestOptions: {} }, ): Promise { - return deleteJob(this._client, jobId, options); + return createNodeUser(this._client, poolId, nodeId, body, options); } - /** Gets information about the specified Job. */ - getJob( + /** Lists the files in a Task's directory on its Compute Node. */ + listTaskFiles( jobId: string, - options: GetJobOptionalParams = { requestOptions: {} }, - ): Promise { - return getJob(this._client, jobId, options); + taskId: string, + options: ListTaskFilesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTaskFiles(this._client, jobId, taskId, options); } - /** - * This replaces only the Job properties specified in the request. For example, if - * the Job has constraints, and a request does not specify the constraints - * element, then the Job keeps the existing constraints. - */ - updateJob( + /** Gets the properties of the specified Task file. */ + getTaskFileProperties( jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: GetTaskFilePropertiesOptionalParams = { requestOptions: {} }, ): Promise { - return updateJob(this._client, jobId, body, options); + return getTaskFileProperties( + this._client, + jobId, + taskId, + filePath, + options, + ); } - /** - * This fully replaces all the updatable properties of the Job. For example, if - * the Job has constraints associated with it and if constraints is not specified - * with this request, then the Batch service will remove the existing constraints. - */ - replaceJob( + /** Returns the content of the specified Task file. */ + getTaskFile( jobId: string, - body: BatchJob, - options: ReplaceJobOptionalParams = { requestOptions: {} }, - ): Promise { - return replaceJob(this._client, jobId, body, options); + taskId: string, + filePath: string, + options: GetTaskFileOptionalParams = { requestOptions: {} }, + ): Promise { + return getTaskFile(this._client, jobId, taskId, filePath, options); } - /** - * The Batch Service immediately moves the Job to the disabling state. Batch then - * uses the disableTasks parameter to determine what to do with the currently - * running Tasks of the Job. The Job remains in the disabling state until the - * disable operation is completed and all Tasks have been dealt with according to - * the disableTasks option; the Job then moves to the disabled state. No new Tasks - * are started under the Job until it moves back to active state. If you try to - * disable a Job that is in any state other than active, disabling, or disabled, - * the request fails with status code 409. - */ - disableJob( + /** Deletes the specified Task file from the Compute Node where the Task ran. */ + deleteTaskFile( jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptionalParams = { requestOptions: {} }, + taskId: string, + filePath: string, + options: DeleteTaskFileOptionalParams = { requestOptions: {} }, ): Promise { - return disableJob(this._client, jobId, body, options); + return deleteTaskFile(this._client, jobId, taskId, filePath, options); } /** - * When you call this API, the Batch service sets a disabled Job to the enabling - * state. After the this operation is completed, the Job moves to the active - * state, and scheduling of new Tasks under the Job resumes. The Batch service - * does not allow a Task to remain in the active state for more than 180 days. - * Therefore, if you enable a Job containing active Tasks which were added more - * than 180 days ago, those Tasks will not run. + * Reactivation makes a Task eligible to be retried again up to its maximum retry + * count. The Task's state is changed to active. As the Task is no longer in the + * completed state, any previous exit code or failure information is no longer + * available after reactivation. Each time a Task is reactivated, its retry count + * is reset to 0. Reactivation will fail for Tasks that are not completed or that + * previously completed successfully (with an exit code of 0). Additionally, it + * will fail if the Job has completed (or is terminating or deleting). */ - enableJob( + reactivateTask( jobId: string, - options: EnableJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: ReactivateTaskOptionalParams = { requestOptions: {} }, ): Promise { - return enableJob(this._client, jobId, options); + return reactivateTask(this._client, jobId, taskId, options); } /** - * When a Terminate Job request is received, the Batch service sets the Job to the - * terminating state. The Batch service then terminates any running Tasks - * associated with the Job and runs any required Job release Tasks. Then the Job - * moves into the completed state. If there are any Tasks in the Job in the active - * state, they will remain in the active state. Once a Job is terminated, new - * Tasks cannot be added and any remaining active Tasks will not be scheduled. + * When the Task has been terminated, it moves to the completed state. For + * multi-instance Tasks, the terminate Task operation applies synchronously to the + * primary task; subtasks are then terminated asynchronously in the background. */ - terminateJob( + terminateTask( jobId: string, - options: TerminateJobOptionalParams = { requestOptions: {} }, - ): Promise { - return terminateJob(this._client, jobId, options); - } - - /** - * The Batch service supports two ways to control the work done as part of a Job. - * In the first approach, the user specifies a Job Manager Task. The Batch service - * launches this Task when it is ready to start the Job. The Job Manager Task - * controls all other Tasks that run under this Job, by using the Task APIs. In - * the second approach, the user directly controls the execution of Tasks under an - * active Job, by using the Task APIs. Also note: when naming Jobs, avoid - * including sensitive information such as user names or secret project names. - * This information may appear in telemetry logs accessible to Microsoft Support - * engineers. - */ - createJob( - body: BatchJobCreateOptions, - options: CreateJobOptionalParams = { requestOptions: {} }, + taskId: string, + options: TerminateTaskOptionalParams = { requestOptions: {} }, ): Promise { - return createJob(this._client, body, options); + return terminateTask(this._client, jobId, taskId, options); } - /** Lists all of the Jobs in the specified Account. */ - listJobs( - options: ListJobsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listJobs(this._client, options); + /** If the Task is not a multi-instance Task then this returns an empty collection. */ + listSubTasks( + jobId: string, + taskId: string, + options: ListSubTasksOptionalParams = { requestOptions: {} }, + ): Promise { + return listSubTasks(this._client, jobId, taskId, options); } - /** Lists the Jobs that have been created under the specified Job Schedule. */ - listJobsFromSchedule( - jobScheduleId: string, - options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listJobsFromSchedule(this._client, jobScheduleId, options); + /** Updates the properties of the specified Task. */ + replaceTask( + jobId: string, + taskId: string, + body: BatchTask, + options: ReplaceTaskOptionalParams = { requestOptions: {} }, + ): Promise { + return replaceTask(this._client, jobId, taskId, body, options); } /** - * This API returns the Job Preparation and Job Release Task status on all Compute - * Nodes that have run the Job Preparation or Job Release Task. This includes - * Compute Nodes which have since been removed from the Pool. If this API is - * invoked on a Job which has no Job Preparation or Job Release Task, the Batch - * service returns HTTP status code 409 (Conflict) with an error code of - * JobPreparationTaskNotSpecified. + * For multi-instance Tasks, information such as affinityId, executionInfo and + * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve + * information about subtasks. */ - listJobPreparationAndReleaseTaskStatus( + getTask( jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { - requestOptions: {}, - }, - ): PagedAsyncIterableIterator { - return listJobPreparationAndReleaseTaskStatus(this._client, jobId, options); + taskId: string, + options: GetTaskOptionalParams = { requestOptions: {} }, + ): Promise { + return getTask(this._client, jobId, taskId, options); } /** - * Task counts provide a count of the Tasks by active, running or completed Task - * state, and a count of Tasks which succeeded or failed. Tasks in the preparing - * state are counted as running. Note that the numbers returned may not always be - * up to date. If you need exact task counts, use a list query. + * When a Task is deleted, all of the files in its directory on the Compute Node + * where it ran are also deleted (regardless of the retention time). For + * multi-instance Tasks, the delete Task operation applies synchronously to the + * primary task; subtasks and their files are then deleted asynchronously in the + * background. */ - getJobTaskCounts( + deleteTask( jobId: string, - options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, - ): Promise { - return getJobTaskCounts(this._client, jobId, options); - } - - /** Creates a Certificate to the specified Account. */ - createCertificate( - body: BatchCertificate, - options: CreateCertificateOptionalParams = { requestOptions: {} }, + taskId: string, + options: DeleteTaskOptionalParams = { requestOptions: {} }, ): Promise { - return createCertificate(this._client, body, options); + return deleteTask(this._client, jobId, taskId, options); } - /** Lists all of the Certificates that have been added to the specified Account. */ - listCertificates( - options: ListCertificatesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listCertificates(this._client, options); + /** + * Note that each Task must have a unique ID. The Batch service may not return the + * results for each Task in the same order the Tasks were submitted in this + * request. If the server times out or the connection is closed during the + * request, the request may have been partially or fully processed, or not at all. + * In such cases, the user should re-issue the request. Note that it is up to the + * user to correctly handle failures when re-issuing a request. For example, you + * should use the same Task IDs during a retry so that if the prior operation + * succeeded, the retry will not create extra Tasks unexpectedly. If the response + * contains any Tasks which failed to add, a client can retry the request. In a + * retry, it is most efficient to resubmit only Tasks that failed to add, and to + * omit Tasks that were successfully added on the first attempt. The maximum + * lifetime of a Task from addition to completion is 180 days. If a Task has not + * completed within 180 days of being added it will be terminated by the Batch + * service and left in whatever state it was in at that time. + */ + createTaskCollection( + jobId: string, + collection: BatchTaskCollection, + options: CreateTaskCollectionOptionalParams = { requestOptions: {} }, + ): Promise { + return createTaskCollection(this._client, jobId, collection, options); } /** - * If you try to delete a Certificate that is being used by a Pool or Compute - * Node, the status of the Certificate changes to deleteFailed. If you decide that - * you want to continue using the Certificate, you can use this operation to set - * the status of the Certificate back to active. If you intend to delete the - * Certificate, you do not need to run this operation after the deletion failed. - * You must make sure that the Certificate is not being used by any resources, and - * then you can try again to delete the Certificate. + * For multi-instance Tasks, information such as affinityId, executionInfo and + * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve + * information about subtasks. */ - cancelCertificateDeletion( - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, - ): Promise { - return cancelCertificateDeletion( - this._client, - thumbprintAlgorithm, - thumbprint, - options, - ); + listTasks( + jobId: string, + options: ListTasksOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTasks(this._client, jobId, options); } /** - * You cannot delete a Certificate if a resource (Pool or Compute Node) is using - * it. Before you can delete a Certificate, you must therefore make sure that the - * Certificate is not associated with any existing Pools, the Certificate is not - * installed on any Nodes (even if you remove a Certificate from a Pool, it is not - * removed from existing Compute Nodes in that Pool until they restart), and no - * running Tasks depend on the Certificate. If you try to delete a Certificate - * that is in use, the deletion fails. The Certificate status changes to - * deleteFailed. You can use Cancel Delete Certificate to set the status back to - * active if you decide that you want to continue using the Certificate. + * The maximum lifetime of a Task from addition to completion is 180 days. If a + * Task has not completed within 180 days of being added it will be terminated by + * the Batch service and left in whatever state it was in at that time. */ - deleteCertificate( - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptionalParams = { requestOptions: {} }, + createTask( + jobId: string, + body: BatchTaskCreateOptions, + options: CreateTaskOptionalParams = { requestOptions: {} }, ): Promise { - return deleteCertificate( - this._client, - thumbprintAlgorithm, - thumbprint, - options, - ); + return createTask(this._client, jobId, body, options); } - /** Gets information about the specified Certificate. */ - getCertificate( - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptionalParams = { requestOptions: {} }, - ): Promise { - return getCertificate( - this._client, - thumbprintAlgorithm, - thumbprint, - options, - ); + /** Lists all of the Job Schedules in the specified Account. */ + listJobSchedules( + options: ListJobSchedulesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listJobSchedules(this._client, options); } - /** Checks the specified Job Schedule exists. */ - jobScheduleExists( - jobScheduleId: string, - options: JobScheduleExistsOptionalParams = { requestOptions: {} }, + /** Creates a Job Schedule to the specified Account. */ + createJobSchedule( + body: BatchJobScheduleCreateOptions, + options: CreateJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - return jobScheduleExists(this._client, jobScheduleId, options); + return createJobSchedule(this._client, body, options); } - /** - * When you delete a Job Schedule, this also deletes all Jobs and Tasks under that - * schedule. When Tasks are deleted, all the files in their working directories on - * the Compute Nodes are also deleted (the retention period is ignored). The Job - * Schedule statistics are no longer accessible once the Job Schedule is deleted, - * though they are still counted towards Account lifetime statistics. - */ - deleteJobSchedule( + /** Terminates a Job Schedule. */ + terminateJobSchedule( jobScheduleId: string, - options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, + options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - return deleteJobSchedule(this._client, jobScheduleId, options); + return terminateJobSchedule(this._client, jobScheduleId, options); } - /** Gets information about the specified Job Schedule. */ - getJobSchedule( + /** Enables a Job Schedule. */ + enableJobSchedule( jobScheduleId: string, - options: GetJobScheduleOptionalParams = { requestOptions: {} }, - ): Promise { - return getJobSchedule(this._client, jobScheduleId, options); + options: EnableJobScheduleOptionalParams = { requestOptions: {} }, + ): Promise { + return enableJobSchedule(this._client, jobScheduleId, options); } - /** - * This replaces only the Job Schedule properties specified in the request. For - * example, if the schedule property is not specified with this request, then the - * Batch service will keep the existing schedule. Changes to a Job Schedule only - * impact Jobs created by the schedule after the update has taken place; currently - * running Jobs are unaffected. - */ - updateJobSchedule( + /** No new Jobs will be created until the Job Schedule is enabled again. */ + disableJobSchedule( jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, + options: DisableJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - return updateJobSchedule(this._client, jobScheduleId, body, options); + return disableJobSchedule(this._client, jobScheduleId, options); } /** @@ -745,439 +675,509 @@ export class BatchClient { return replaceJobSchedule(this._client, jobScheduleId, body, options); } - /** No new Jobs will be created until the Job Schedule is enabled again. */ - disableJobSchedule( + /** + * This replaces only the Job Schedule properties specified in the request. For + * example, if the schedule property is not specified with this request, then the + * Batch service will keep the existing schedule. Changes to a Job Schedule only + * impact Jobs created by the schedule after the update has taken place; currently + * running Jobs are unaffected. + */ + updateJobSchedule( jobScheduleId: string, - options: DisableJobScheduleOptionalParams = { requestOptions: {} }, + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - return disableJobSchedule(this._client, jobScheduleId, options); + return updateJobSchedule(this._client, jobScheduleId, body, options); } - /** Enables a Job Schedule. */ - enableJobSchedule( + /** Gets information about the specified Job Schedule. */ + getJobSchedule( jobScheduleId: string, - options: EnableJobScheduleOptionalParams = { requestOptions: {} }, - ): Promise { - return enableJobSchedule(this._client, jobScheduleId, options); + options: GetJobScheduleOptionalParams = { requestOptions: {} }, + ): Promise { + return getJobSchedule(this._client, jobScheduleId, options); } - /** Terminates a Job Schedule. */ - terminateJobSchedule( + /** + * When you delete a Job Schedule, this also deletes all Jobs and Tasks under that + * schedule. When Tasks are deleted, all the files in their working directories on + * the Compute Nodes are also deleted (the retention period is ignored). The Job + * Schedule statistics are no longer accessible once the Job Schedule is deleted, + * though they are still counted towards Account lifetime statistics. + */ + deleteJobSchedule( jobScheduleId: string, - options: TerminateJobScheduleOptionalParams = { requestOptions: {} }, + options: DeleteJobScheduleOptionalParams = { requestOptions: {} }, ): Promise { - return terminateJobSchedule(this._client, jobScheduleId, options); + return deleteJobSchedule(this._client, jobScheduleId, options); } - /** Creates a Job Schedule to the specified Account. */ - createJobSchedule( - body: BatchJobScheduleCreateOptions, - options: CreateJobScheduleOptionalParams = { requestOptions: {} }, + /** Checks the specified Job Schedule exists. */ + jobScheduleExists( + jobScheduleId: string, + options: JobScheduleExistsOptionalParams = { requestOptions: {} }, ): Promise { - return createJobSchedule(this._client, body, options); + return jobScheduleExists(this._client, jobScheduleId, options); } - /** Lists all of the Job Schedules in the specified Account. */ - listJobSchedules( - options: ListJobSchedulesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listJobSchedules(this._client, options); + /** Gets information about the specified Certificate. */ + getCertificate( + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptionalParams = { requestOptions: {} }, + ): Promise { + return getCertificate( + this._client, + thumbprintAlgorithm, + thumbprint, + options, + ); } /** - * The maximum lifetime of a Task from addition to completion is 180 days. If a - * Task has not completed within 180 days of being added it will be terminated by - * the Batch service and left in whatever state it was in at that time. + * You cannot delete a Certificate if a resource (Pool or Compute Node) is using + * it. Before you can delete a Certificate, you must therefore make sure that the + * Certificate is not associated with any existing Pools, the Certificate is not + * installed on any Nodes (even if you remove a Certificate from a Pool, it is not + * removed from existing Compute Nodes in that Pool until they restart), and no + * running Tasks depend on the Certificate. If you try to delete a Certificate + * that is in use, the deletion fails. The Certificate status changes to + * deleteFailed. You can use Cancel Delete Certificate to set the status back to + * active if you decide that you want to continue using the Certificate. */ - createTask( - jobId: string, - body: BatchTaskCreateOptions, - options: CreateTaskOptionalParams = { requestOptions: {} }, + deleteCertificate( + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptionalParams = { requestOptions: {} }, ): Promise { - return createTask(this._client, jobId, body, options); + return deleteCertificate( + this._client, + thumbprintAlgorithm, + thumbprint, + options, + ); } /** - * For multi-instance Tasks, information such as affinityId, executionInfo and - * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve - * information about subtasks. + * If you try to delete a Certificate that is being used by a Pool or Compute + * Node, the status of the Certificate changes to deleteFailed. If you decide that + * you want to continue using the Certificate, you can use this operation to set + * the status of the Certificate back to active. If you intend to delete the + * Certificate, you do not need to run this operation after the deletion failed. + * You must make sure that the Certificate is not being used by any resources, and + * then you can try again to delete the Certificate. */ - listTasks( - jobId: string, - options: ListTasksOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTasks(this._client, jobId, options); + cancelCertificateDeletion( + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptionalParams = { requestOptions: {} }, + ): Promise { + return cancelCertificateDeletion( + this._client, + thumbprintAlgorithm, + thumbprint, + options, + ); } - /** - * Note that each Task must have a unique ID. The Batch service may not return the - * results for each Task in the same order the Tasks were submitted in this - * request. If the server times out or the connection is closed during the - * request, the request may have been partially or fully processed, or not at all. - * In such cases, the user should re-issue the request. Note that it is up to the - * user to correctly handle failures when re-issuing a request. For example, you - * should use the same Task IDs during a retry so that if the prior operation - * succeeded, the retry will not create extra Tasks unexpectedly. If the response - * contains any Tasks which failed to add, a client can retry the request. In a - * retry, it is most efficient to resubmit only Tasks that failed to add, and to - * omit Tasks that were successfully added on the first attempt. The maximum - * lifetime of a Task from addition to completion is 180 days. If a Task has not - * completed within 180 days of being added it will be terminated by the Batch - * service and left in whatever state it was in at that time. - */ - createTaskCollection( - jobId: string, - collection: BatchTaskCollection, - options: CreateTaskCollectionOptionalParams = { requestOptions: {} }, - ): Promise { - return createTaskCollection(this._client, jobId, collection, options); + /** Lists all of the Certificates that have been added to the specified Account. */ + listCertificates( + options: ListCertificatesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listCertificates(this._client, options); + } + + /** Creates a Certificate to the specified Account. */ + createCertificate( + body: BatchCertificate, + options: CreateCertificateOptionalParams = { requestOptions: {} }, + ): Promise { + return createCertificate(this._client, body, options); } /** - * When a Task is deleted, all of the files in its directory on the Compute Node - * where it ran are also deleted (regardless of the retention time). For - * multi-instance Tasks, the delete Task operation applies synchronously to the - * primary task; subtasks and their files are then deleted asynchronously in the - * background. + * Task counts provide a count of the Tasks by active, running or completed Task + * state, and a count of Tasks which succeeded or failed. Tasks in the preparing + * state are counted as running. Note that the numbers returned may not always be + * up to date. If you need exact task counts, use a list query. */ - deleteTask( + getJobTaskCounts( jobId: string, - taskId: string, - options: DeleteTaskOptionalParams = { requestOptions: {} }, - ): Promise { - return deleteTask(this._client, jobId, taskId, options); + options: GetJobTaskCountsOptionalParams = { requestOptions: {} }, + ): Promise { + return getJobTaskCounts(this._client, jobId, options); } /** - * For multi-instance Tasks, information such as affinityId, executionInfo and - * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve - * information about subtasks. + * This API returns the Job Preparation and Job Release Task status on all Compute + * Nodes that have run the Job Preparation or Job Release Task. This includes + * Compute Nodes which have since been removed from the Pool. If this API is + * invoked on a Job which has no Job Preparation or Job Release Task, the Batch + * service returns HTTP status code 409 (Conflict) with an error code of + * JobPreparationTaskNotSpecified. */ - getTask( + listJobPreparationAndReleaseTaskStatus( jobId: string, - taskId: string, - options: GetTaskOptionalParams = { requestOptions: {} }, - ): Promise { - return getTask(this._client, jobId, taskId, options); + options: ListJobPreparationAndReleaseTaskStatusOptionalParams = { + requestOptions: {}, + }, + ): PagedAsyncIterableIterator { + return listJobPreparationAndReleaseTaskStatus(this._client, jobId, options); } - /** Updates the properties of the specified Task. */ - replaceTask( - jobId: string, - taskId: string, - body: BatchTask, - options: ReplaceTaskOptionalParams = { requestOptions: {} }, - ): Promise { - return replaceTask(this._client, jobId, taskId, body, options); + /** Lists the Jobs that have been created under the specified Job Schedule. */ + listJobsFromSchedule( + jobScheduleId: string, + options: ListJobsFromScheduleOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listJobsFromSchedule(this._client, jobScheduleId, options); } - /** If the Task is not a multi-instance Task then this returns an empty collection. */ - listSubTasks( - jobId: string, - taskId: string, - options: ListSubTasksOptionalParams = { requestOptions: {} }, - ): Promise { - return listSubTasks(this._client, jobId, taskId, options); + /** Lists all of the Jobs in the specified Account. */ + listJobs( + options: ListJobsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listJobs(this._client, options); } /** - * When the Task has been terminated, it moves to the completed state. For - * multi-instance Tasks, the terminate Task operation applies synchronously to the - * primary task; subtasks are then terminated asynchronously in the background. + * The Batch service supports two ways to control the work done as part of a Job. + * In the first approach, the user specifies a Job Manager Task. The Batch service + * launches this Task when it is ready to start the Job. The Job Manager Task + * controls all other Tasks that run under this Job, by using the Task APIs. In + * the second approach, the user directly controls the execution of Tasks under an + * active Job, by using the Task APIs. Also note: when naming Jobs, avoid + * including sensitive information such as user names or secret project names. + * This information may appear in telemetry logs accessible to Microsoft Support + * engineers. */ - terminateTask( - jobId: string, - taskId: string, - options: TerminateTaskOptionalParams = { requestOptions: {} }, + createJob( + body: BatchJobCreateOptions, + options: CreateJobOptionalParams = { requestOptions: {} }, ): Promise { - return terminateTask(this._client, jobId, taskId, options); + return createJob(this._client, body, options); } /** - * Reactivation makes a Task eligible to be retried again up to its maximum retry - * count. The Task's state is changed to active. As the Task is no longer in the - * completed state, any previous exit code or failure information is no longer - * available after reactivation. Each time a Task is reactivated, its retry count - * is reset to 0. Reactivation will fail for Tasks that are not completed or that - * previously completed successfully (with an exit code of 0). Additionally, it - * will fail if the Job has completed (or is terminating or deleting). + * When a Terminate Job request is received, the Batch service sets the Job to the + * terminating state. The Batch service then terminates any running Tasks + * associated with the Job and runs any required Job release Tasks. Then the Job + * moves into the completed state. If there are any Tasks in the Job in the active + * state, they will remain in the active state. Once a Job is terminated, new + * Tasks cannot be added and any remaining active Tasks will not be scheduled. */ - reactivateTask( + terminateJob( jobId: string, - taskId: string, - options: ReactivateTaskOptionalParams = { requestOptions: {} }, + options: TerminateJobOptionalParams = { requestOptions: {} }, ): Promise { - return reactivateTask(this._client, jobId, taskId, options); + return terminateJob(this._client, jobId, options); } - /** Deletes the specified Task file from the Compute Node where the Task ran. */ - deleteTaskFile( + /** + * When you call this API, the Batch service sets a disabled Job to the enabling + * state. After the this operation is completed, the Job moves to the active + * state, and scheduling of new Tasks under the Job resumes. The Batch service + * does not allow a Task to remain in the active state for more than 180 days. + * Therefore, if you enable a Job containing active Tasks which were added more + * than 180 days ago, those Tasks will not run. + */ + enableJob( jobId: string, - taskId: string, - filePath: string, - options: DeleteTaskFileOptionalParams = { requestOptions: {} }, + options: EnableJobOptionalParams = { requestOptions: {} }, ): Promise { - return deleteTaskFile(this._client, jobId, taskId, filePath, options); - } - - /** Returns the content of the specified Task file. */ - getTaskFile( - jobId: string, - taskId: string, - filePath: string, - options: GetTaskFileOptionalParams = { requestOptions: {} }, - ): Promise { - return getTaskFile(this._client, jobId, taskId, filePath, options); + return enableJob(this._client, jobId, options); } - /** Gets the properties of the specified Task file. */ - getTaskFileProperties( + /** + * The Batch Service immediately moves the Job to the disabling state. Batch then + * uses the disableTasks parameter to determine what to do with the currently + * running Tasks of the Job. The Job remains in the disabling state until the + * disable operation is completed and all Tasks have been dealt with according to + * the disableTasks option; the Job then moves to the disabled state. No new Tasks + * are started under the Job until it moves back to active state. If you try to + * disable a Job that is in any state other than active, disabling, or disabled, + * the request fails with status code 409. + */ + disableJob( jobId: string, - taskId: string, - filePath: string, - options: GetTaskFilePropertiesOptionalParams = { requestOptions: {} }, + body: BatchJobDisableOptions, + options: DisableJobOptionalParams = { requestOptions: {} }, ): Promise { - return getTaskFileProperties( - this._client, - jobId, - taskId, - filePath, - options, - ); + return disableJob(this._client, jobId, body, options); } - /** Lists the files in a Task's directory on its Compute Node. */ - listTaskFiles( + /** + * This fully replaces all the updatable properties of the Job. For example, if + * the Job has constraints associated with it and if constraints is not specified + * with this request, then the Batch service will remove the existing constraints. + */ + replaceJob( jobId: string, - taskId: string, - options: ListTaskFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTaskFiles(this._client, jobId, taskId, options); + body: BatchJob, + options: ReplaceJobOptionalParams = { requestOptions: {} }, + ): Promise { + return replaceJob(this._client, jobId, body, options); } /** - * You can add a user Account to a Compute Node only when it is in the idle or - * running state. + * This replaces only the Job properties specified in the request. For example, if + * the Job has constraints, and a request does not specify the constraints + * element, then the Job keeps the existing constraints. */ - createNodeUser( - poolId: string, - nodeId: string, - body: BatchNodeUserCreateOptions, - options: CreateNodeUserOptionalParams = { requestOptions: {} }, + updateJob( + jobId: string, + body: BatchJobUpdateOptions, + options: UpdateJobOptionalParams = { requestOptions: {} }, ): Promise { - return createNodeUser(this._client, poolId, nodeId, body, options); + return updateJob(this._client, jobId, body, options); + } + + /** Gets information about the specified Job. */ + getJob( + jobId: string, + options: GetJobOptionalParams = { requestOptions: {} }, + ): Promise { + return getJob(this._client, jobId, options); } /** - * You can delete a user Account to a Compute Node only when it is in the idle or - * running state. + * Deleting a Job also deletes all Tasks that are part of that Job, and all Job + * statistics. This also overrides the retention period for Task data; that is, if + * the Job contains Tasks which are still retained on Compute Nodes, the Batch + * services deletes those Tasks' working directories and all their contents. When + * a Delete Job request is received, the Batch service sets the Job to the + * deleting state. All update operations on a Job that is in deleting state will + * fail with status code 409 (Conflict), with additional information indicating + * that the Job is being deleted. */ - deleteNodeUser( - poolId: string, - nodeId: string, - userName: string, - options: DeleteNodeUserOptionalParams = { requestOptions: {} }, + deleteJob( + jobId: string, + options: DeleteJobOptionalParams = { requestOptions: {} }, ): Promise { - return deleteNodeUser(this._client, poolId, nodeId, userName, options); + return deleteJob(this._client, jobId, options); } /** - * This operation replaces of all the updatable properties of the Account. For - * example, if the expiryTime element is not specified, the current value is - * replaced with the default value, not left unmodified. You can update a user - * Account on a Compute Node only when it is in the idle or running state. + * Gets the number of Compute Nodes in each state, grouped by Pool. Note that the + * numbers returned may not always be up to date. If you need exact node counts, + * use a list query. */ - replaceNodeUser( - poolId: string, - nodeId: string, - userName: string, - body: BatchNodeUserUpdateOptions, - options: ReplaceNodeUserOptionalParams = { requestOptions: {} }, - ): Promise { - return replaceNodeUser( - this._client, - poolId, - nodeId, - userName, - body, - options, - ); + listPoolNodeCounts( + options: ListPoolNodeCountsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listPoolNodeCounts(this._client, options); } - /** Gets information about the specified Compute Node. */ - getNode( - poolId: string, - nodeId: string, - options: GetNodeOptionalParams = { requestOptions: {} }, - ): Promise { - return getNode(this._client, poolId, nodeId, options); + /** Lists all Virtual Machine Images supported by the Azure Batch service. */ + listSupportedImages( + options: ListSupportedImagesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listSupportedImages(this._client, options); } - /** You can restart a Compute Node only if it is in an idle or running state. */ - rebootNode( + /** + * This operation can only run when the allocation state of the Pool is steady. + * When this operation runs, the allocation state changes from steady to resizing. + * Each request may remove up to 100 nodes. + */ + removeNodes( poolId: string, - nodeId: string, - options: RebootNodeOptionalParams = { requestOptions: {} }, + body: NodeRemoveOptions, + options: RemoveNodesOptionalParams = { requestOptions: {} }, ): Promise { - return rebootNode(this._client, poolId, nodeId, options); + return removeNodes(this._client, poolId, body, options); } /** - * You can reinstall the operating system on a Compute Node only if it is in an - * idle or running state. This API can be invoked only on Pools created with the - * cloud service configuration property. + * This fully replaces all the updatable properties of the Pool. For example, if + * the Pool has a StartTask associated with it and if StartTask is not specified + * with this request, then the Batch service will remove the existing StartTask. */ - reimageNode( + replacePoolProperties( poolId: string, - nodeId: string, - options: ReimageNodeOptionalParams = { requestOptions: {} }, + body: BatchPoolReplaceOptions, + options: ReplacePoolPropertiesOptionalParams = { requestOptions: {} }, ): Promise { - return reimageNode(this._client, poolId, nodeId, options); + return replacePoolProperties(this._client, poolId, body, options); } /** - * You can disable Task scheduling on a Compute Node only if its current - * scheduling state is enabled. + * This does not restore the Pool to its previous state before the resize + * operation: it only stops any further changes being made, and the Pool maintains + * its current state. After stopping, the Pool stabilizes at the number of Compute + * Nodes it was at when the stop operation was done. During the stop operation, + * the Pool allocation state changes first to stopping and then to steady. A + * resize operation need not be an explicit resize Pool request; this API can also + * be used to halt the initial sizing of the Pool when it is created. */ - disableNodeScheduling( + stopPoolResize( poolId: string, - nodeId: string, - options: DisableNodeSchedulingOptionalParams = { requestOptions: {} }, + options: StopPoolResizeOptionalParams = { requestOptions: {} }, ): Promise { - return disableNodeScheduling(this._client, poolId, nodeId, options); + return stopPoolResize(this._client, poolId, options); } /** - * You can enable Task scheduling on a Compute Node only if its current scheduling - * state is disabled + * You can only resize a Pool when its allocation state is steady. If the Pool is + * already resizing, the request fails with status code 409. When you resize a + * Pool, the Pool's allocation state changes from steady to resizing. You cannot + * resize Pools which are configured for automatic scaling. If you try to do this, + * the Batch service returns an error 409. If you resize a Pool downwards, the + * Batch service chooses which Compute Nodes to remove. To remove specific Compute + * Nodes, use the Pool remove Compute Nodes API instead. */ - enableNodeScheduling( + resizePool( poolId: string, - nodeId: string, - options: EnableNodeSchedulingOptionalParams = { requestOptions: {} }, + body: BatchPoolResizeOptions, + options: ResizePoolOptionalParams = { requestOptions: {} }, ): Promise { - return enableNodeScheduling(this._client, poolId, nodeId, options); + return resizePool(this._client, poolId, body, options); } /** - * Before you can remotely login to a Compute Node using the remote login - * settings, you must create a user Account on the Compute Node. This API can be - * invoked only on Pools created with the virtual machine configuration property. - * For Pools created with a cloud service configuration, see the GetRemoteDesktop - * API. + * This API is primarily for validating an autoscale formula, as it simply returns + * the result without applying the formula to the Pool. The Pool must have auto + * scaling enabled in order to evaluate a formula. */ - getNodeRemoteLoginSettings( + evaluatePoolAutoScale( poolId: string, - nodeId: string, - options: GetNodeRemoteLoginSettingsOptionalParams = { requestOptions: {} }, - ): Promise { - return getNodeRemoteLoginSettings(this._client, poolId, nodeId, options); + body: BatchPoolEvaluateAutoScaleOptions, + options: EvaluatePoolAutoScaleOptionalParams = { requestOptions: {} }, + ): Promise { + return evaluatePoolAutoScale(this._client, poolId, body, options); } /** - * Before you can access a Compute Node by using the RDP file, you must create a - * user Account on the Compute Node. This API can only be invoked on Pools created - * with a cloud service configuration. For Pools created with a virtual machine - * configuration, see the GetRemoteLoginSettings API. + * You cannot enable automatic scaling on a Pool if a resize operation is in + * progress on the Pool. If automatic scaling of the Pool is currently disabled, + * you must specify a valid autoscale formula as part of the request. If automatic + * scaling of the Pool is already enabled, you may specify a new autoscale formula + * and/or a new evaluation interval. You cannot call this API for the same Pool + * more than once every 30 seconds. */ - getNodeRemoteDesktopFile( + enablePoolAutoScale( poolId: string, - nodeId: string, - options: GetNodeRemoteDesktopFileOptionalParams = { requestOptions: {} }, - ): Promise { - return getNodeRemoteDesktopFile(this._client, poolId, nodeId, options); + body: BatchPoolEnableAutoScaleOptions, + options: EnablePoolAutoScaleOptionalParams = { requestOptions: {} }, + ): Promise { + return enablePoolAutoScale(this._client, poolId, body, options); } - /** - * This is for gathering Azure Batch service log files in an automated fashion - * from Compute Nodes if you are experiencing an error and wish to escalate to - * Azure support. The Azure Batch service log files should be shared with Azure - * support to aid in debugging issues with the Batch service. - */ - uploadNodeLogs( + /** Disables automatic scaling for a Pool. */ + disablePoolAutoScale( poolId: string, - nodeId: string, - body: UploadBatchServiceLogsOptions, - options: UploadNodeLogsOptionalParams = { requestOptions: {} }, - ): Promise { - return uploadNodeLogs(this._client, poolId, nodeId, body, options); + options: DisablePoolAutoScaleOptionalParams = { requestOptions: {} }, + ): Promise { + return disablePoolAutoScale(this._client, poolId, options); } - /** Lists the Compute Nodes in the specified Pool. */ - listNodes( + /** + * This only replaces the Pool properties specified in the request. For example, + * if the Pool has a StartTask associated with it, and a request does not specify + * a StartTask element, then the Pool keeps the existing StartTask. + */ + updatePool( poolId: string, - options: ListNodesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listNodes(this._client, poolId, options); + body: BatchPoolUpdateOptions, + options: UpdatePoolOptionalParams = { requestOptions: {} }, + ): Promise { + return updatePool(this._client, poolId, body, options); } - /** Gets information about the specified Compute Node Extension. */ - getNodeExtension( + /** Gets information about the specified Pool. */ + getPool( poolId: string, - nodeId: string, - extensionName: string, - options: GetNodeExtensionOptionalParams = { requestOptions: {} }, - ): Promise { - return getNodeExtension( - this._client, - poolId, - nodeId, - extensionName, - options, - ); + options: GetPoolOptionalParams = { requestOptions: {} }, + ): Promise { + return getPool(this._client, poolId, options); } - /** Lists the Compute Nodes Extensions in the specified Pool. */ - listNodeExtensions( + /** Gets basic properties of a Pool. */ + poolExists( poolId: string, - nodeId: string, - options: ListNodeExtensionsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listNodeExtensions(this._client, poolId, nodeId, options); + options: PoolExistsOptionalParams = { requestOptions: {} }, + ): Promise { + return poolExists(this._client, poolId, options); } - /** Deletes the specified file from the Compute Node. */ - deleteNodeFile( + /** + * When you request that a Pool be deleted, the following actions occur: the Pool + * state is set to deleting; any ongoing resize operation on the Pool are stopped; + * the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks + * running on existing Compute Nodes are terminated and requeued (as if a resize + * Pool operation had been requested with the default requeue option); finally, + * the Pool is removed from the system. Because running Tasks are requeued, the + * user can rerun these Tasks by updating their Job to target a different Pool. + * The Tasks can then run on the new Pool. If you want to override the requeue + * behavior, then you should call resize Pool explicitly to shrink the Pool to + * zero size before deleting the Pool. If you call an Update, Patch or Delete API + * on a Pool in the deleting state, it will fail with HTTP status code 409 with + * error code PoolBeingDeleted. + */ + deletePool( poolId: string, - nodeId: string, - filePath: string, - options: DeleteNodeFileOptionalParams = { requestOptions: {} }, + options: DeletePoolOptionalParams = { requestOptions: {} }, ): Promise { - return deleteNodeFile(this._client, poolId, nodeId, filePath, options); + return deletePool(this._client, poolId, options); } - /** Returns the content of the specified Compute Node file. */ - getNodeFile( - poolId: string, - nodeId: string, - filePath: string, - options: GetNodeFileOptionalParams = { requestOptions: {} }, - ): Promise { - return getNodeFile(this._client, poolId, nodeId, filePath, options); + /** Lists all of the Pools in the specified Account. */ + listPools( + options: ListPoolsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listPools(this._client, options); } - /** Gets the properties of the specified Compute Node file. */ - getNodeFileProperties( - poolId: string, - nodeId: string, - filePath: string, - options: GetNodeFilePropertiesOptionalParams = { requestOptions: {} }, + /** + * When naming Pools, avoid including sensitive information such as user names or + * secret project names. This information may appear in telemetry logs accessible + * to Microsoft Support engineers. + */ + createPool( + body: BatchPoolCreateOptions, + options: CreatePoolOptionalParams = { requestOptions: {} }, ): Promise { - return getNodeFileProperties( - this._client, - poolId, - nodeId, - filePath, - options, - ); + return createPool(this._client, body, options); } - /** Lists all of the files in Task directories on the specified Compute Node. */ - listNodeFiles( - poolId: string, - nodeId: string, - options: ListNodeFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listNodeFiles(this._client, poolId, nodeId, options); + /** + * If you do not specify a $filter clause including a poolId, the response + * includes all Pools that existed in the Account in the time range of the + * returned aggregation intervals. If you do not specify a $filter clause + * including a startTime or endTime these filters default to the start and end + * times of the last aggregation interval currently available; that is, only the + * last aggregation interval is returned. + */ + listPoolUsageMetrics( + options: ListPoolUsageMetricsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listPoolUsageMetrics(this._client, options); + } + + /** + * This operation returns only Applications and versions that are available for + * use on Compute Nodes; that is, that can be used in an Package reference. For + * administrator information about Applications and versions that are not yet + * available to Compute Nodes, use the Azure portal or the Azure Resource Manager + * API. + */ + getApplication( + applicationId: string, + options: GetApplicationOptionalParams = { requestOptions: {} }, + ): Promise { + return getApplication(this._client, applicationId, options); + } + + /** + * This operation returns only Applications and versions that are available for + * use on Compute Nodes; that is, that can be used in an Package reference. For + * administrator information about applications and versions that are not yet + * available to Compute Nodes, use the Azure portal or the Azure Resource Manager + * API. + */ + listApplications( + options: ListApplicationsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listApplications(this._client, options); } } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts index da83f7f950..2395bdc817 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/index.ts @@ -204,81 +204,81 @@ export { } from "./models/index.js"; export { BatchClientOptionalParams, - ListApplicationsOptionalParams, - GetApplicationOptionalParams, - ListPoolUsageMetricsOptionalParams, - CreatePoolOptionalParams, - ListPoolsOptionalParams, - DeletePoolOptionalParams, - PoolExistsOptionalParams, - GetPoolOptionalParams, - UpdatePoolOptionalParams, - DisablePoolAutoScaleOptionalParams, - EnablePoolAutoScaleOptionalParams, - EvaluatePoolAutoScaleOptionalParams, - ResizePoolOptionalParams, - StopPoolResizeOptionalParams, - ReplacePoolPropertiesOptionalParams, - RemoveNodesOptionalParams, - ListSupportedImagesOptionalParams, - ListPoolNodeCountsOptionalParams, - DeleteJobOptionalParams, - GetJobOptionalParams, - UpdateJobOptionalParams, - ReplaceJobOptionalParams, - DisableJobOptionalParams, - EnableJobOptionalParams, - TerminateJobOptionalParams, - CreateJobOptionalParams, - ListJobsOptionalParams, - ListJobsFromScheduleOptionalParams, - ListJobPreparationAndReleaseTaskStatusOptionalParams, - GetJobTaskCountsOptionalParams, - CreateCertificateOptionalParams, - ListCertificatesOptionalParams, - CancelCertificateDeletionOptionalParams, - DeleteCertificateOptionalParams, - GetCertificateOptionalParams, - JobScheduleExistsOptionalParams, - DeleteJobScheduleOptionalParams, - GetJobScheduleOptionalParams, - UpdateJobScheduleOptionalParams, - ReplaceJobScheduleOptionalParams, - DisableJobScheduleOptionalParams, - EnableJobScheduleOptionalParams, - TerminateJobScheduleOptionalParams, - CreateJobScheduleOptionalParams, - ListJobSchedulesOptionalParams, - CreateTaskOptionalParams, - ListTasksOptionalParams, - CreateTaskCollectionOptionalParams, - DeleteTaskOptionalParams, - GetTaskOptionalParams, - ReplaceTaskOptionalParams, - ListSubTasksOptionalParams, - TerminateTaskOptionalParams, - ReactivateTaskOptionalParams, - DeleteTaskFileOptionalParams, - GetTaskFileOptionalParams, - GetTaskFilePropertiesOptionalParams, - ListTaskFilesOptionalParams, - CreateNodeUserOptionalParams, - DeleteNodeUserOptionalParams, - ReplaceNodeUserOptionalParams, - GetNodeOptionalParams, - RebootNodeOptionalParams, - ReimageNodeOptionalParams, - DisableNodeSchedulingOptionalParams, - EnableNodeSchedulingOptionalParams, - GetNodeRemoteLoginSettingsOptionalParams, - GetNodeRemoteDesktopFileOptionalParams, - UploadNodeLogsOptionalParams, - ListNodesOptionalParams, - GetNodeExtensionOptionalParams, - ListNodeExtensionsOptionalParams, - DeleteNodeFileOptionalParams, - GetNodeFileOptionalParams, - GetNodeFilePropertiesOptionalParams, ListNodeFilesOptionalParams, + GetNodeFilePropertiesOptionalParams, + GetNodeFileOptionalParams, + DeleteNodeFileOptionalParams, + ListNodeExtensionsOptionalParams, + GetNodeExtensionOptionalParams, + ListNodesOptionalParams, + UploadNodeLogsOptionalParams, + GetNodeRemoteDesktopFileOptionalParams, + GetNodeRemoteLoginSettingsOptionalParams, + EnableNodeSchedulingOptionalParams, + DisableNodeSchedulingOptionalParams, + ReimageNodeOptionalParams, + RebootNodeOptionalParams, + GetNodeOptionalParams, + ReplaceNodeUserOptionalParams, + DeleteNodeUserOptionalParams, + CreateNodeUserOptionalParams, + ListTaskFilesOptionalParams, + GetTaskFilePropertiesOptionalParams, + GetTaskFileOptionalParams, + DeleteTaskFileOptionalParams, + ReactivateTaskOptionalParams, + TerminateTaskOptionalParams, + ListSubTasksOptionalParams, + ReplaceTaskOptionalParams, + GetTaskOptionalParams, + DeleteTaskOptionalParams, + CreateTaskCollectionOptionalParams, + ListTasksOptionalParams, + CreateTaskOptionalParams, + ListJobSchedulesOptionalParams, + CreateJobScheduleOptionalParams, + TerminateJobScheduleOptionalParams, + EnableJobScheduleOptionalParams, + DisableJobScheduleOptionalParams, + ReplaceJobScheduleOptionalParams, + UpdateJobScheduleOptionalParams, + GetJobScheduleOptionalParams, + DeleteJobScheduleOptionalParams, + JobScheduleExistsOptionalParams, + GetCertificateOptionalParams, + DeleteCertificateOptionalParams, + CancelCertificateDeletionOptionalParams, + ListCertificatesOptionalParams, + CreateCertificateOptionalParams, + GetJobTaskCountsOptionalParams, + ListJobPreparationAndReleaseTaskStatusOptionalParams, + ListJobsFromScheduleOptionalParams, + ListJobsOptionalParams, + CreateJobOptionalParams, + TerminateJobOptionalParams, + EnableJobOptionalParams, + DisableJobOptionalParams, + ReplaceJobOptionalParams, + UpdateJobOptionalParams, + GetJobOptionalParams, + DeleteJobOptionalParams, + ListPoolNodeCountsOptionalParams, + ListSupportedImagesOptionalParams, + RemoveNodesOptionalParams, + ReplacePoolPropertiesOptionalParams, + StopPoolResizeOptionalParams, + ResizePoolOptionalParams, + EvaluatePoolAutoScaleOptionalParams, + EnablePoolAutoScaleOptionalParams, + DisablePoolAutoScaleOptionalParams, + UpdatePoolOptionalParams, + GetPoolOptionalParams, + PoolExistsOptionalParams, + DeletePoolOptionalParams, + ListPoolsOptionalParams, + CreatePoolOptionalParams, + ListPoolUsageMetricsOptionalParams, + GetApplicationOptionalParams, + ListApplicationsOptionalParams, } from "./api/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts index fb399e7977..c1035ebe9e 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/models.ts @@ -23,7 +23,9 @@ export function batchNodeUserCreateOptionsSerializer( return { name: item["name"], isAdmin: item["isAdmin"], - expiryTime: item["expiryTime"]?.toISOString(), + expiryTime: !item["expiryTime"] + ? item["expiryTime"] + : item["expiryTime"].toISOString(), password: item["password"], sshPublicKey: item["sshPublicKey"], }; @@ -104,7 +106,9 @@ export function batchNodeUserUpdateOptionsSerializer( ): any { return { password: item["password"], - expiryTime: item["expiryTime"]?.toISOString(), + expiryTime: !item["expiryTime"] + ? item["expiryTime"] + : item["expiryTime"].toISOString(), sshPublicKey: item["sshPublicKey"], }; } @@ -1080,7 +1084,7 @@ export function uploadBatchServiceLogsOptionsSerializer( return { containerUrl: item["containerUrl"], startTime: item["startTime"].toISOString(), - endTime: item["endTime"]?.toISOString(), + endTime: !item["endTime"] ? item["endTime"] : item["endTime"].toISOString(), identityReference: !item["identityReference"] ? item["identityReference"] : batchNodeIdentityReferenceSerializer(item["identityReference"]), @@ -2549,8 +2553,12 @@ export interface Schedule { export function scheduleSerializer(item: Schedule): any { return { - doNotRunUntil: item["doNotRunUntil"]?.toISOString(), - doNotRunAfter: item["doNotRunAfter"]?.toISOString(), + doNotRunUntil: !item["doNotRunUntil"] + ? item["doNotRunUntil"] + : item["doNotRunUntil"].toISOString(), + doNotRunAfter: !item["doNotRunAfter"] + ? item["doNotRunAfter"] + : item["doNotRunAfter"].toISOString(), startWindow: item["startWindow"], recurrenceInterval: item["recurrenceInterval"], }; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts index e78832bd25..6338acedbb 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/chatProtocolContext.ts @@ -17,7 +17,8 @@ export function createChatProtocol( credential: KeyCredential | TokenCredential, options: ChatProtocolClientOptionalParams = {}, ): ChatProtocolContext { - const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-ai-chat-protocol/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts index 22560e6770..10e197885f 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/index.ts @@ -6,8 +6,8 @@ export { ChatProtocolContext, ChatProtocolClientOptionalParams, } from "./chatProtocolContext.js"; -export { createStreaming, create } from "./operations.js"; +export { create, createStreaming } from "./operations.js"; export { - CreateStreamingOptionalParams, CreateOptionalParams, + CreateStreamingOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts index c5dbadb244..73b52d498c 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/operations.ts @@ -23,70 +23,80 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createStreamingSend( +export function _createSend( context: Client, - body: StreamingChatCompletionOptionsRecord, - options: CreateStreamingOptionalParams = { requestOptions: {} }, + body: ChatCompletionOptionsRecord, + options: CreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/chat") .post({ ...operationOptionsToRequestParameters(options), - body: streamingChatCompletionOptionsRecordSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: chatCompletionOptionsRecordSerializer(body), }); } -export async function _createStreamingDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return chatCompletionChunkRecordDeserializer(result.body); + return chatCompletionRecordDeserializer(result.body); } -/** Creates a new streaming chat completion. */ -export async function createStreaming( +/** Creates a new chat completion. */ +export async function create( context: Client, - body: StreamingChatCompletionOptionsRecord, - options: CreateStreamingOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createStreamingSend(context, body, options); - return _createStreamingDeserialize(result); + body: ChatCompletionOptionsRecord, + options: CreateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createSend(context, body, options); + return _createDeserialize(result); } -export function _createSend( +export function _createStreamingSend( context: Client, - body: ChatCompletionOptionsRecord, - options: CreateOptionalParams = { requestOptions: {} }, + body: StreamingChatCompletionOptionsRecord, + options: CreateStreamingOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/chat") .post({ ...operationOptionsToRequestParameters(options), - body: chatCompletionOptionsRecordSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: streamingChatCompletionOptionsRecordSerializer(body), }); } -export async function _createDeserialize( +export async function _createStreamingDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return chatCompletionRecordDeserializer(result.body); + return chatCompletionChunkRecordDeserializer(result.body); } -/** Creates a new chat completion. */ -export async function create( +/** Creates a new streaming chat completion. */ +export async function createStreaming( context: Client, - body: ChatCompletionOptionsRecord, - options: CreateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createSend(context, body, options); - return _createDeserialize(result); + body: StreamingChatCompletionOptionsRecord, + options: CreateStreamingOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createStreamingSend(context, body, options); + return _createStreamingDeserialize(result); } diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/options.ts index 05af57f5c0..a18cbb9bc2 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/api/options.ts @@ -4,7 +4,7 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface CreateStreamingOptionalParams extends OperationOptions {} +export interface CreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface CreateOptionalParams extends OperationOptions {} +export interface CreateStreamingOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts index 2e2d174669..80ac51737a 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/chatProtocolClient.ts @@ -5,10 +5,10 @@ import { createChatProtocol, ChatProtocolContext, ChatProtocolClientOptionalParams, - createStreaming, create, - CreateStreamingOptionalParams, + createStreaming, CreateOptionalParams, + CreateStreamingOptionalParams, } from "./api/index.js"; import { StreamingChatCompletionOptionsRecord, @@ -43,14 +43,6 @@ export class ChatProtocolClient { this.pipeline = this._client.pipeline; } - /** Creates a new streaming chat completion. */ - createStreaming( - body: StreamingChatCompletionOptionsRecord, - options: CreateStreamingOptionalParams = { requestOptions: {} }, - ): Promise { - return createStreaming(this._client, body, options); - } - /** Creates a new chat completion. */ create( body: ChatCompletionOptionsRecord, @@ -58,4 +50,12 @@ export class ChatProtocolClient { ): Promise { return create(this._client, body, options); } + + /** Creates a new streaming chat completion. */ + createStreaming( + body: StreamingChatCompletionOptionsRecord, + options: CreateStreamingOptionalParams = { requestOptions: {} }, + ): Promise { + return createStreaming(this._client, body, options); + } } diff --git a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts index e55dfe4e8d..e0afac0868 100644 --- a/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/chatApi_modular/generated/typespec-ts/src/index.ts @@ -17,6 +17,6 @@ export { } from "./models/index.js"; export { ChatProtocolClientOptionalParams, - CreateStreamingOptionalParams, CreateOptionalParams, + CreateStreamingOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md index 7bdc977575..07e1e23dc7 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/review/ai-content-safety.api.md @@ -93,7 +93,6 @@ export type ContinuablePage = TPage & { // @public export interface CreateOrUpdateTextBlocklistOptionalParams extends OperationOptions { - contentType?: string; } // @public diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts index 3c7372177c..09cecf3b5d 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/contentSafetyContext.ts @@ -7,7 +7,11 @@ import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { KeyCredential, TokenCredential } from "@azure/core-auth"; /** Analyze harmful content */ -export interface ContentSafetyContext extends Client {} +export interface ContentSafetyContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface ContentSafetyClientOptionalParams extends ClientOptions { @@ -59,5 +63,5 @@ export function createContentSafety( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as ContentSafetyContext; } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts index cfe55ac498..f1e125761b 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/index.ts @@ -7,26 +7,26 @@ export { ContentSafetyClientOptionalParams, } from "./contentSafetyContext.js"; export { - analyzeText, - analyzeImage, - getTextBlocklist, - createOrUpdateTextBlocklist, - deleteTextBlocklist, - listTextBlocklists, - addOrUpdateBlockItems, - removeBlockItems, - getTextBlocklistItem, listTextBlocklistItems, + getTextBlocklistItem, + removeBlockItems, + addOrUpdateBlockItems, + listTextBlocklists, + deleteTextBlocklist, + createOrUpdateTextBlocklist, + getTextBlocklist, + analyzeImage, + analyzeText, } from "./operations.js"; export { - AnalyzeTextOptionalParams, - AnalyzeImageOptionalParams, - GetTextBlocklistOptionalParams, - CreateOrUpdateTextBlocklistOptionalParams, - DeleteTextBlocklistOptionalParams, - ListTextBlocklistsOptionalParams, - AddOrUpdateBlockItemsOptionalParams, - RemoveBlockItemsOptionalParams, - GetTextBlocklistItemOptionalParams, ListTextBlocklistItemsOptionalParams, + GetTextBlocklistItemOptionalParams, + RemoveBlockItemsOptionalParams, + AddOrUpdateBlockItemsOptionalParams, + ListTextBlocklistsOptionalParams, + DeleteTextBlocklistOptionalParams, + CreateOrUpdateTextBlocklistOptionalParams, + GetTextBlocklistOptionalParams, + AnalyzeImageOptionalParams, + AnalyzeTextOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts index 9620a7e5c4..25b6e6d764 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/operations.ts @@ -50,181 +50,198 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _analyzeTextSend( +export function _listTextBlocklistItemsSend( context: Client, - body: AnalyzeTextOptions, - options: AnalyzeTextOptionalParams = { requestOptions: {} }, + blocklistName: string, + options: ListTextBlocklistItemsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/text:analyze") - .post({ + .path("/text/blocklists/{blocklistName}/blockItems", blocklistName) + .get({ ...operationOptionsToRequestParameters(options), - body: analyzeTextOptionsSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + top: options?.top, + skip: options?.skip, + maxpagesize: options?.maxpagesize, + }, }); } -export async function _analyzeTextDeserialize( +export async function _listTextBlocklistItemsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_PagedTextBlockItem> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return analyzeTextResultDeserializer(result.body); + return _pagedTextBlockItemDeserializer(result.body); } -/** A sync API for harmful content analysis for text. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ -export async function analyzeText( +/** Get all blockItems in a text blocklist */ +export function listTextBlocklistItems( context: Client, - body: AnalyzeTextOptions, - options: AnalyzeTextOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _analyzeTextSend(context, body, options); - return _analyzeTextDeserialize(result); + blocklistName: string, + options: ListTextBlocklistItemsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTextBlocklistItemsSend(context, blocklistName, options), + _listTextBlocklistItemsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); } -export function _analyzeImageSend( +export function _getTextBlocklistItemSend( context: Client, - body: AnalyzeImageOptions, - options: AnalyzeImageOptionalParams = { requestOptions: {} }, + blocklistName: string, + blockItemId: string, + options: GetTextBlocklistItemOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/image:analyze") - .post({ + .path( + "/text/blocklists/{blocklistName}/blockItems/{blockItemId}", + blocklistName, + blockItemId, + ) + .get({ ...operationOptionsToRequestParameters(options), - body: analyzeImageOptionsSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _analyzeImageDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return analyzeImageResultDeserializer(result.body); -} - -/** A sync API for harmful content analysis for image. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ -export async function analyzeImage( - context: Client, - body: AnalyzeImageOptions, - options: AnalyzeImageOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _analyzeImageSend(context, body, options); - return _analyzeImageDeserialize(result); -} - -export function _getTextBlocklistSend( - context: Client, - blocklistName: string, - options: GetTextBlocklistOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/text/blocklists/{blocklistName}", blocklistName) - .get({ ...operationOptionsToRequestParameters(options) }); -} - -export async function _getTextBlocklistDeserialize( +export async function _getTextBlocklistItemDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return textBlocklistDeserializer(result.body); + return textBlockItemDeserializer(result.body); } -/** Returns text blocklist details. */ -export async function getTextBlocklist( +/** Get blockItem By blockItemId from a text blocklist. */ +export async function getTextBlocklistItem( context: Client, blocklistName: string, - options: GetTextBlocklistOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTextBlocklistSend(context, blocklistName, options); - return _getTextBlocklistDeserialize(result); + blockItemId: string, + options: GetTextBlocklistItemOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTextBlocklistItemSend( + context, + blocklistName, + blockItemId, + options, + ); + return _getTextBlocklistItemDeserialize(result); } -export function _createOrUpdateTextBlocklistSend( +export function _removeBlockItemsSend( context: Client, blocklistName: string, - resource: TextBlocklist, - options: CreateOrUpdateTextBlocklistOptionalParams = { requestOptions: {} }, + body: RemoveBlockItemsOptions, + options: RemoveBlockItemsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/text/blocklists/{blocklistName}", blocklistName) - .patch({ + .path("/text/blocklists/{blocklistName}:removeBlockItems", blocklistName) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: textBlocklistSerializer(resource), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: removeBlockItemsOptionsSerializer(body), }); } -export async function _createOrUpdateTextBlocklistDeserialize( +export async function _removeBlockItemsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "201"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return textBlocklistDeserializer(result.body); + return; } -/** Updates a text blocklist, if blocklistName does not exist, create a new blocklist. */ -export async function createOrUpdateTextBlocklist( +/** Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. */ +export async function removeBlockItems( context: Client, blocklistName: string, - resource: TextBlocklist, - options: CreateOrUpdateTextBlocklistOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createOrUpdateTextBlocklistSend( + body: RemoveBlockItemsOptions, + options: RemoveBlockItemsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _removeBlockItemsSend( context, blocklistName, - resource, + body, options, ); - return _createOrUpdateTextBlocklistDeserialize(result); + return _removeBlockItemsDeserialize(result); } -export function _deleteTextBlocklistSend( +export function _addOrUpdateBlockItemsSend( context: Client, blocklistName: string, - options: DeleteTextBlocklistOptionalParams = { requestOptions: {} }, + body: AddOrUpdateBlockItemsOptions, + options: AddOrUpdateBlockItemsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/text/blocklists/{blocklistName}", blocklistName) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path( + "/text/blocklists/{blocklistName}:addOrUpdateBlockItems", + blocklistName, + ) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: addOrUpdateBlockItemsOptionsSerializer(body), + }); } -export async function _deleteTextBlocklistDeserialize( +export async function _addOrUpdateBlockItemsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return addOrUpdateBlockItemsResultDeserializer(result.body); } -/** Deletes a text blocklist. */ -export async function deleteTextBlocklist( +/** Add or update blockItems to a text blocklist. You can add or update at most 100 BlockItems in one request. */ +export async function addOrUpdateBlockItems( context: Client, blocklistName: string, - options: DeleteTextBlocklistOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteTextBlocklistSend( + body: AddOrUpdateBlockItemsOptions, + options: AddOrUpdateBlockItemsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _addOrUpdateBlockItemsSend( context, blocklistName, + body, options, ); - return _deleteTextBlocklistDeserialize(result); + return _addOrUpdateBlockItemsDeserialize(result); } export function _listTextBlocklistsSend( @@ -233,7 +250,14 @@ export function _listTextBlocklistsSend( ): StreamableMethod { return context .path("/text/blocklists") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _listTextBlocklistsDeserialize( @@ -261,172 +285,209 @@ export function listTextBlocklists( ); } -export function _addOrUpdateBlockItemsSend( +export function _deleteTextBlocklistSend( context: Client, blocklistName: string, - body: AddOrUpdateBlockItemsOptions, - options: AddOrUpdateBlockItemsOptionalParams = { requestOptions: {} }, + options: DeleteTextBlocklistOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/text/blocklists/{blocklistName}:addOrUpdateBlockItems", - blocklistName, - ) - .post({ + .path("/text/blocklists/{blocklistName}", blocklistName) + .delete({ ...operationOptionsToRequestParameters(options), - body: addOrUpdateBlockItemsOptionsSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _addOrUpdateBlockItemsDeserialize( +export async function _deleteTextBlocklistDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return addOrUpdateBlockItemsResultDeserializer(result.body); + return; } -/** Add or update blockItems to a text blocklist. You can add or update at most 100 BlockItems in one request. */ -export async function addOrUpdateBlockItems( +/** Deletes a text blocklist. */ +export async function deleteTextBlocklist( context: Client, blocklistName: string, - body: AddOrUpdateBlockItemsOptions, - options: AddOrUpdateBlockItemsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _addOrUpdateBlockItemsSend( + options: DeleteTextBlocklistOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTextBlocklistSend( context, blocklistName, - body, options, ); - return _addOrUpdateBlockItemsDeserialize(result); + return _deleteTextBlocklistDeserialize(result); } -export function _removeBlockItemsSend( +export function _createOrUpdateTextBlocklistSend( context: Client, blocklistName: string, - body: RemoveBlockItemsOptions, - options: RemoveBlockItemsOptionalParams = { requestOptions: {} }, + resource: TextBlocklist, + options: CreateOrUpdateTextBlocklistOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/text/blocklists/{blocklistName}:removeBlockItems", blocklistName) - .post({ + .path("/text/blocklists/{blocklistName}", blocklistName) + .patch({ ...operationOptionsToRequestParameters(options), - body: removeBlockItemsOptionsSerializer(body), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: textBlocklistSerializer(resource), }); } -export async function _removeBlockItemsDeserialize( +export async function _createOrUpdateTextBlocklistDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return textBlocklistDeserializer(result.body); } -/** Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. */ -export async function removeBlockItems( +/** Updates a text blocklist, if blocklistName does not exist, create a new blocklist. */ +export async function createOrUpdateTextBlocklist( context: Client, blocklistName: string, - body: RemoveBlockItemsOptions, - options: RemoveBlockItemsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _removeBlockItemsSend( + resource: TextBlocklist, + options: CreateOrUpdateTextBlocklistOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTextBlocklistSend( context, blocklistName, - body, + resource, options, ); - return _removeBlockItemsDeserialize(result); + return _createOrUpdateTextBlocklistDeserialize(result); } -export function _getTextBlocklistItemSend( +export function _getTextBlocklistSend( context: Client, blocklistName: string, - blockItemId: string, - options: GetTextBlocklistItemOptionalParams = { requestOptions: {} }, + options: GetTextBlocklistOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/text/blocklists/{blocklistName}/blockItems/{blockItemId}", - blocklistName, - blockItemId, - ) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/text/blocklists/{blocklistName}", blocklistName) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getTextBlocklistItemDeserialize( +export async function _getTextBlocklistDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return textBlockItemDeserializer(result.body); + return textBlocklistDeserializer(result.body); } -/** Get blockItem By blockItemId from a text blocklist. */ -export async function getTextBlocklistItem( +/** Returns text blocklist details. */ +export async function getTextBlocklist( context: Client, blocklistName: string, - blockItemId: string, - options: GetTextBlocklistItemOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTextBlocklistItemSend( - context, - blocklistName, - blockItemId, - options, - ); - return _getTextBlocklistItemDeserialize(result); + options: GetTextBlocklistOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTextBlocklistSend(context, blocklistName, options); + return _getTextBlocklistDeserialize(result); } -export function _listTextBlocklistItemsSend( +export function _analyzeImageSend( context: Client, - blocklistName: string, - options: ListTextBlocklistItemsOptionalParams = { requestOptions: {} }, + body: AnalyzeImageOptions, + options: AnalyzeImageOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/text/blocklists/{blocklistName}/blockItems", blocklistName) - .get({ + .path("/image:analyze") + .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - top: options?.top, - skip: options?.skip, - maxpagesize: options?.maxpagesize, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, + body: analyzeImageOptionsSerializer(body), }); } -export async function _listTextBlocklistItemsDeserialize( +export async function _analyzeImageDeserialize( result: PathUncheckedResponse, -): Promise<_PagedTextBlockItem> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedTextBlockItemDeserializer(result.body); + return analyzeImageResultDeserializer(result.body); } -/** Get all blockItems in a text blocklist */ -export function listTextBlocklistItems( +/** A sync API for harmful content analysis for image. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ +export async function analyzeImage( context: Client, - blocklistName: string, - options: ListTextBlocklistItemsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listTextBlocklistItemsSend(context, blocklistName, options), - _listTextBlocklistItemsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); + body: AnalyzeImageOptions, + options: AnalyzeImageOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _analyzeImageSend(context, body, options); + return _analyzeImageDeserialize(result); +} + +export function _analyzeTextSend( + context: Client, + body: AnalyzeTextOptions, + options: AnalyzeTextOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/text:analyze") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: analyzeTextOptionsSerializer(body), + }); +} + +export async function _analyzeTextDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return analyzeTextResultDeserializer(result.body); +} + +/** A sync API for harmful content analysis for text. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ +export async function analyzeText( + context: Client, + body: AnalyzeTextOptions, + options: AnalyzeTextOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _analyzeTextSend(context, body, options); + return _analyzeTextDeserialize(result); } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/options.ts index 0e939a2597..44fc6c8c48 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/options.ts @@ -4,42 +4,39 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface AnalyzeTextOptionalParams extends OperationOptions {} +export interface ListTextBlocklistItemsOptionalParams extends OperationOptions { + /** The number of result items to return. */ + top?: number; + /** The number of result items to skip. */ + skip?: number; + /** The maximum number of result items per page. */ + maxpagesize?: number; +} /** Optional parameters. */ -export interface AnalyzeImageOptionalParams extends OperationOptions {} +export interface GetTextBlocklistItemOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetTextBlocklistOptionalParams extends OperationOptions {} +export interface RemoveBlockItemsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface CreateOrUpdateTextBlocklistOptionalParams - extends OperationOptions { - /** This request has a JSON Merge Patch body. */ - contentType?: string; -} +export interface AddOrUpdateBlockItemsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DeleteTextBlocklistOptionalParams extends OperationOptions {} +export interface ListTextBlocklistsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ListTextBlocklistsOptionalParams extends OperationOptions {} +export interface DeleteTextBlocklistOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AddOrUpdateBlockItemsOptionalParams extends OperationOptions {} +export interface CreateOrUpdateTextBlocklistOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface RemoveBlockItemsOptionalParams extends OperationOptions {} +export interface GetTextBlocklistOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetTextBlocklistItemOptionalParams extends OperationOptions {} +export interface AnalyzeImageOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ListTextBlocklistItemsOptionalParams extends OperationOptions { - /** The number of result items to return. */ - top?: number; - /** The number of result items to skip. */ - skip?: number; - /** The maximum number of result items per page. */ - maxpagesize?: number; -} +export interface AnalyzeTextOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts index ad87ba7dec..a98e2357f9 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/contentSafetyClient.ts @@ -5,26 +5,26 @@ import { createContentSafety, ContentSafetyContext, ContentSafetyClientOptionalParams, - analyzeText, - analyzeImage, - getTextBlocklist, - createOrUpdateTextBlocklist, - deleteTextBlocklist, - listTextBlocklists, - addOrUpdateBlockItems, - removeBlockItems, - getTextBlocklistItem, listTextBlocklistItems, - AnalyzeTextOptionalParams, - AnalyzeImageOptionalParams, - GetTextBlocklistOptionalParams, - CreateOrUpdateTextBlocklistOptionalParams, - DeleteTextBlocklistOptionalParams, - ListTextBlocklistsOptionalParams, - AddOrUpdateBlockItemsOptionalParams, - RemoveBlockItemsOptionalParams, - GetTextBlocklistItemOptionalParams, + getTextBlocklistItem, + removeBlockItems, + addOrUpdateBlockItems, + listTextBlocklists, + deleteTextBlocklist, + createOrUpdateTextBlocklist, + getTextBlocklist, + analyzeImage, + analyzeText, ListTextBlocklistItemsOptionalParams, + GetTextBlocklistItemOptionalParams, + RemoveBlockItemsOptionalParams, + AddOrUpdateBlockItemsOptionalParams, + ListTextBlocklistsOptionalParams, + DeleteTextBlocklistOptionalParams, + CreateOrUpdateTextBlocklistOptionalParams, + GetTextBlocklistOptionalParams, + AnalyzeImageOptionalParams, + AnalyzeTextOptionalParams, } from "./api/index.js"; import { TextBlocklist, @@ -65,57 +65,35 @@ export class ContentSafetyClient { this.pipeline = this._client.pipeline; } - /** A sync API for harmful content analysis for text. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ - analyzeText( - body: AnalyzeTextOptions, - options: AnalyzeTextOptionalParams = { requestOptions: {} }, - ): Promise { - return analyzeText(this._client, body, options); - } - - /** A sync API for harmful content analysis for image. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ - analyzeImage( - body: AnalyzeImageOptions, - options: AnalyzeImageOptionalParams = { requestOptions: {} }, - ): Promise { - return analyzeImage(this._client, body, options); - } - - /** Returns text blocklist details. */ - getTextBlocklist( + /** Get all blockItems in a text blocklist */ + listTextBlocklistItems( blocklistName: string, - options: GetTextBlocklistOptionalParams = { requestOptions: {} }, - ): Promise { - return getTextBlocklist(this._client, blocklistName, options); + options: ListTextBlocklistItemsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTextBlocklistItems(this._client, blocklistName, options); } - /** Updates a text blocklist, if blocklistName does not exist, create a new blocklist. */ - createOrUpdateTextBlocklist( + /** Get blockItem By blockItemId from a text blocklist. */ + getTextBlocklistItem( blocklistName: string, - resource: TextBlocklist, - options: CreateOrUpdateTextBlocklistOptionalParams = { requestOptions: {} }, - ): Promise { - return createOrUpdateTextBlocklist( + blockItemId: string, + options: GetTextBlocklistItemOptionalParams = { requestOptions: {} }, + ): Promise { + return getTextBlocklistItem( this._client, blocklistName, - resource, + blockItemId, options, ); } - /** Deletes a text blocklist. */ - deleteTextBlocklist( + /** Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. */ + removeBlockItems( blocklistName: string, - options: DeleteTextBlocklistOptionalParams = { requestOptions: {} }, + body: RemoveBlockItemsOptions, + options: RemoveBlockItemsOptionalParams = { requestOptions: {} }, ): Promise { - return deleteTextBlocklist(this._client, blocklistName, options); - } - - /** Get all text blocklists details. */ - listTextBlocklists( - options: ListTextBlocklistsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTextBlocklists(this._client, options); + return removeBlockItems(this._client, blocklistName, body, options); } /** Add or update blockItems to a text blocklist. You can add or update at most 100 BlockItems in one request. */ @@ -127,34 +105,56 @@ export class ContentSafetyClient { return addOrUpdateBlockItems(this._client, blocklistName, body, options); } - /** Remove blockItems from a text blocklist. You can remove at most 100 BlockItems in one request. */ - removeBlockItems( + /** Get all text blocklists details. */ + listTextBlocklists( + options: ListTextBlocklistsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTextBlocklists(this._client, options); + } + + /** Deletes a text blocklist. */ + deleteTextBlocklist( blocklistName: string, - body: RemoveBlockItemsOptions, - options: RemoveBlockItemsOptionalParams = { requestOptions: {} }, + options: DeleteTextBlocklistOptionalParams = { requestOptions: {} }, ): Promise { - return removeBlockItems(this._client, blocklistName, body, options); + return deleteTextBlocklist(this._client, blocklistName, options); } - /** Get blockItem By blockItemId from a text blocklist. */ - getTextBlocklistItem( + /** Updates a text blocklist, if blocklistName does not exist, create a new blocklist. */ + createOrUpdateTextBlocklist( blocklistName: string, - blockItemId: string, - options: GetTextBlocklistItemOptionalParams = { requestOptions: {} }, - ): Promise { - return getTextBlocklistItem( + resource: TextBlocklist, + options: CreateOrUpdateTextBlocklistOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateTextBlocklist( this._client, blocklistName, - blockItemId, + resource, options, ); } - /** Get all blockItems in a text blocklist */ - listTextBlocklistItems( + /** Returns text blocklist details. */ + getTextBlocklist( blocklistName: string, - options: ListTextBlocklistItemsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTextBlocklistItems(this._client, blocklistName, options); + options: GetTextBlocklistOptionalParams = { requestOptions: {} }, + ): Promise { + return getTextBlocklist(this._client, blocklistName, options); + } + + /** A sync API for harmful content analysis for image. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ + analyzeImage( + body: AnalyzeImageOptions, + options: AnalyzeImageOptionalParams = { requestOptions: {} }, + ): Promise { + return analyzeImage(this._client, body, options); + } + + /** A sync API for harmful content analysis for text. Currently, we support four categories: Hate, SelfHarm, Sexual, Violence. */ + analyzeText( + body: AnalyzeTextOptions, + options: AnalyzeTextOptionalParams = { requestOptions: {} }, + ): Promise { + return analyzeText(this._client, body, options); } } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts index 547f3619df..147bfb0e2e 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/index.ts @@ -31,15 +31,15 @@ export { } from "./models/index.js"; export { ContentSafetyClientOptionalParams, - AnalyzeTextOptionalParams, - AnalyzeImageOptionalParams, - GetTextBlocklistOptionalParams, - CreateOrUpdateTextBlocklistOptionalParams, - DeleteTextBlocklistOptionalParams, - ListTextBlocklistsOptionalParams, - AddOrUpdateBlockItemsOptionalParams, - RemoveBlockItemsOptionalParams, - GetTextBlocklistItemOptionalParams, ListTextBlocklistItemsOptionalParams, + GetTextBlocklistItemOptionalParams, + RemoveBlockItemsOptionalParams, + AddOrUpdateBlockItemsOptionalParams, + ListTextBlocklistsOptionalParams, + DeleteTextBlocklistOptionalParams, + CreateOrUpdateTextBlocklistOptionalParams, + GetTextBlocklistOptionalParams, + AnalyzeImageOptionalParams, + AnalyzeTextOptionalParams, } from "./api/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md index b818f6af46..4165dc18d3 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/review/eventgrid.api.md @@ -11,7 +11,6 @@ import { Pipeline } from '@azure/core-rest-pipeline'; // @public export interface AcknowledgeCloudEventsOptionalParams extends OperationOptions { - contentType?: string; } // @public @@ -79,12 +78,10 @@ export enum KnownServiceApiVersions { // @public export interface PublishCloudEventOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface PublishCloudEventsOptionalParams extends OperationOptions { - contentType?: string; } // @public @@ -110,7 +107,6 @@ export interface ReceiveResult { // @public export interface RejectCloudEventsOptionalParams extends OperationOptions { - contentType?: string; } // @public @@ -126,7 +122,6 @@ export interface RejectResult { // @public export interface ReleaseCloudEventsOptionalParams extends OperationOptions { - contentType?: string; } // @public diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts index 6389fc8731..305de28694 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/eventGridContext.ts @@ -7,7 +7,11 @@ import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { KeyCredential } from "@azure/core-auth"; /** Azure Messaging EventGrid Client */ -export interface EventGridContext extends Client {} +export interface EventGridContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownServiceApiVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface EventGridClientOptionalParams extends ClientOptions { @@ -22,7 +26,8 @@ export function createEventGrid( credential: KeyCredential, options: EventGridClientOptionalParams = {}, ): EventGridContext { - const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}`; + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-eventgrid/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -55,5 +60,5 @@ export function createEventGrid( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as EventGridContext; } diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts index 8a029ed362..fd2135207b 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/index.ts @@ -7,18 +7,18 @@ export { EventGridClientOptionalParams, } from "./eventGridContext.js"; export { - publishCloudEvent, - publishCloudEvents, - receiveCloudEvents, - acknowledgeCloudEvents, - releaseCloudEvents, rejectCloudEvents, + releaseCloudEvents, + acknowledgeCloudEvents, + receiveCloudEvents, + publishCloudEvents, + publishCloudEvent, } from "./operations.js"; export { - PublishCloudEventOptionalParams, - PublishCloudEventsOptionalParams, - ReceiveCloudEventsOptionalParams, - AcknowledgeCloudEventsOptionalParams, - ReleaseCloudEventsOptionalParams, RejectCloudEventsOptionalParams, + ReleaseCloudEventsOptionalParams, + AcknowledgeCloudEventsOptionalParams, + ReceiveCloudEventsOptionalParams, + PublishCloudEventsOptionalParams, + PublishCloudEventOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts index a204297726..2be45096ef 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/operations.ts @@ -13,6 +13,7 @@ import { import { _publishCloudEventRequestSerializer, CloudEvent, + cloudEventSerializer, PublishResult, publishResultDeserializer, ReceiveResult, @@ -29,7 +30,6 @@ import { rejectOptionsSerializer, RejectResult, rejectResultDeserializer, - cloudEventArraySerializer, } from "../models/models.js"; import { StreamableMethod, @@ -38,144 +38,112 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _publishCloudEventSend( - context: Client, - topicName: string, - event: { - event: CloudEvent; - }, - options: PublishCloudEventOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/topics/{topicName}:publish", topicName) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/cloudevents+json; charset=utf-8", - body: _publishCloudEventRequestSerializer(event), - }); -} - -export async function _publishCloudEventDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return publishResultDeserializer(result.body); -} - -/** Publish Single Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ -export async function publishCloudEvent( - context: Client, - topicName: string, - event: { - event: CloudEvent; - }, - options: PublishCloudEventOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _publishCloudEventSend( - context, - topicName, - event, - options, - ); - return _publishCloudEventDeserialize(result); -} - -export function _publishCloudEventsSend( +export function _rejectCloudEventsSend( context: Client, topicName: string, - events: CloudEvent[], - options: PublishCloudEventsOptionalParams = { requestOptions: {} }, + eventSubscriptionName: string, + lockTokens: RejectOptions, + options: RejectCloudEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/topics/{topicName}:publish", topicName) + .path( + "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:reject", + topicName, + eventSubscriptionName, + ) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/cloudevents-batch+json; charset=utf-8", - body: cloudEventArraySerializer(events), + contentType: "application/json; charset=utf-8", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: rejectOptionsSerializer(lockTokens), }); } -export async function _publishCloudEventsDeserialize( +export async function _rejectCloudEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return publishResultDeserializer(result.body); + return rejectResultDeserializer(result.body); } -/** Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ -export async function publishCloudEvents( +/** Reject batch of Cloud Events. */ +export async function rejectCloudEvents( context: Client, topicName: string, - events: CloudEvent[], - options: PublishCloudEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _publishCloudEventsSend( + eventSubscriptionName: string, + lockTokens: RejectOptions, + options: RejectCloudEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _rejectCloudEventsSend( context, topicName, - events, + eventSubscriptionName, + lockTokens, options, ); - return _publishCloudEventsDeserialize(result); + return _rejectCloudEventsDeserialize(result); } -export function _receiveCloudEventsSend( +export function _releaseCloudEventsSend( context: Client, topicName: string, eventSubscriptionName: string, - options: ReceiveCloudEventsOptionalParams = { requestOptions: {} }, + lockTokens: ReleaseOptions, + options: ReleaseCloudEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:receive", + "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:release", topicName, eventSubscriptionName, ) .post({ ...operationOptionsToRequestParameters(options), - queryParameters: { - maxEvents: options?.maxEvents, - maxWaitTime: options?.maxWaitTime, + contentType: "application/json; charset=utf-8", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, + body: releaseOptionsSerializer(lockTokens), }); } -export async function _receiveCloudEventsDeserialize( +export async function _releaseCloudEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return receiveResultDeserializer(result.body); + return releaseResultDeserializer(result.body); } -/** Receive Batch of Cloud Events from the Event Subscription. */ -export async function receiveCloudEvents( +/** Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is successfully released. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. */ +export async function releaseCloudEvents( context: Client, topicName: string, eventSubscriptionName: string, - options: ReceiveCloudEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _receiveCloudEventsSend( + lockTokens: ReleaseOptions, + options: ReleaseCloudEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _releaseCloudEventsSend( context, topicName, eventSubscriptionName, + lockTokens, options, ); - return _receiveCloudEventsDeserialize(result); + return _releaseCloudEventsDeserialize(result); } export function _acknowledgeCloudEventsSend( @@ -193,8 +161,12 @@ export function _acknowledgeCloudEventsSend( ) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; charset=utf-8", + contentType: "application/json; charset=utf-8", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: acknowledgeOptionsSerializer(lockTokens), }); } @@ -228,102 +200,150 @@ export async function acknowledgeCloudEvents( return _acknowledgeCloudEventsDeserialize(result); } -export function _releaseCloudEventsSend( +export function _receiveCloudEventsSend( context: Client, topicName: string, eventSubscriptionName: string, - lockTokens: ReleaseOptions, - options: ReleaseCloudEventsOptionalParams = { requestOptions: {} }, + options: ReceiveCloudEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path( - "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:release", + "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:receive", topicName, eventSubscriptionName, ) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; charset=utf-8", - body: releaseOptionsSerializer(lockTokens), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + maxEvents: options?.maxEvents, + maxWaitTime: options?.maxWaitTime, + }, }); } -export async function _releaseCloudEventsDeserialize( +export async function _receiveCloudEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return releaseResultDeserializer(result.body); + return receiveResultDeserializer(result.body); } -/** Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is successfully released. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. */ -export async function releaseCloudEvents( +/** Receive Batch of Cloud Events from the Event Subscription. */ +export async function receiveCloudEvents( context: Client, topicName: string, eventSubscriptionName: string, - lockTokens: ReleaseOptions, - options: ReleaseCloudEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _releaseCloudEventsSend( + options: ReceiveCloudEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _receiveCloudEventsSend( context, topicName, eventSubscriptionName, - lockTokens, options, ); - return _releaseCloudEventsDeserialize(result); + return _receiveCloudEventsDeserialize(result); } -export function _rejectCloudEventsSend( +export function _publishCloudEventsSend( context: Client, topicName: string, - eventSubscriptionName: string, - lockTokens: RejectOptions, - options: RejectCloudEventsOptionalParams = { requestOptions: {} }, + events: CloudEvent[], + options: PublishCloudEventsOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context.path("/topics/{topicName}:publish", topicName).post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/cloudevents-batch+json; charset=utf-8", + headers: { accept: "application/json", ...options.requestOptions?.headers }, + queryParameters: { "api-version": context.apiVersion }, + body: events.map((p: any) => { + return cloudEventSerializer(p); + }), + }); +} + +export async function _publishCloudEventsDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return publishResultDeserializer(result.body); +} + +/** Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ +export async function publishCloudEvents( + context: Client, + topicName: string, + events: CloudEvent[], + options: PublishCloudEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _publishCloudEventsSend( + context, + topicName, + events, + options, + ); + return _publishCloudEventsDeserialize(result); +} + +export function _publishCloudEventSend( + context: Client, + topicName: string, + event: { + event: CloudEvent; + }, + options: PublishCloudEventOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:reject", - topicName, - eventSubscriptionName, - ) + .path("/topics/{topicName}:publish", topicName) .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; charset=utf-8", - body: rejectOptionsSerializer(lockTokens), + contentType: "application/cloudevents+json; charset=utf-8", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: _publishCloudEventRequestSerializer(event), }); } -export async function _rejectCloudEventsDeserialize( +export async function _publishCloudEventDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return rejectResultDeserializer(result.body); + return publishResultDeserializer(result.body); } -/** Reject batch of Cloud Events. */ -export async function rejectCloudEvents( +/** Publish Single Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ +export async function publishCloudEvent( context: Client, topicName: string, - eventSubscriptionName: string, - lockTokens: RejectOptions, - options: RejectCloudEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _rejectCloudEventsSend( + event: { + event: CloudEvent; + }, + options: PublishCloudEventOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _publishCloudEventSend( context, topicName, - eventSubscriptionName, - lockTokens, + event, options, ); - return _rejectCloudEventsDeserialize(result); + return _publishCloudEventDeserialize(result); } diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/options.ts index 289cd79ae7..1d731f3367 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/api/options.ts @@ -4,16 +4,14 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface PublishCloudEventOptionalParams extends OperationOptions { - /** content type */ - contentType?: string; -} +export interface RejectCloudEventsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface PublishCloudEventsOptionalParams extends OperationOptions { - /** content type */ - contentType?: string; -} +export interface ReleaseCloudEventsOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface AcknowledgeCloudEventsOptionalParams + extends OperationOptions {} /** Optional parameters. */ export interface ReceiveCloudEventsOptionalParams extends OperationOptions { @@ -24,19 +22,7 @@ export interface ReceiveCloudEventsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface AcknowledgeCloudEventsOptionalParams extends OperationOptions { - /** content type */ - contentType?: string; -} +export interface PublishCloudEventsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ReleaseCloudEventsOptionalParams extends OperationOptions { - /** content type */ - contentType?: string; -} - -/** Optional parameters. */ -export interface RejectCloudEventsOptionalParams extends OperationOptions { - /** content type */ - contentType?: string; -} +export interface PublishCloudEventOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts index 388daa6fa6..b50357700d 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/eventGridClient.ts @@ -5,18 +5,18 @@ import { createEventGrid, EventGridContext, EventGridClientOptionalParams, - publishCloudEvent, - publishCloudEvents, - receiveCloudEvents, - acknowledgeCloudEvents, - releaseCloudEvents, rejectCloudEvents, - PublishCloudEventOptionalParams, - PublishCloudEventsOptionalParams, - ReceiveCloudEventsOptionalParams, - AcknowledgeCloudEventsOptionalParams, - ReleaseCloudEventsOptionalParams, + releaseCloudEvents, + acknowledgeCloudEvents, + receiveCloudEvents, + publishCloudEvents, + publishCloudEvent, RejectCloudEventsOptionalParams, + ReleaseCloudEventsOptionalParams, + AcknowledgeCloudEventsOptionalParams, + ReceiveCloudEventsOptionalParams, + PublishCloudEventsOptionalParams, + PublishCloudEventOptionalParams, } from "./api/index.js"; import { CloudEvent, @@ -56,36 +56,34 @@ export class EventGridClient { this.pipeline = this._client.pipeline; } - /** Publish Single Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ - publishCloudEvent( - topicName: string, - event: { - event: CloudEvent; - }, - options: PublishCloudEventOptionalParams = { requestOptions: {} }, - ): Promise { - return publishCloudEvent(this._client, topicName, event, options); - } - - /** Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ - publishCloudEvents( + /** Reject batch of Cloud Events. */ + rejectCloudEvents( topicName: string, - events: CloudEvent[], - options: PublishCloudEventsOptionalParams = { requestOptions: {} }, - ): Promise { - return publishCloudEvents(this._client, topicName, events, options); + eventSubscriptionName: string, + lockTokens: RejectOptions, + options: RejectCloudEventsOptionalParams = { requestOptions: {} }, + ): Promise { + return rejectCloudEvents( + this._client, + topicName, + eventSubscriptionName, + lockTokens, + options, + ); } - /** Receive Batch of Cloud Events from the Event Subscription. */ - receiveCloudEvents( + /** Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is successfully released. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. */ + releaseCloudEvents( topicName: string, eventSubscriptionName: string, - options: ReceiveCloudEventsOptionalParams = { requestOptions: {} }, - ): Promise { - return receiveCloudEvents( + lockTokens: ReleaseOptions, + options: ReleaseCloudEventsOptionalParams = { requestOptions: {} }, + ): Promise { + return releaseCloudEvents( this._client, topicName, eventSubscriptionName, + lockTokens, options, ); } @@ -106,35 +104,37 @@ export class EventGridClient { ); } - /** Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is successfully released. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. */ - releaseCloudEvents( + /** Receive Batch of Cloud Events from the Event Subscription. */ + receiveCloudEvents( topicName: string, eventSubscriptionName: string, - lockTokens: ReleaseOptions, - options: ReleaseCloudEventsOptionalParams = { requestOptions: {} }, - ): Promise { - return releaseCloudEvents( + options: ReceiveCloudEventsOptionalParams = { requestOptions: {} }, + ): Promise { + return receiveCloudEvents( this._client, topicName, eventSubscriptionName, - lockTokens, options, ); } - /** Reject batch of Cloud Events. */ - rejectCloudEvents( + /** Publish Batch Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ + publishCloudEvents( topicName: string, - eventSubscriptionName: string, - lockTokens: RejectOptions, - options: RejectCloudEventsOptionalParams = { requestOptions: {} }, - ): Promise { - return rejectCloudEvents( - this._client, - topicName, - eventSubscriptionName, - lockTokens, - options, - ); + events: CloudEvent[], + options: PublishCloudEventsOptionalParams = { requestOptions: {} }, + ): Promise { + return publishCloudEvents(this._client, topicName, events, options); + } + + /** Publish Single Cloud Event to namespace topic. In case of success, the server responds with an HTTP 200 status code with an empty JSON object in response. Otherwise, the server can return various error codes. For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for internal server error. */ + publishCloudEvent( + topicName: string, + event: { + event: CloudEvent; + }, + options: PublishCloudEventOptionalParams = { requestOptions: {} }, + ): Promise { + return publishCloudEvent(this._client, topicName, event, options); } } diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts index 710d80405e..7453f778b6 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/index.ts @@ -19,10 +19,10 @@ export { } from "./models/index.js"; export { EventGridClientOptionalParams, - PublishCloudEventOptionalParams, - PublishCloudEventsOptionalParams, - ReceiveCloudEventsOptionalParams, - AcknowledgeCloudEventsOptionalParams, - ReleaseCloudEventsOptionalParams, RejectCloudEventsOptionalParams, + ReleaseCloudEventsOptionalParams, + AcknowledgeCloudEventsOptionalParams, + ReceiveCloudEventsOptionalParams, + PublishCloudEventsOptionalParams, + PublishCloudEventOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts index 2274727647..7700a165ca 100644 --- a/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/eventgrid_modular/generated/typespec-ts/src/models/models.ts @@ -47,7 +47,7 @@ export function cloudEventSerializer(item: CloudEvent): any { ? item["dataBase64"] : uint8ArrayToString(item["dataBase64"], "base64"), type: item["type"], - time: item["time"]?.toISOString(), + time: !item["time"] ? item["time"] : item["time"].toISOString(), specversion: item["specversion"], dataschema: item["dataschema"], datacontenttype: item["datacontenttype"], diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/operations.ts index c95cdae3f5..c5c2a995ec 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/operations.ts @@ -7,8 +7,8 @@ import { } from "./index.js"; import { PatientRecord, - patientRecordSerializer, - radiologyInsightsInferenceOptionsSerializer, + radiologyInsightsModelConfigurationSerializer, + patientRecordArraySerializer, RadiologyInsightsInferenceResult, radiologyInsightsInferenceResultDeserializer, } from "../models/models.js"; @@ -26,41 +26,35 @@ export function _inferRadiologyInsightsSend( patients: PatientRecord[], options: InferRadiologyInsightsOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/radiology-insights/jobs").post({ - ...operationOptionsToRequestParameters(options), - headers: { - ...(options?.repeatabilityRequestId !== undefined - ? { "Repeatability-Request-ID": options?.repeatabilityRequestId } - : {}), - ...(options?.repeatabilityFirstSent !== undefined - ? { - "Repeatability-First-Sent": !options?.repeatabilityFirstSent - ? options?.repeatabilityFirstSent - : options?.repeatabilityFirstSent.toUTCString(), - } - : {}), - }, - body: { - patients: patients.map((p: any) => { - return patientRecordSerializer(p); - }), - configuration: { - verbose: options?.configuration?.["verbose"], - includeEvidence: options?.configuration?.["includeEvidence"], - inferenceTypes: !options?.configuration?.["inferenceTypes"] - ? options?.configuration?.["inferenceTypes"] - : options?.configuration?.["inferenceTypes"].map((p: any) => { - return p; - }), - inferenceOptions: !options?.configuration?.["inferenceOptions"] - ? options?.configuration?.["inferenceOptions"] - : radiologyInsightsInferenceOptionsSerializer( - options?.configuration?.["inferenceOptions"], + return context + .path("/radiology-insights/jobs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + ...(options?.repeatabilityRequestId !== undefined + ? { "Repeatability-Request-ID": options?.repeatabilityRequestId } + : {}), + ...(options?.repeatabilityFirstSent !== undefined + ? { + "Repeatability-First-Sent": !options?.repeatabilityFirstSent + ? options?.repeatabilityFirstSent + : options?.repeatabilityFirstSent.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: { + patients: patientRecordArraySerializer(patients), + configuration: !options?.configuration + ? options?.configuration + : radiologyInsightsModelConfigurationSerializer( + options?.configuration, ), - locale: options?.configuration?.["locale"], }, - }, - }); + }); } export async function _inferRadiologyInsightsDeserialize( diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/options.ts index 81b1a219a7..51a2dae974 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/options.ts @@ -1,17 +1,17 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { OperationOptions } from "@azure-rest/core-client"; import { RadiologyInsightsModelConfiguration } from "../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ export interface InferRadiologyInsightsOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; + /** Configuration affecting the Radiology Insights model's inference. */ + configuration?: RadiologyInsightsModelConfiguration; /** An opaque, globally-unique, client-generated string identifier for the request. */ repeatabilityRequestId?: string; /** Specifies the date and time at which the request was first created. */ repeatabilityFirstSent?: Date; - /** Configuration affecting the Radiology Insights model's inference. */ - configuration?: RadiologyInsightsModelConfiguration; } diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/radiologyInsightsContext.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/radiologyInsightsContext.ts index 5fd8dc7a43..e24c57f5b4 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/radiologyInsightsContext.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/api/radiologyInsightsContext.ts @@ -6,7 +6,11 @@ import { KnownApiVersion } from "../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { KeyCredential } from "@azure/core-auth"; -export interface RadiologyInsightsContext extends Client {} +export interface RadiologyInsightsContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownApiVersion} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface RadiologyInsightsClientOptionalParams extends ClientOptions { @@ -54,5 +58,5 @@ export function createRadiologyInsights( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as RadiologyInsightsContext; } diff --git a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/models/models.ts index 953e733046..c35d6172da 100644 --- a/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/healthInsights_radiologyinsights/generated/typespec-ts/src/models/models.ts @@ -247,8 +247,8 @@ export interface TimePeriod { export function timePeriodSerializer(item: TimePeriod): any { return { - start: item["start"]?.toISOString(), - end: item["end"]?.toISOString(), + start: !item["start"] ? item["start"] : item["start"].toISOString(), + end: !item["end"] ? item["end"] : item["end"].toISOString(), }; } @@ -297,7 +297,9 @@ export function patientDocumentSerializer(item: PatientDocument): any { clinicalType: item["clinicalType"], id: item["id"], language: item["language"], - createdDateTime: item["createdDateTime"]?.toISOString(), + createdDateTime: !item["createdDateTime"] + ? item["createdDateTime"] + : item["createdDateTime"].toISOString(), authors: !item["authors"] ? item["authors"] : documentAuthorArraySerializer(item["authors"]), @@ -1477,6 +1479,7 @@ export interface Observation extends DomainResource { export function observationDeserializer(item: any): Observation { return { ...item, + resourceType: item["resourceType"], text: !item["text"] ? item["text"] : narrativeDeserializer(item["text"]), contained: !item["contained"] ? item["contained"] @@ -1487,7 +1490,6 @@ export function observationDeserializer(item: any): Observation { modifierExtension: !item["modifierExtension"] ? item["modifierExtension"] : extensionArrayDeserializer(item["modifierExtension"]), - resourceType: item["resourceType"], id: item["id"], meta: !item["meta"] ? item["meta"] : metaDeserializer(item["meta"]), implicitRules: item["implicitRules"], diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json index bd395c7c4f..127887b3fd 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/package.json @@ -13,10 +13,10 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/b": "./src/api/b/index.ts", - "./api/b/e/c": "./src/api/b/e/c/index.ts", + "./api/d": "./src/api/d/index.ts", "./api/b/c": "./src/api/b/c/index.ts", - "./api/d": "./src/api/d/index.ts" + "./api/b/e/c": "./src/api/b/e/c/index.ts", + "./api/b": "./src/api/b/index.ts" }, "dialects": [ "esm", @@ -144,40 +144,22 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/b": { - "browser": { - "types": "./dist/browser/api/b/index.d.ts", - "default": "./dist/browser/api/b/index.js" - }, - "react-native": { - "types": "./dist/react-native/api/b/index.d.ts", - "default": "./dist/react-native/api/b/index.js" - }, - "import": { - "types": "./dist/esm/api/b/index.d.ts", - "default": "./dist/esm/api/b/index.js" - }, - "require": { - "types": "./dist/commonjs/api/b/index.d.ts", - "default": "./dist/commonjs/api/b/index.js" - } - }, - "./api/b/e/c": { + "./api/d": { "browser": { - "types": "./dist/browser/api/b/e/c/index.d.ts", - "default": "./dist/browser/api/b/e/c/index.js" + "types": "./dist/browser/api/d/index.d.ts", + "default": "./dist/browser/api/d/index.js" }, "react-native": { - "types": "./dist/react-native/api/b/e/c/index.d.ts", - "default": "./dist/react-native/api/b/e/c/index.js" + "types": "./dist/react-native/api/d/index.d.ts", + "default": "./dist/react-native/api/d/index.js" }, "import": { - "types": "./dist/esm/api/b/e/c/index.d.ts", - "default": "./dist/esm/api/b/e/c/index.js" + "types": "./dist/esm/api/d/index.d.ts", + "default": "./dist/esm/api/d/index.js" }, "require": { - "types": "./dist/commonjs/api/b/e/c/index.d.ts", - "default": "./dist/commonjs/api/b/e/c/index.js" + "types": "./dist/commonjs/api/d/index.d.ts", + "default": "./dist/commonjs/api/d/index.js" } }, "./api/b/c": { @@ -198,22 +180,40 @@ "default": "./dist/commonjs/api/b/c/index.js" } }, - "./api/d": { + "./api/b/e/c": { "browser": { - "types": "./dist/browser/api/d/index.d.ts", - "default": "./dist/browser/api/d/index.js" + "types": "./dist/browser/api/b/e/c/index.d.ts", + "default": "./dist/browser/api/b/e/c/index.js" }, "react-native": { - "types": "./dist/react-native/api/d/index.d.ts", - "default": "./dist/react-native/api/d/index.js" + "types": "./dist/react-native/api/b/e/c/index.d.ts", + "default": "./dist/react-native/api/b/e/c/index.js" }, "import": { - "types": "./dist/esm/api/d/index.d.ts", - "default": "./dist/esm/api/d/index.js" + "types": "./dist/esm/api/b/e/c/index.d.ts", + "default": "./dist/esm/api/b/e/c/index.js" }, "require": { - "types": "./dist/commonjs/api/d/index.d.ts", - "default": "./dist/commonjs/api/d/index.js" + "types": "./dist/commonjs/api/b/e/c/index.d.ts", + "default": "./dist/commonjs/api/b/e/c/index.js" + } + }, + "./api/b": { + "browser": { + "types": "./dist/browser/api/b/index.d.ts", + "default": "./dist/browser/api/b/index.js" + }, + "react-native": { + "types": "./dist/react-native/api/b/index.d.ts", + "default": "./dist/react-native/api/b/index.js" + }, + "import": { + "types": "./dist/esm/api/b/index.d.ts", + "default": "./dist/esm/api/b/index.js" + }, + "require": { + "types": "./dist/commonjs/api/b/index.d.ts", + "default": "./dist/commonjs/api/b/index.js" } } }, diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts index ed37ae2eb6..6b08c7be47 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/c/index.ts @@ -19,6 +19,7 @@ export function _op1Send( .path("/b/c") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", body: baSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts index 5ce947d93f..fb3d4a5208 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/e/c/index.ts @@ -19,6 +19,7 @@ export function _op1Send( .path("/b/e") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", body: beaSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts index 2a52876fa2..1a7051ad54 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/b/index.ts @@ -19,6 +19,7 @@ export function _op1Send( .path("/b") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", body: baSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts index 88a9c3c693..4917071436 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/d/index.ts @@ -19,6 +19,7 @@ export function _op1Send( .path("/d") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", body: aSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts index c044a71254..318e2aa4fb 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/fooContext.ts @@ -13,6 +13,8 @@ export function createFoo( endpointParam: string, options: FooClientOptionalParams = {}, ): FooContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-hierarchy-generic/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -23,11 +25,7 @@ export function createFoo( userAgentOptions: { userAgentPrefix }, loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; - const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? String(endpointParam), - undefined, - updatedOptions, - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); if (options.apiVersion) { logger.warning( diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts index f65f356c47..400dc8964e 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/index.ts @@ -8,9 +8,9 @@ export { } from "./fooContext.js"; export { op1 } from "./operations.js"; export { - Op1OptionalParams, - BOp1OptionalParams, - BECOp1OptionalParams, - BCOp1OptionalParams, DOp1OptionalParams, + BCOp1OptionalParams, + BECOp1OptionalParams, + BOp1OptionalParams, + Op1OptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts index 158936ffaa..f2fac5451d 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/operations.ts @@ -19,6 +19,7 @@ export function _op1Send( .path("/") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", body: aSerializer(body), }); } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/options.ts index 7dfde86d85..1f1282ddaf 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/api/options.ts @@ -4,16 +4,16 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface Op1OptionalParams extends OperationOptions {} +export interface DOp1OptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface BOp1OptionalParams extends OperationOptions {} +export interface BCOp1OptionalParams extends OperationOptions {} /** Optional parameters. */ export interface BECOp1OptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface BCOp1OptionalParams extends OperationOptions {} +export interface BOp1OptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DOp1OptionalParams extends OperationOptions {} +export interface Op1OptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts index d0f7c5c6f4..4ae4bcc6d4 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/classic/b/index.ts @@ -11,8 +11,8 @@ import { BEOperations, getBEOperations } from "./e/index.js"; /** Interface representing a B operations. */ export interface BOperations { op1: (body: Ba, options?: BOp1OptionalParams) => Promise; - e: BEOperations; c: BCOperations; + e: BEOperations; } export function getB(context: FooContext) { @@ -25,7 +25,7 @@ export function getB(context: FooContext) { export function getBOperations(context: FooContext): BOperations { return { ...getB(context), - e: getBEOperations(context), c: getBCOperations(context), + e: getBEOperations(context), }; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts index 37cc6badaf..c60543c5d9 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/fooClient.ts @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { getBOperations, BOperations } from "./classic/b/index.js"; import { getDOperations, DOperations } from "./classic/d/index.js"; +import { getBOperations, BOperations } from "./classic/b/index.js"; import { createFoo, FooContext, @@ -30,19 +30,19 @@ export class FooClient { userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; - this.b = getBOperations(this._client); this.d = getDOperations(this._client); + this.b = getBOperations(this._client); } + /** The operation groups for d */ + public readonly d: DOperations; + /** The operation groups for b */ + public readonly b: BOperations; + op1( body: A, options: Op1OptionalParams = { requestOptions: {} }, ): Promise { return op1(this._client, body, options); } - - /** The operation groups for B */ - public readonly b: BOperations; - /** The operation groups for D */ - public readonly d: DOperations; } diff --git a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts index f07da1513d..96e5c0c3b1 100644 --- a/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/hierarchy_generic/generated/typespec-ts/src/index.ts @@ -5,11 +5,11 @@ export { FooClient } from "./fooClient.js"; export { A, Ba, Bea } from "./models/index.js"; export { FooClientOptionalParams, - Op1OptionalParams, - BOp1OptionalParams, - BECOp1OptionalParams, - BCOp1OptionalParams, DOp1OptionalParams, + BCOp1OptionalParams, + BECOp1OptionalParams, + BOp1OptionalParams, + Op1OptionalParams, } from "./api/index.js"; export { BOperations, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md index fb0569faaf..5ffc76bdf1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -53,32 +53,26 @@ export type ContinuablePage = TPage & { // @public export interface CreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface CreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface CreateOrUpdateTestOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface CreateOrUpdateTestProfileOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface CreateOrUpdateTestProfileRunOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { - contentType?: string; oldTestRunId?: string; } @@ -476,12 +470,10 @@ export class LoadTestRunClient { // @public export interface LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParams extends OperationOptions { - contentType?: string; } // @public @@ -932,7 +924,6 @@ export interface TimeSeriesElement { // @public export interface UploadTestFileOptionalParams extends OperationOptions { - contentType?: string; fileType?: FileType; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts index 29ca730c59..2a72c5bb19 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/index.ts @@ -94,52 +94,52 @@ export { } from "./models/index.js"; export { LoadTestAdministrationClientOptionalParams, - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, DeleteTestOptionalParams, + DeleteTestFileOptionalParams, + UploadTestFileOptionalParams, + ListTestsOptionalParams, + ListTestFilesOptionalParams, + GetTestFileOptionalParams, + GetTestOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestOptionalParams, } from "./loadTestAdministration/api/index.js"; export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; export { LoadTestRunClient } from "./loadTestRun/loadTestRunClient.js"; export { LoadTestRunClientOptionalParams, - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams as LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams as LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams as LoadTestRunClientGetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams as LoadTestRunClientGetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, StopTestRunOptionalParams, + ListTestRunsOptionalParams, + ListMetricsOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricDimensionValuesOptionalParams, + GetTestRunFileOptionalParams, + GetTestRunOptionalParams, + GetServerMetricsConfigOptionalParams as LoadTestRunClientGetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams as LoadTestRunClientGetAppComponentsOptionalParams, + DeleteTestRunOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams as LoadTestRunClientCreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams as LoadTestRunClientCreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestRunOptionalParams, } from "./loadTestRun/api/index.js"; export { TestProfileAdministrationClient } from "./testProfileAdministration/testProfileAdministrationClient.js"; export { - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, ListTestProfilesOptionalParams, + GetTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + CreateOrUpdateTestProfileOptionalParams, TestProfileAdministrationClientOptionalParams, } from "./testProfileAdministration/api/index.js"; export { TestProfileRunClient } from "./testProfileRun/testProfileRunClient.js"; export { - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, StopTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + GetTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + CreateOrUpdateTestProfileRunOptionalParams, TestProfileRunClientOptionalParams, } from "./testProfileRun/api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts index 44e82f5edd..2c8e84081a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/index.ts @@ -7,30 +7,30 @@ export { LoadTestAdministrationClientOptionalParams, } from "./loadTestAdministrationContext.js"; export { - createOrUpdateTest, - createOrUpdateAppComponents, - createOrUpdateServerMetricsConfig, - getAppComponents, - getServerMetricsConfig, - getTest, - getTestFile, - listTestFiles, - listTests, - uploadTestFile, - deleteTestFile, deleteTest, + deleteTestFile, + uploadTestFile, + listTests, + listTestFiles, + getTestFile, + getTest, + getServerMetricsConfig, + getAppComponents, + createOrUpdateServerMetricsConfig, + createOrUpdateAppComponents, + createOrUpdateTest, } from "./operations.js"; export { - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, DeleteTestOptionalParams, + DeleteTestFileOptionalParams, + UploadTestFileOptionalParams, + ListTestsOptionalParams, + ListTestFilesOptionalParams, + GetTestFileOptionalParams, + GetTestOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts index 938d630deb..3b2416714f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/loadTestAdministrationContext.ts @@ -6,7 +6,11 @@ import { KnownAPIVersions } from "../../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface LoadTestAdministrationContext extends Client {} +export interface LoadTestAdministrationContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownAPIVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface LoadTestAdministrationClientOptionalParams @@ -56,5 +60,5 @@ export function createLoadTestAdministration( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as LoadTestAdministrationContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts index c5da4f8cf1..d003541b28 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/operations.ts @@ -44,452 +44,529 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createOrUpdateTestSend( +export function _deleteTestSend( context: Client, testId: string, - body: Test, - options: CreateOrUpdateTestOptionalParams = { requestOptions: {} }, + options: DeleteTestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/tests/{testId}", testId) - .patch({ + .delete({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createOrUpdateTestDeserialize( +export async function _deleteTestDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201", "200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testDeserializer(result.body); + return; } -/** Create a new test or update an existing test by providing the test Id. */ -export async function createOrUpdateTest( +/** Delete a test by its test Id. */ +export async function deleteTest( context: Client, testId: string, - body: Test, - options: CreateOrUpdateTestOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createOrUpdateTestSend(context, testId, body, options); - return _createOrUpdateTestDeserialize(result); + options: DeleteTestOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTestSend(context, testId, options); + return _deleteTestDeserialize(result); } -export function _createOrUpdateAppComponentsSend( +export function _deleteTestFileSend( context: Client, testId: string, - body: TestAppComponents, - options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, + fileName: string, + options: DeleteTestFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/app-components", testId) - .patch({ + .path("/tests/{testId}/files/{fileName}", testId, fileName) + .delete({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testAppComponentsSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createOrUpdateAppComponentsDeserialize( +export async function _deleteTestFileDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201", "200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testAppComponentsDeserializer(result.body); + return; } -/** Add an app component to a test by providing the resource Id, name and type. */ -export async function createOrUpdateAppComponents( +/** Delete file by the file name for a test */ +export async function deleteTestFile( context: Client, testId: string, - body: TestAppComponents, - options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createOrUpdateAppComponentsSend( - context, - testId, - body, - options, - ); - return _createOrUpdateAppComponentsDeserialize(result); + fileName: string, + options: DeleteTestFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTestFileSend(context, testId, fileName, options); + return _deleteTestFileDeserialize(result); } -export function _createOrUpdateServerMetricsConfigSend( +export function _uploadTestFileSend( context: Client, testId: string, - body: TestServerMetricConfig, - options: CreateOrUpdateServerMetricsConfigOptionalParams = { - requestOptions: {}, - }, + fileName: string, + body: Uint8Array, + options: UploadTestFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/server-metrics-config", testId) - .patch({ + .path("/tests/{testId}/files/{fileName}", testId, fileName) + .put({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testServerMetricConfigSerializer(body), + contentType: "application/octet-stream", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + fileType: options?.fileType, + }, + body: body, }); } -export async function _createOrUpdateServerMetricsConfigDeserialize( +export async function _uploadTestFileDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201", "200"]; +): Promise { + const expectedStatuses = ["201"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testServerMetricConfigDeserializer(result.body); + return testFileInfoDeserializer(result.body); } -/** Configure server metrics for a test */ -export async function createOrUpdateServerMetricsConfig( +/** + * Upload input file for a given test Id. File size can't be more than 50 MB. + * Existing file with same name for the given test will be overwritten. File + * should be provided in the request body as application/octet-stream. + */ +export async function uploadTestFile( context: Client, testId: string, - body: TestServerMetricConfig, - options: CreateOrUpdateServerMetricsConfigOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _createOrUpdateServerMetricsConfigSend( + fileName: string, + body: Uint8Array, + options: UploadTestFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _uploadTestFileSend( context, testId, + fileName, body, options, ); - return _createOrUpdateServerMetricsConfigDeserialize(result); + return _uploadTestFileDeserialize(result); } -export function _getAppComponentsSend( +export function _listTestsSend( context: Client, - testId: string, - options: GetAppComponentsOptionalParams = { requestOptions: {} }, + options: ListTestsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/app-components", testId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/tests") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + orderby: options?.orderby, + search: options?.search, + lastModifiedStartTime: !options?.lastModifiedStartTime + ? options?.lastModifiedStartTime + : options?.lastModifiedStartTime.toISOString(), + lastModifiedEndTime: !options?.lastModifiedEndTime + ? options?.lastModifiedEndTime + : options?.lastModifiedEndTime.toISOString(), + maxpagesize: options?.maxpagesize, + }, + }); } -export async function _getAppComponentsDeserialize( +export async function _listTestsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_PagedTest> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testAppComponentsDeserializer(result.body); + return _pagedTestDeserializer(result.body); } -/** Get associated app component (collection of azure resources) for the given test. */ -export async function getAppComponents( +/** + * Get all load tests by the fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. + */ +export function listTests( context: Client, - testId: string, - options: GetAppComponentsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getAppComponentsSend(context, testId, options); - return _getAppComponentsDeserialize(result); + options: ListTestsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTestsSend(context, options), + _listTestsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); } -export function _getServerMetricsConfigSend( +export function _listTestFilesSend( context: Client, testId: string, - options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, + options: ListTestFilesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/server-metrics-config", testId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/tests/{testId}/files", testId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getServerMetricsConfigDeserialize( +export async function _listTestFilesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_PagedTestFileInfo> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testServerMetricConfigDeserializer(result.body); + return _pagedTestFileInfoDeserializer(result.body); } -/** List server metrics configuration for the given test. */ -export async function getServerMetricsConfig( +/** Get all test files. */ +export function listTestFiles( context: Client, testId: string, - options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getServerMetricsConfigSend(context, testId, options); - return _getServerMetricsConfigDeserialize(result); + options: ListTestFilesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTestFilesSend(context, testId, options), + _listTestFilesDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); } -export function _getTestSend( +export function _getTestFileSend( context: Client, testId: string, - options: GetTestOptionalParams = { requestOptions: {} }, + fileName: string, + options: GetTestFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}", testId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/tests/{testId}/files/{fileName}", testId, fileName) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getTestDeserialize( +export async function _getTestFileDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testDeserializer(result.body); + return testFileInfoDeserializer(result.body); } -/** Get load test details by test Id */ -export async function getTest( +/** Get all the files that are associated with a test. */ +export async function getTestFile( context: Client, testId: string, - options: GetTestOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTestSend(context, testId, options); - return _getTestDeserialize(result); + fileName: string, + options: GetTestFileOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTestFileSend(context, testId, fileName, options); + return _getTestFileDeserialize(result); } -export function _getTestFileSend( +export function _getTestSend( context: Client, testId: string, - fileName: string, - options: GetTestFileOptionalParams = { requestOptions: {} }, + options: GetTestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/files/{fileName}", testId, fileName) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/tests/{testId}", testId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getTestFileDeserialize( +export async function _getTestDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testFileInfoDeserializer(result.body); + return testDeserializer(result.body); } -/** Get all the files that are associated with a test. */ -export async function getTestFile( +/** Get load test details by test Id */ +export async function getTest( context: Client, testId: string, - fileName: string, - options: GetTestFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTestFileSend(context, testId, fileName, options); - return _getTestFileDeserialize(result); + options: GetTestOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTestSend(context, testId, options); + return _getTestDeserialize(result); } -export function _listTestFilesSend( +export function _getServerMetricsConfigSend( context: Client, testId: string, - options: ListTestFilesOptionalParams = { requestOptions: {} }, + options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/files", testId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/tests/{testId}/server-metrics-config", testId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _listTestFilesDeserialize( +export async function _getServerMetricsConfigDeserialize( result: PathUncheckedResponse, -): Promise<_PagedTestFileInfo> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedTestFileInfoDeserializer(result.body); + return testServerMetricConfigDeserializer(result.body); } -/** Get all test files. */ -export function listTestFiles( +/** List server metrics configuration for the given test. */ +export async function getServerMetricsConfig( context: Client, testId: string, - options: ListTestFilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listTestFilesSend(context, testId, options), - _listTestFilesDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); + options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getServerMetricsConfigSend(context, testId, options); + return _getServerMetricsConfigDeserialize(result); } -export function _listTestsSend( +export function _getAppComponentsSend( context: Client, - options: ListTestsOptionalParams = { requestOptions: {} }, + testId: string, + options: GetAppComponentsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests") + .path("/tests/{testId}/app-components", testId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { - orderby: options?.orderby, - search: options?.search, - lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), - lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), - maxpagesize: options?.maxpagesize, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _listTestsDeserialize( +export async function _getAppComponentsDeserialize( result: PathUncheckedResponse, -): Promise<_PagedTest> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedTestDeserializer(result.body); + return testAppComponentsDeserializer(result.body); } -/** - * Get all load tests by the fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. - */ -export function listTests( +/** Get associated app component (collection of azure resources) for the given test. */ +export async function getAppComponents( context: Client, - options: ListTestsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listTestsSend(context, options), - _listTestsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, - ); + testId: string, + options: GetAppComponentsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getAppComponentsSend(context, testId, options); + return _getAppComponentsDeserialize(result); } -export function _uploadTestFileSend( +export function _createOrUpdateServerMetricsConfigSend( context: Client, testId: string, - fileName: string, - body: Uint8Array, - options: UploadTestFileOptionalParams = { requestOptions: {} }, + body: TestServerMetricConfig, + options: CreateOrUpdateServerMetricsConfigOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/tests/{testId}/files/{fileName}", testId, fileName) - .put({ + .path("/tests/{testId}/server-metrics-config", testId) + .patch({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "application/octet-stream", - queryParameters: { fileType: options?.fileType }, - body: body, + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: testServerMetricConfigSerializer(body), }); } -export async function _uploadTestFileDeserialize( +export async function _createOrUpdateServerMetricsConfigDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testFileInfoDeserializer(result.body); + return testServerMetricConfigDeserializer(result.body); } -/** - * Upload input file for a given test Id. File size can't be more than 50 MB. - * Existing file with same name for the given test will be overwritten. File - * should be provided in the request body as application/octet-stream. - */ -export async function uploadTestFile( +/** Configure server metrics for a test */ +export async function createOrUpdateServerMetricsConfig( context: Client, testId: string, - fileName: string, - body: Uint8Array, - options: UploadTestFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _uploadTestFileSend( + body: TestServerMetricConfig, + options: CreateOrUpdateServerMetricsConfigOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _createOrUpdateServerMetricsConfigSend( context, testId, - fileName, body, options, ); - return _uploadTestFileDeserialize(result); + return _createOrUpdateServerMetricsConfigDeserialize(result); } -export function _deleteTestFileSend( +export function _createOrUpdateAppComponentsSend( context: Client, testId: string, - fileName: string, - options: DeleteTestFileOptionalParams = { requestOptions: {} }, + body: TestAppComponents, + options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/tests/{testId}/files/{fileName}", testId, fileName) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/tests/{testId}/app-components", testId) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: testAppComponentsSerializer(body), + }); } -export async function _deleteTestFileDeserialize( +export async function _createOrUpdateAppComponentsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return testAppComponentsDeserializer(result.body); } -/** Delete file by the file name for a test */ -export async function deleteTestFile( +/** Add an app component to a test by providing the resource Id, name and type. */ +export async function createOrUpdateAppComponents( context: Client, testId: string, - fileName: string, - options: DeleteTestFileOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteTestFileSend(context, testId, fileName, options); - return _deleteTestFileDeserialize(result); + body: TestAppComponents, + options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateAppComponentsSend( + context, + testId, + body, + options, + ); + return _createOrUpdateAppComponentsDeserialize(result); } -export function _deleteTestSend( +export function _createOrUpdateTestSend( context: Client, testId: string, - options: DeleteTestOptionalParams = { requestOptions: {} }, + body: Test, + options: CreateOrUpdateTestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/tests/{testId}", testId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: testSerializer(body), + }); } -export async function _deleteTestDeserialize( +export async function _createOrUpdateTestDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return testDeserializer(result.body); } -/** Delete a test by its test Id. */ -export async function deleteTest( +/** Create a new test or update an existing test by providing the test Id. */ +export async function createOrUpdateTest( context: Client, testId: string, - options: DeleteTestOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteTestSend(context, testId, options); - return _deleteTestDeserialize(result); + body: Test, + options: CreateOrUpdateTestOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateTestSend(context, testId, body, options); + return _createOrUpdateTestDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts index 5f76c93bb7..2386d06167 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/options.ts @@ -1,45 +1,21 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { OperationOptions } from "@azure-rest/core-client"; import { FileType } from "../../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface CreateOrUpdateTestOptionalParams extends OperationOptions { - /** This request has a JSON Merge Patch body. */ - contentType?: string; -} +export interface DeleteTestOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface CreateOrUpdateAppComponentsOptionalParams - extends OperationOptions { - /** Content type. */ - contentType?: string; -} +export interface DeleteTestFileOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface CreateOrUpdateServerMetricsConfigOptionalParams - extends OperationOptions { - /** Content type. */ - contentType?: string; +export interface UploadTestFileOptionalParams extends OperationOptions { + /** File type */ + fileType?: FileType; } -/** Optional parameters. */ -export interface GetAppComponentsOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetServerMetricsConfigOptionalParams - extends OperationOptions {} - -/** Optional parameters. */ -export interface GetTestOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetTestFileOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface ListTestFilesOptionalParams extends OperationOptions {} - /** Optional parameters. */ export interface ListTestsOptionalParams extends OperationOptions { /** @@ -62,15 +38,28 @@ export interface ListTestsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface UploadTestFileOptionalParams extends OperationOptions { - /** Content type. */ - contentType?: string; - /** File type */ - fileType?: FileType; -} +export interface ListTestFilesOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DeleteTestFileOptionalParams extends OperationOptions {} +export interface GetTestFileOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DeleteTestOptionalParams extends OperationOptions {} +export interface GetTestOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface GetServerMetricsConfigOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface GetAppComponentsOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface CreateOrUpdateServerMetricsConfigOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface CreateOrUpdateAppComponentsOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface CreateOrUpdateTestOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts index 8470bd3fad..ac4696f65d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/index.ts @@ -5,16 +5,16 @@ export { LoadTestAdministrationClient } from "./loadTestAdministrationClient.js" export { LoadTestAdministrationContext, LoadTestAdministrationClientOptionalParams, - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, DeleteTestOptionalParams, + DeleteTestFileOptionalParams, + UploadTestFileOptionalParams, + ListTestsOptionalParams, + ListTestFilesOptionalParams, + GetTestFileOptionalParams, + GetTestOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts index 5408604ba4..0c6b16a608 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/loadTestAdministrationClient.ts @@ -5,30 +5,30 @@ import { createLoadTestAdministration, LoadTestAdministrationContext, LoadTestAdministrationClientOptionalParams, - createOrUpdateTest, - createOrUpdateAppComponents, - createOrUpdateServerMetricsConfig, - getAppComponents, - getServerMetricsConfig, - getTest, - getTestFile, - listTestFiles, - listTests, - uploadTestFile, - deleteTestFile, deleteTest, - CreateOrUpdateTestOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestOptionalParams, - GetTestFileOptionalParams, - ListTestFilesOptionalParams, - ListTestsOptionalParams, - UploadTestFileOptionalParams, - DeleteTestFileOptionalParams, + deleteTestFile, + uploadTestFile, + listTests, + listTestFiles, + getTestFile, + getTest, + getServerMetricsConfig, + getAppComponents, + createOrUpdateServerMetricsConfig, + createOrUpdateAppComponents, + createOrUpdateTest, DeleteTestOptionalParams, + DeleteTestFileOptionalParams, + UploadTestFileOptionalParams, + ListTestsOptionalParams, + ListTestFilesOptionalParams, + GetTestFileOptionalParams, + GetTestOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestOptionalParams, } from "./api/index.js"; import { Test, @@ -63,54 +63,62 @@ export class LoadTestAdministrationClient { this.pipeline = this._client.pipeline; } - /** Create a new test or update an existing test by providing the test Id. */ - createOrUpdateTest( + /** Delete a test by its test Id. */ + deleteTest( testId: string, - body: Test, - options: CreateOrUpdateTestOptionalParams = { requestOptions: {} }, - ): Promise { - return createOrUpdateTest(this._client, testId, body, options); + options: DeleteTestOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteTest(this._client, testId, options); } - /** Add an app component to a test by providing the resource Id, name and type. */ - createOrUpdateAppComponents( + /** Delete file by the file name for a test */ + deleteTestFile( testId: string, - body: TestAppComponents, - options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, - ): Promise { - return createOrUpdateAppComponents(this._client, testId, body, options); + fileName: string, + options: DeleteTestFileOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteTestFile(this._client, testId, fileName, options); } - /** Configure server metrics for a test */ - createOrUpdateServerMetricsConfig( + /** + * Upload input file for a given test Id. File size can't be more than 50 MB. + * Existing file with same name for the given test will be overwritten. File + * should be provided in the request body as application/octet-stream. + */ + uploadTestFile( testId: string, - body: TestServerMetricConfig, - options: CreateOrUpdateServerMetricsConfigOptionalParams = { - requestOptions: {}, - }, - ): Promise { - return createOrUpdateServerMetricsConfig( - this._client, - testId, - body, - options, - ); + fileName: string, + body: Uint8Array, + options: UploadTestFileOptionalParams = { requestOptions: {} }, + ): Promise { + return uploadTestFile(this._client, testId, fileName, body, options); } - /** Get associated app component (collection of azure resources) for the given test. */ - getAppComponents( + /** + * Get all load tests by the fully qualified resource Id e.g + * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. + */ + listTests( + options: ListTestsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTests(this._client, options); + } + + /** Get all test files. */ + listTestFiles( testId: string, - options: GetAppComponentsOptionalParams = { requestOptions: {} }, - ): Promise { - return getAppComponents(this._client, testId, options); + options: ListTestFilesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTestFiles(this._client, testId, options); } - /** List server metrics configuration for the given test. */ - getServerMetricsConfig( + /** Get all the files that are associated with a test. */ + getTestFile( testId: string, - options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, - ): Promise { - return getServerMetricsConfig(this._client, testId, options); + fileName: string, + options: GetTestFileOptionalParams = { requestOptions: {} }, + ): Promise { + return getTestFile(this._client, testId, fileName, options); } /** Get load test details by test Id */ @@ -121,61 +129,53 @@ export class LoadTestAdministrationClient { return getTest(this._client, testId, options); } - /** Get all the files that are associated with a test. */ - getTestFile( + /** List server metrics configuration for the given test. */ + getServerMetricsConfig( testId: string, - fileName: string, - options: GetTestFileOptionalParams = { requestOptions: {} }, - ): Promise { - return getTestFile(this._client, testId, fileName, options); + options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, + ): Promise { + return getServerMetricsConfig(this._client, testId, options); } - /** Get all test files. */ - listTestFiles( + /** Get associated app component (collection of azure resources) for the given test. */ + getAppComponents( testId: string, - options: ListTestFilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTestFiles(this._client, testId, options); - } - - /** - * Get all load tests by the fully qualified resource Id e.g - * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. - */ - listTests( - options: ListTestsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTests(this._client, options); + options: GetAppComponentsOptionalParams = { requestOptions: {} }, + ): Promise { + return getAppComponents(this._client, testId, options); } - /** - * Upload input file for a given test Id. File size can't be more than 50 MB. - * Existing file with same name for the given test will be overwritten. File - * should be provided in the request body as application/octet-stream. - */ - uploadTestFile( + /** Configure server metrics for a test */ + createOrUpdateServerMetricsConfig( testId: string, - fileName: string, - body: Uint8Array, - options: UploadTestFileOptionalParams = { requestOptions: {} }, - ): Promise { - return uploadTestFile(this._client, testId, fileName, body, options); + body: TestServerMetricConfig, + options: CreateOrUpdateServerMetricsConfigOptionalParams = { + requestOptions: {}, + }, + ): Promise { + return createOrUpdateServerMetricsConfig( + this._client, + testId, + body, + options, + ); } - /** Delete file by the file name for a test */ - deleteTestFile( + /** Add an app component to a test by providing the resource Id, name and type. */ + createOrUpdateAppComponents( testId: string, - fileName: string, - options: DeleteTestFileOptionalParams = { requestOptions: {} }, - ): Promise { - return deleteTestFile(this._client, testId, fileName, options); + body: TestAppComponents, + options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateAppComponents(this._client, testId, body, options); } - /** Delete a test by its test Id. */ - deleteTest( + /** Create a new test or update an existing test by providing the test Id. */ + createOrUpdateTest( testId: string, - options: DeleteTestOptionalParams = { requestOptions: {} }, - ): Promise { - return deleteTest(this._client, testId, options); + body: Test, + options: CreateOrUpdateTestOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateTest(this._client, testId, body, options); } } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts index 5180ae7e37..89b564274c 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/index.ts @@ -7,34 +7,34 @@ export { LoadTestRunClientOptionalParams, } from "./loadTestRunContext.js"; export { - createOrUpdateTestRun, - createOrUpdateAppComponents, - createOrUpdateServerMetricsConfig, - deleteTestRun, - getAppComponents, - getServerMetricsConfig, - getTestRun, - getTestRunFile, - listMetricDimensionValues, - listMetricDefinitions, - listMetricNamespaces, - listMetrics, - listTestRuns, stopTestRun, + listTestRuns, + listMetrics, + listMetricNamespaces, + listMetricDefinitions, + listMetricDimensionValues, + getTestRunFile, + getTestRun, + getServerMetricsConfig, + getAppComponents, + deleteTestRun, + createOrUpdateServerMetricsConfig, + createOrUpdateAppComponents, + createOrUpdateTestRun, } from "./operations.js"; export { - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, StopTestRunOptionalParams, + ListTestRunsOptionalParams, + ListMetricsOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricDimensionValuesOptionalParams, + GetTestRunFileOptionalParams, + GetTestRunOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + DeleteTestRunOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestRunOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts index 71d1362608..bcf2b1bc42 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/loadTestRunContext.ts @@ -6,7 +6,11 @@ import { KnownAPIVersions } from "../../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface LoadTestRunContext extends Client {} +export interface LoadTestRunContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownAPIVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface LoadTestRunClientOptionalParams extends ClientOptions { @@ -55,5 +59,5 @@ export function createLoadTestRun( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as LoadTestRunContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts index 4f9e14838f..fe256ba686 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/operations.ts @@ -54,27 +54,27 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createOrUpdateTestRunSend( +export function _stopTestRunSend( context: Client, testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}", testRunId) - .patch({ + .path("/test-runs/{testRunId}:stop", testRunId) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - queryParameters: { oldTestRunId: options?.oldTestRunId }, - body: testRunSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createOrUpdateTestRunDeserialize( +export async function _stopTestRunDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["201", "200"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -82,237 +82,286 @@ export async function _createOrUpdateTestRunDeserialize( return testRunDeserializer(result.body); } -/** Create and start a new test run with the given test run Id. */ -export async function createOrUpdateTestRun( +/** Stop test run by test run Id. */ +export async function stopTestRun( context: Client, testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createOrUpdateTestRunSend( - context, - testRunId, - body, - options, - ); - return _createOrUpdateTestRunDeserialize(result); + const result = await _stopTestRunSend(context, testRunId, options); + return _stopTestRunDeserialize(result); } -export function _createOrUpdateAppComponentsSend( +export function _listTestRunsSend( context: Client, - testRunId: string, - body: TestRunAppComponents, - options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, + options: ListTestRunsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/app-components", testRunId) - .patch({ + .path("/test-runs") + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testRunAppComponentsSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + orderby: options?.orderby, + search: options?.search, + testId: options?.testId, + executionFrom: !options?.executionFrom + ? options?.executionFrom + : options?.executionFrom.toISOString(), + executionTo: !options?.executionTo + ? options?.executionTo + : options?.executionTo.toISOString(), + status: options?.status, + maxpagesize: options?.maxpagesize, + }, }); } -export async function _createOrUpdateAppComponentsDeserialize( +export async function _listTestRunsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201", "200"]; +): Promise<_PagedTestRun> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testRunAppComponentsDeserializer(result.body); + return _pagedTestRunDeserializer(result.body); } -/** Add an app component to a test run by providing the resource Id, name and type. */ -export async function createOrUpdateAppComponents( +/** Get all test runs for the given filters. */ +export function listTestRuns( context: Client, - testRunId: string, - body: TestRunAppComponents, - options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createOrUpdateAppComponentsSend( + options: ListTestRunsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - testRunId, - body, - options, + () => _listTestRunsSend(context, options), + _listTestRunsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _createOrUpdateAppComponentsDeserialize(result); } -export function _createOrUpdateServerMetricsConfigSend( +export function _listMetricsSend( context: Client, testRunId: string, - body: TestRunServerMetricConfig, - options: CreateOrUpdateServerMetricsConfigOptionalParams = { - requestOptions: {}, - }, + metricname: string, + metricNamespace: string, + timespan: string, + options: ListMetricsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/server-metrics-config", testRunId) - .patch({ + .path("/test-runs/{testRunId}/metrics", testRunId) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testRunServerMetricConfigSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + aggregation: options?.aggregation, + metricname: metricname, + interval: options?.interval, + metricNamespace: metricNamespace, + timespan: timespan, + }, + body: !options["body"] + ? options["body"] + : metricRequestPayloadSerializer(options["body"]), }); } -export async function _createOrUpdateServerMetricsConfigDeserialize( +export async function _listMetricsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["201", "200"]; +): Promise<_Metrics> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testRunServerMetricConfigDeserializer(result.body); + return _metricsDeserializer(result.body); } -/** Configure server metrics for a test run */ -export async function createOrUpdateServerMetricsConfig( +/** List the metric values for a load test run. */ +export function listMetrics( context: Client, testRunId: string, - body: TestRunServerMetricConfig, - options: CreateOrUpdateServerMetricsConfigOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _createOrUpdateServerMetricsConfigSend( + metricname: string, + metricNamespace: string, + timespan: string, + options: ListMetricsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - testRunId, - body, - options, + () => + _listMetricsSend( + context, + testRunId, + metricname, + metricNamespace, + timespan, + options, + ), + _listMetricsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _createOrUpdateServerMetricsConfigDeserialize(result); -} - -export function _deleteTestRunSend( - context: Client, - testRunId: string, - options: DeleteTestRunOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/test-runs/{testRunId}", testRunId) - .delete({ ...operationOptionsToRequestParameters(options) }); } -export async function _deleteTestRunDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return; -} - -/** Delete an existing load test run by providing the testRunId. */ -export async function deleteTestRun( - context: Client, - testRunId: string, - options: DeleteTestRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteTestRunSend(context, testRunId, options); - return _deleteTestRunDeserialize(result); -} - -export function _getAppComponentsSend( +export function _listMetricNamespacesSend( context: Client, testRunId: string, - options: GetAppComponentsOptionalParams = { requestOptions: {} }, + options: ListMetricNamespacesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/app-components", testRunId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/test-runs/{testRunId}/metric-namespaces", testRunId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _getAppComponentsDeserialize( +export async function _listMetricNamespacesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testRunAppComponentsDeserializer(result.body); + return metricNamespaceCollectionDeserializer(result.body); } -/** - * Get associated app component (collection of azure resources) for the given test - * run. - */ -export async function getAppComponents( +/** List the metric namespaces for a load test run. */ +export async function listMetricNamespaces( context: Client, testRunId: string, - options: GetAppComponentsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getAppComponentsSend(context, testRunId, options); - return _getAppComponentsDeserialize(result); + options: ListMetricNamespacesOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listMetricNamespacesSend(context, testRunId, options); + return _listMetricNamespacesDeserialize(result); } -export function _getServerMetricsConfigSend( +export function _listMetricDefinitionsSend( context: Client, testRunId: string, - options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, + metricNamespace: string, + options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/server-metrics-config", testRunId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/test-runs/{testRunId}/metric-definitions", testRunId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + metricNamespace: metricNamespace, + }, + }); } -export async function _getServerMetricsConfigDeserialize( +export async function _listMetricDefinitionsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testRunServerMetricConfigDeserializer(result.body); + return metricDefinitionCollectionDeserializer(result.body); } -/** Get associated server metrics configuration for the given test run. */ -export async function getServerMetricsConfig( +/** List the metric definitions for a load test run. */ +export async function listMetricDefinitions( context: Client, testRunId: string, - options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getServerMetricsConfigSend(context, testRunId, options); - return _getServerMetricsConfigDeserialize(result); + metricNamespace: string, + options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listMetricDefinitionsSend( + context, + testRunId, + metricNamespace, + options, + ); + return _listMetricDefinitionsDeserialize(result); } -export function _getTestRunSend( +export function _listMetricDimensionValuesSend( context: Client, testRunId: string, - options: GetTestRunOptionalParams = { requestOptions: {} }, + name: string, + metricname: string, + metricNamespace: string, + timespan: string, + options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}", testRunId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path( + "/test-runs/{testRunId}/metric-dimensions/{name}/values", + testRunId, + name, + ) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + metricname: metricname, + interval: options?.interval, + metricNamespace: metricNamespace, + timespan: timespan, + }, + }); } -export async function _getTestRunDeserialize( +export async function _listMetricDimensionValuesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return testRunDeserializer(result.body); + return dimensionValueListDeserializer(result.body); } -/** Get test run details by test run Id. */ -export async function getTestRun( +/** List the dimension values for the given metric dimension name. */ +export async function listMetricDimensionValues( context: Client, testRunId: string, - options: GetTestRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getTestRunSend(context, testRunId, options); - return _getTestRunDeserialize(result); + name: string, + metricname: string, + metricNamespace: string, + timespan: string, + options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listMetricDimensionValuesSend( + context, + testRunId, + name, + metricname, + metricNamespace, + timespan, + options, + ); + return _listMetricDimensionValuesDeserialize(result); } export function _getTestRunFileSend( @@ -323,7 +372,14 @@ export function _getTestRunFileSend( ): StreamableMethod { return context .path("/test-runs/{testRunId}/files/{fileName}", testRunId, fileName) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _getTestRunFileDeserialize( @@ -353,258 +409,286 @@ export async function getTestRunFile( return _getTestRunFileDeserialize(result); } -export function _listMetricDimensionValuesSend( +export function _getTestRunSend( + context: Client, + testRunId: string, + options: GetTestRunOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/test-runs/{testRunId}", testRunId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); +} + +export async function _getTestRunDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return testRunDeserializer(result.body); +} + +/** Get test run details by test run Id. */ +export async function getTestRun( + context: Client, + testRunId: string, + options: GetTestRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getTestRunSend(context, testRunId, options); + return _getTestRunDeserialize(result); +} + +export function _getServerMetricsConfigSend( context: Client, testRunId: string, - name: string, - metricname: string, - metricNamespace: string, - timespan: string, - options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, + options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/test-runs/{testRunId}/metric-dimensions/{name}/values", - testRunId, - name, - ) + .path("/test-runs/{testRunId}/server-metrics-config", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { - metricname: metricname, - interval: options?.interval, - metricNamespace: metricNamespace, - timespan: timespan, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _listMetricDimensionValuesDeserialize( +export async function _getServerMetricsConfigDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return dimensionValueListDeserializer(result.body); + return testRunServerMetricConfigDeserializer(result.body); } -/** List the dimension values for the given metric dimension name. */ -export async function listMetricDimensionValues( +/** Get associated server metrics configuration for the given test run. */ +export async function getServerMetricsConfig( context: Client, testRunId: string, - name: string, - metricname: string, - metricNamespace: string, - timespan: string, - options: ListMetricDimensionValuesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listMetricDimensionValuesSend( - context, - testRunId, - name, - metricname, - metricNamespace, - timespan, - options, - ); - return _listMetricDimensionValuesDeserialize(result); + options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getServerMetricsConfigSend(context, testRunId, options); + return _getServerMetricsConfigDeserialize(result); } -export function _listMetricDefinitionsSend( +export function _getAppComponentsSend( context: Client, testRunId: string, - metricNamespace: string, - options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, + options: GetAppComponentsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/metric-definitions", testRunId) + .path("/test-runs/{testRunId}/app-components", testRunId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { metricNamespace: metricNamespace }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _listMetricDefinitionsDeserialize( +export async function _getAppComponentsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return metricDefinitionCollectionDeserializer(result.body); + return testRunAppComponentsDeserializer(result.body); } -/** List the metric definitions for a load test run. */ -export async function listMetricDefinitions( +/** + * Get associated app component (collection of azure resources) for the given test + * run. + */ +export async function getAppComponents( context: Client, testRunId: string, - metricNamespace: string, - options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listMetricDefinitionsSend( - context, - testRunId, - metricNamespace, - options, - ); - return _listMetricDefinitionsDeserialize(result); + options: GetAppComponentsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getAppComponentsSend(context, testRunId, options); + return _getAppComponentsDeserialize(result); } -export function _listMetricNamespacesSend( +export function _deleteTestRunSend( context: Client, testRunId: string, - options: ListMetricNamespacesOptionalParams = { requestOptions: {} }, + options: DeleteTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/metric-namespaces", testRunId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/test-runs/{testRunId}", testRunId) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } -export async function _listMetricNamespacesDeserialize( +export async function _deleteTestRunDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return metricNamespaceCollectionDeserializer(result.body); + return; } -/** List the metric namespaces for a load test run. */ -export async function listMetricNamespaces( +/** Delete an existing load test run by providing the testRunId. */ +export async function deleteTestRun( context: Client, testRunId: string, - options: ListMetricNamespacesOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listMetricNamespacesSend(context, testRunId, options); - return _listMetricNamespacesDeserialize(result); + options: DeleteTestRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTestRunSend(context, testRunId, options); + return _deleteTestRunDeserialize(result); } -export function _listMetricsSend( +export function _createOrUpdateServerMetricsConfigSend( context: Client, testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - options: ListMetricsOptionalParams = { requestOptions: {} }, + body: TestRunServerMetricConfig, + options: CreateOrUpdateServerMetricsConfigOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}/metrics", testRunId) - .post({ + .path("/test-runs/{testRunId}/server-metrics-config", testRunId) + .patch({ ...operationOptionsToRequestParameters(options), - queryParameters: { - aggregation: options?.aggregation, - metricname: metricname, - interval: options?.interval, - metricNamespace: metricNamespace, - timespan: timespan, + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, - body: !options["body"] - ? options["body"] - : metricRequestPayloadSerializer(options["body"]), + queryParameters: { "api-version": context.apiVersion }, + body: testRunServerMetricConfigSerializer(body), }); } -export async function _listMetricsDeserialize( +export async function _createOrUpdateServerMetricsConfigDeserialize( result: PathUncheckedResponse, -): Promise<_Metrics> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _metricsDeserializer(result.body); + return testRunServerMetricConfigDeserializer(result.body); } -/** List the metric values for a load test run. */ -export function listMetrics( +/** Configure server metrics for a test run */ +export async function createOrUpdateServerMetricsConfig( context: Client, testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - options: ListMetricsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + body: TestRunServerMetricConfig, + options: CreateOrUpdateServerMetricsConfigOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _createOrUpdateServerMetricsConfigSend( context, - () => - _listMetricsSend( - context, - testRunId, - metricname, - metricNamespace, - timespan, - options, - ), - _listMetricsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + testRunId, + body, + options, ); + return _createOrUpdateServerMetricsConfigDeserialize(result); } -export function _listTestRunsSend( +export function _createOrUpdateAppComponentsSend( context: Client, - options: ListTestRunsOptionalParams = { requestOptions: {} }, + testRunId: string, + body: TestRunAppComponents, + options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs") - .get({ + .path("/test-runs/{testRunId}/app-components", testRunId) + .patch({ ...operationOptionsToRequestParameters(options), - queryParameters: { - orderby: options?.orderby, - search: options?.search, - testId: options?.testId, - executionFrom: options?.executionFrom?.toISOString(), - executionTo: options?.executionTo?.toISOString(), - status: options?.status, - maxpagesize: options?.maxpagesize, + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, + body: testRunAppComponentsSerializer(body), }); } -export async function _listTestRunsDeserialize( +export async function _createOrUpdateAppComponentsDeserialize( result: PathUncheckedResponse, -): Promise<_PagedTestRun> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedTestRunDeserializer(result.body); + return testRunAppComponentsDeserializer(result.body); } -/** Get all test runs for the given filters. */ -export function listTestRuns( +/** Add an app component to a test run by providing the resource Id, name and type. */ +export async function createOrUpdateAppComponents( context: Client, - options: ListTestRunsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + testRunId: string, + body: TestRunAppComponents, + options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createOrUpdateAppComponentsSend( context, - () => _listTestRunsSend(context, options), - _listTestRunsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + testRunId, + body, + options, ); + return _createOrUpdateAppComponentsDeserialize(result); } -export function _stopTestRunSend( +export function _createOrUpdateTestRunSend( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-runs/{testRunId}:stop", testRunId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/test-runs/{testRunId}", testRunId) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + oldTestRunId: options?.oldTestRunId, + }, + body: testRunSerializer(body), + }); } -export async function _stopTestRunDeserialize( +export async function _createOrUpdateTestRunDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -612,12 +696,18 @@ export async function _stopTestRunDeserialize( return testRunDeserializer(result.body); } -/** Stop test run by test run Id. */ -export async function stopTestRun( +/** Create and start a new test run with the given test run Id. */ +export async function createOrUpdateTestRun( context: Client, testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopTestRunSend(context, testRunId, options); - return _stopTestRunDeserialize(result); + const result = await _createOrUpdateTestRunSend( + context, + testRunId, + body, + options, + ); + return _createOrUpdateTestRunDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts index 994804cd76..9813190065 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/options.ts @@ -1,99 +1,91 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { OperationOptions } from "@azure-rest/core-client"; import { TimeGrain, MetricRequestPayload } from "../../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { - /** This request has a JSON Merge Patch body. */ - contentType?: string; +export interface StopTestRunOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface ListTestRunsOptionalParams extends OperationOptions { /** - * Existing test run identifier that should be rerun, if this is provided, the - * test will run with the JMX file, configuration and app components from the - * existing test run. You can override the configuration values for new test run - * in the request body. + * Sort on the supported fields in (field asc/desc) format. eg: executedDateTime + * asc. Supported fields - executedDateTime */ - oldTestRunId?: string; + orderby?: string; + /** + * Prefix based, case sensitive search on searchable fields - description, + * executedUser. For example, to search for a test run, with description 500 VUs, + * the search parameter can be 500. + */ + search?: string; + /** Unique name of an existing load test. */ + testId?: string; + /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionFrom?: Date; + /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ + executionTo?: Date; + /** Comma separated list of test run status. */ + status?: string; + /** Number of results in response. */ + maxpagesize?: number; } /** Optional parameters. */ -export interface CreateOrUpdateAppComponentsOptionalParams - extends OperationOptions { - /** Content type. */ - contentType?: string; +export interface ListMetricsOptionalParams extends OperationOptions { + /** The aggregation */ + aggregation?: string; + /** The interval (i.e. timegrain) of the query. */ + interval?: TimeGrain; + /** Metric dimension filter */ + body?: MetricRequestPayload; } /** Optional parameters. */ -export interface CreateOrUpdateServerMetricsConfigOptionalParams - extends OperationOptions { - /** Content type. */ - contentType?: string; -} +export interface ListMetricNamespacesOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface DeleteTestRunOptionalParams extends OperationOptions {} +export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetAppComponentsOptionalParams extends OperationOptions {} +export interface ListMetricDimensionValuesOptionalParams + extends OperationOptions { + /** The interval (i.e. timegrain) of the query. */ + interval?: TimeGrain; +} /** Optional parameters. */ -export interface GetServerMetricsConfigOptionalParams - extends OperationOptions {} +export interface GetTestRunFileOptionalParams extends OperationOptions {} /** Optional parameters. */ export interface GetTestRunOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetTestRunFileOptionalParams extends OperationOptions {} +export interface GetServerMetricsConfigOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ListMetricDimensionValuesOptionalParams - extends OperationOptions { - /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; -} +export interface GetAppComponentsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ListMetricDefinitionsOptionalParams extends OperationOptions {} +export interface DeleteTestRunOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ListMetricNamespacesOptionalParams extends OperationOptions {} +export interface CreateOrUpdateServerMetricsConfigOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ListMetricsOptionalParams extends OperationOptions { - /** The aggregation */ - aggregation?: string; - /** The interval (i.e. timegrain) of the query. */ - interval?: TimeGrain; - /** Metric dimension filter */ - body?: MetricRequestPayload; -} +export interface CreateOrUpdateAppComponentsOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ListTestRunsOptionalParams extends OperationOptions { - /** - * Sort on the supported fields in (field asc/desc) format. eg: executedDateTime - * asc. Supported fields - executedDateTime - */ - orderby?: string; +export interface CreateOrUpdateTestRunOptionalParams extends OperationOptions { /** - * Prefix based, case sensitive search on searchable fields - description, - * executedUser. For example, to search for a test run, with description 500 VUs, - * the search parameter can be 500. + * Existing test run identifier that should be rerun, if this is provided, the + * test will run with the JMX file, configuration and app components from the + * existing test run. You can override the configuration values for new test run + * in the request body. */ - search?: string; - /** Unique name of an existing load test. */ - testId?: string; - /** Start DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionFrom?: Date; - /** End DateTime(RFC 3339 literal format) of test-run execution time filter range. */ - executionTo?: Date; - /** Comma separated list of test run status. */ - status?: string; - /** Number of results in response. */ - maxpagesize?: number; + oldTestRunId?: string; } - -/** Optional parameters. */ -export interface StopTestRunOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts index 3cbd04210a..baf81b8d23 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/index.ts @@ -5,18 +5,18 @@ export { LoadTestRunClient } from "./loadTestRunClient.js"; export { LoadTestRunContext, LoadTestRunClientOptionalParams, - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, StopTestRunOptionalParams, + ListTestRunsOptionalParams, + ListMetricsOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricDimensionValuesOptionalParams, + GetTestRunFileOptionalParams, + GetTestRunOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + DeleteTestRunOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestRunOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts index 085f3cce1a..3b191868a6 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/loadTestRunClient.ts @@ -5,34 +5,34 @@ import { createLoadTestRun, LoadTestRunContext, LoadTestRunClientOptionalParams, - createOrUpdateTestRun, - createOrUpdateAppComponents, - createOrUpdateServerMetricsConfig, - deleteTestRun, - getAppComponents, - getServerMetricsConfig, - getTestRun, - getTestRunFile, - listMetricDimensionValues, - listMetricDefinitions, - listMetricNamespaces, - listMetrics, - listTestRuns, stopTestRun, - CreateOrUpdateTestRunOptionalParams, - CreateOrUpdateAppComponentsOptionalParams, - CreateOrUpdateServerMetricsConfigOptionalParams, - DeleteTestRunOptionalParams, - GetAppComponentsOptionalParams, - GetServerMetricsConfigOptionalParams, - GetTestRunOptionalParams, - GetTestRunFileOptionalParams, - ListMetricDimensionValuesOptionalParams, - ListMetricDefinitionsOptionalParams, - ListMetricNamespacesOptionalParams, - ListMetricsOptionalParams, - ListTestRunsOptionalParams, + listTestRuns, + listMetrics, + listMetricNamespaces, + listMetricDefinitions, + listMetricDimensionValues, + getTestRunFile, + getTestRun, + getServerMetricsConfig, + getAppComponents, + deleteTestRun, + createOrUpdateServerMetricsConfig, + createOrUpdateAppComponents, + createOrUpdateTestRun, StopTestRunOptionalParams, + ListTestRunsOptionalParams, + ListMetricsOptionalParams, + ListMetricNamespacesOptionalParams, + ListMetricDefinitionsOptionalParams, + ListMetricDimensionValuesOptionalParams, + GetTestRunFileOptionalParams, + GetTestRunOptionalParams, + GetServerMetricsConfigOptionalParams, + GetAppComponentsOptionalParams, + DeleteTestRunOptionalParams, + CreateOrUpdateServerMetricsConfigOptionalParams, + CreateOrUpdateAppComponentsOptionalParams, + CreateOrUpdateTestRunOptionalParams, } from "./api/index.js"; import { TestRun, @@ -71,82 +71,59 @@ export class LoadTestRunClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test run with the given test run Id. */ - createOrUpdateTestRun( + /** Stop test run by test run Id. */ + stopTestRun( testRunId: string, - body: TestRun, - options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, + options: StopTestRunOptionalParams = { requestOptions: {} }, ): Promise { - return createOrUpdateTestRun(this._client, testRunId, body, options); + return stopTestRun(this._client, testRunId, options); } - /** Add an app component to a test run by providing the resource Id, name and type. */ - createOrUpdateAppComponents( - testRunId: string, - body: TestRunAppComponents, - options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, - ): Promise { - return createOrUpdateAppComponents(this._client, testRunId, body, options); + /** Get all test runs for the given filters. */ + listTestRuns( + options: ListTestRunsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTestRuns(this._client, options); } - /** Configure server metrics for a test run */ - createOrUpdateServerMetricsConfig( + /** List the metric values for a load test run. */ + listMetrics( testRunId: string, - body: TestRunServerMetricConfig, - options: CreateOrUpdateServerMetricsConfigOptionalParams = { - requestOptions: {}, - }, - ): Promise { - return createOrUpdateServerMetricsConfig( + metricname: string, + metricNamespace: string, + timespan: string, + options: ListMetricsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listMetrics( this._client, testRunId, - body, + metricname, + metricNamespace, + timespan, options, ); } - /** Delete an existing load test run by providing the testRunId. */ - deleteTestRun( - testRunId: string, - options: DeleteTestRunOptionalParams = { requestOptions: {} }, - ): Promise { - return deleteTestRun(this._client, testRunId, options); - } - - /** - * Get associated app component (collection of azure resources) for the given test - * run. - */ - getAppComponents( - testRunId: string, - options: GetAppComponentsOptionalParams = { requestOptions: {} }, - ): Promise { - return getAppComponents(this._client, testRunId, options); - } - - /** Get associated server metrics configuration for the given test run. */ - getServerMetricsConfig( - testRunId: string, - options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, - ): Promise { - return getServerMetricsConfig(this._client, testRunId, options); - } - - /** Get test run details by test run Id. */ - getTestRun( + /** List the metric namespaces for a load test run. */ + listMetricNamespaces( testRunId: string, - options: GetTestRunOptionalParams = { requestOptions: {} }, - ): Promise { - return getTestRun(this._client, testRunId, options); + options: ListMetricNamespacesOptionalParams = { requestOptions: {} }, + ): Promise { + return listMetricNamespaces(this._client, testRunId, options); } - /** Get test run file by file name. */ - getTestRunFile( + /** List the metric definitions for a load test run. */ + listMetricDefinitions( testRunId: string, - fileName: string, - options: GetTestRunFileOptionalParams = { requestOptions: {} }, - ): Promise { - return getTestRunFile(this._client, testRunId, fileName, options); + metricNamespace: string, + options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, + ): Promise { + return listMetricDefinitions( + this._client, + testRunId, + metricNamespace, + options, + ); } /** List the dimension values for the given metric dimension name. */ @@ -169,58 +146,81 @@ export class LoadTestRunClient { ); } - /** List the metric definitions for a load test run. */ - listMetricDefinitions( + /** Get test run file by file name. */ + getTestRunFile( testRunId: string, - metricNamespace: string, - options: ListMetricDefinitionsOptionalParams = { requestOptions: {} }, - ): Promise { - return listMetricDefinitions( - this._client, - testRunId, - metricNamespace, - options, - ); + fileName: string, + options: GetTestRunFileOptionalParams = { requestOptions: {} }, + ): Promise { + return getTestRunFile(this._client, testRunId, fileName, options); } - /** List the metric namespaces for a load test run. */ - listMetricNamespaces( + /** Get test run details by test run Id. */ + getTestRun( testRunId: string, - options: ListMetricNamespacesOptionalParams = { requestOptions: {} }, - ): Promise { - return listMetricNamespaces(this._client, testRunId, options); + options: GetTestRunOptionalParams = { requestOptions: {} }, + ): Promise { + return getTestRun(this._client, testRunId, options); } - /** List the metric values for a load test run. */ - listMetrics( + /** Get associated server metrics configuration for the given test run. */ + getServerMetricsConfig( testRunId: string, - metricname: string, - metricNamespace: string, - timespan: string, - options: ListMetricsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listMetrics( + options: GetServerMetricsConfigOptionalParams = { requestOptions: {} }, + ): Promise { + return getServerMetricsConfig(this._client, testRunId, options); + } + + /** + * Get associated app component (collection of azure resources) for the given test + * run. + */ + getAppComponents( + testRunId: string, + options: GetAppComponentsOptionalParams = { requestOptions: {} }, + ): Promise { + return getAppComponents(this._client, testRunId, options); + } + + /** Delete an existing load test run by providing the testRunId. */ + deleteTestRun( + testRunId: string, + options: DeleteTestRunOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteTestRun(this._client, testRunId, options); + } + + /** Configure server metrics for a test run */ + createOrUpdateServerMetricsConfig( + testRunId: string, + body: TestRunServerMetricConfig, + options: CreateOrUpdateServerMetricsConfigOptionalParams = { + requestOptions: {}, + }, + ): Promise { + return createOrUpdateServerMetricsConfig( this._client, testRunId, - metricname, - metricNamespace, - timespan, + body, options, ); } - /** Get all test runs for the given filters. */ - listTestRuns( - options: ListTestRunsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTestRuns(this._client, options); + /** Add an app component to a test run by providing the resource Id, name and type. */ + createOrUpdateAppComponents( + testRunId: string, + body: TestRunAppComponents, + options: CreateOrUpdateAppComponentsOptionalParams = { requestOptions: {} }, + ): Promise { + return createOrUpdateAppComponents(this._client, testRunId, body, options); } - /** Stop test run by test run Id. */ - stopTestRun( + /** Create and start a new test run with the given test run Id. */ + createOrUpdateTestRun( testRunId: string, - options: StopTestRunOptionalParams = { requestOptions: {} }, + body: TestRun, + options: CreateOrUpdateTestRunOptionalParams = { requestOptions: {} }, ): Promise { - return stopTestRun(this._client, testRunId, options); + return createOrUpdateTestRun(this._client, testRunId, body, options); } } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts index 3c55ffe9d3..6e3da8b933 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/index.ts @@ -2,16 +2,16 @@ // Licensed under the MIT License. export { - createOrUpdateTestProfile, - deleteTestProfile, - getTestProfile, listTestProfiles, + getTestProfile, + deleteTestProfile, + createOrUpdateTestProfile, } from "./operations.js"; export { - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, ListTestProfilesOptionalParams, + GetTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + CreateOrUpdateTestProfileOptionalParams, } from "./options.js"; export { createTestProfileAdministration, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts index 20e50d48a3..39e33a2648 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/operations.ts @@ -26,26 +26,79 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createOrUpdateTestProfileSend( +export function _listTestProfilesSend( + context: Client, + options: ListTestProfilesOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/test-profiles") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + maxpagesize: options?.maxpagesize, + lastModifiedStartTime: !options?.lastModifiedStartTime + ? options?.lastModifiedStartTime + : options?.lastModifiedStartTime.toISOString(), + lastModifiedEndTime: !options?.lastModifiedEndTime + ? options?.lastModifiedEndTime + : options?.lastModifiedEndTime.toISOString(), + testProfileIds: options?.testProfileIds, + testIds: options?.testIds, + }, + }); +} + +export async function _listTestProfilesDeserialize( + result: PathUncheckedResponse, +): Promise<_PagedTestProfile> { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return _pagedTestProfileDeserializer(result.body); +} + +/** Get all test profiles for the given filters. */ +export function listTestProfiles( + context: Client, + options: ListTestProfilesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listTestProfilesSend(context, options), + _listTestProfilesDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, + ); +} + +export function _getTestProfileSend( context: Client, testProfileId: string, - body: TestProfile, - options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, + options: GetTestProfileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/test-profiles/{testProfileId}", testProfileId) - .patch({ + .get({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testProfileSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createOrUpdateTestProfileDeserialize( +export async function _getTestProfileDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["201", "200"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -53,20 +106,14 @@ export async function _createOrUpdateTestProfileDeserialize( return testProfileDeserializer(result.body); } -/** Create a new test profile or update an existing test profile by providing the test profile Id. */ -export async function createOrUpdateTestProfile( +/** Get load test profile details by test profile Id. */ +export async function getTestProfile( context: Client, testProfileId: string, - body: TestProfile, - options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, + options: GetTestProfileOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createOrUpdateTestProfileSend( - context, - testProfileId, - body, - options, - ); - return _createOrUpdateTestProfileDeserialize(result); + const result = await _getTestProfileSend(context, testProfileId, options); + return _getTestProfileDeserialize(result); } export function _deleteTestProfileSend( @@ -76,7 +123,14 @@ export function _deleteTestProfileSend( ): StreamableMethod { return context .path("/test-profiles/{testProfileId}", testProfileId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _deleteTestProfileDeserialize( @@ -100,20 +154,30 @@ export async function deleteTestProfile( return _deleteTestProfileDeserialize(result); } -export function _getTestProfileSend( +export function _createOrUpdateTestProfileSend( context: Client, testProfileId: string, - options: GetTestProfileOptionalParams = { requestOptions: {} }, + body: TestProfile, + options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/test-profiles/{testProfileId}", testProfileId) - .get({ ...operationOptionsToRequestParameters(options) }); + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: testProfileSerializer(body), + }); } -export async function _getTestProfileDeserialize( +export async function _createOrUpdateTestProfileDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -121,55 +185,18 @@ export async function _getTestProfileDeserialize( return testProfileDeserializer(result.body); } -/** Get load test profile details by test profile Id. */ -export async function getTestProfile( +/** Create a new test profile or update an existing test profile by providing the test profile Id. */ +export async function createOrUpdateTestProfile( context: Client, testProfileId: string, - options: GetTestProfileOptionalParams = { requestOptions: {} }, + body: TestProfile, + options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _getTestProfileSend(context, testProfileId, options); - return _getTestProfileDeserialize(result); -} - -export function _listTestProfilesSend( - context: Client, - options: ListTestProfilesOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/test-profiles") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxpagesize: options?.maxpagesize, - lastModifiedStartTime: options?.lastModifiedStartTime?.toISOString(), - lastModifiedEndTime: options?.lastModifiedEndTime?.toISOString(), - testProfileIds: options?.testProfileIds, - testIds: options?.testIds, - }, - }); -} - -export async function _listTestProfilesDeserialize( - result: PathUncheckedResponse, -): Promise<_PagedTestProfile> { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return _pagedTestProfileDeserializer(result.body); -} - -/** Get all test profiles for the given filters. */ -export function listTestProfiles( - context: Client, - options: ListTestProfilesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + const result = await _createOrUpdateTestProfileSend( context, - () => _listTestProfilesSend(context, options), - _listTestProfilesDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + testProfileId, + body, + options, ); + return _createOrUpdateTestProfileDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/options.ts index 7f021b292d..554ca8cbf6 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/options.ts @@ -3,19 +3,6 @@ import { OperationOptions } from "@azure-rest/core-client"; -/** Optional parameters. */ -export interface CreateOrUpdateTestProfileOptionalParams - extends OperationOptions { - /** This request has a JSON Merge Patch body. */ - contentType?: string; -} - -/** Optional parameters. */ -export interface DeleteTestProfileOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetTestProfileOptionalParams extends OperationOptions {} - /** Optional parameters. */ export interface ListTestProfilesOptionalParams extends OperationOptions { /** Maximum number of results to include in a single response. */ @@ -29,3 +16,13 @@ export interface ListTestProfilesOptionalParams extends OperationOptions { /** Comma separated list IDs of the tests which should be associated with the test profiles to fetch. */ testIds?: string; } + +/** Optional parameters. */ +export interface GetTestProfileOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface DeleteTestProfileOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface CreateOrUpdateTestProfileOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts index e2920aa082..772f92223e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/api/testProfileAdministrationContext.ts @@ -6,7 +6,11 @@ import { KnownAPIVersions } from "../../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface TestProfileAdministrationContext extends Client {} +export interface TestProfileAdministrationContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownAPIVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface TestProfileAdministrationClientOptionalParams @@ -56,5 +60,5 @@ export function createTestProfileAdministration( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as TestProfileAdministrationContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts index 9cd5d80591..3f4c23cc35 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/index.ts @@ -3,10 +3,10 @@ export { TestProfileAdministrationClient } from "./testProfileAdministrationClient.js"; export { - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, ListTestProfilesOptionalParams, + GetTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + CreateOrUpdateTestProfileOptionalParams, TestProfileAdministrationContext, TestProfileAdministrationClientOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts index 61f820586e..9db474f98a 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileAdministration/testProfileAdministrationClient.ts @@ -2,14 +2,14 @@ // Licensed under the MIT License. import { - createOrUpdateTestProfile, - deleteTestProfile, - getTestProfile, listTestProfiles, - CreateOrUpdateTestProfileOptionalParams, - DeleteTestProfileOptionalParams, - GetTestProfileOptionalParams, + getTestProfile, + deleteTestProfile, + createOrUpdateTestProfile, ListTestProfilesOptionalParams, + GetTestProfileOptionalParams, + DeleteTestProfileOptionalParams, + CreateOrUpdateTestProfileOptionalParams, createTestProfileAdministration, TestProfileAdministrationContext, TestProfileAdministrationClientOptionalParams, @@ -42,18 +42,19 @@ export class TestProfileAdministrationClient { this.pipeline = this._client.pipeline; } - /** Create a new test profile or update an existing test profile by providing the test profile Id. */ - createOrUpdateTestProfile( + /** Get all test profiles for the given filters. */ + listTestProfiles( + options: ListTestProfilesOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTestProfiles(this._client, options); + } + + /** Get load test profile details by test profile Id. */ + getTestProfile( testProfileId: string, - body: TestProfile, - options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, + options: GetTestProfileOptionalParams = { requestOptions: {} }, ): Promise { - return createOrUpdateTestProfile( - this._client, - testProfileId, - body, - options, - ); + return getTestProfile(this._client, testProfileId, options); } /** Delete a test profile by its test profile Id. */ @@ -64,18 +65,17 @@ export class TestProfileAdministrationClient { return deleteTestProfile(this._client, testProfileId, options); } - /** Get load test profile details by test profile Id. */ - getTestProfile( + /** Create a new test profile or update an existing test profile by providing the test profile Id. */ + createOrUpdateTestProfile( testProfileId: string, - options: GetTestProfileOptionalParams = { requestOptions: {} }, + body: TestProfile, + options: CreateOrUpdateTestProfileOptionalParams = { requestOptions: {} }, ): Promise { - return getTestProfile(this._client, testProfileId, options); - } - - /** Get all test profiles for the given filters. */ - listTestProfiles( - options: ListTestProfilesOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTestProfiles(this._client, options); + return createOrUpdateTestProfile( + this._client, + testProfileId, + body, + options, + ); } } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts index 4f3d1b732f..850cb1c092 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/index.ts @@ -2,18 +2,18 @@ // Licensed under the MIT License. export { - createOrUpdateTestProfileRun, - deleteTestProfileRun, - getTestProfileRun, - listTestProfileRuns, stopTestProfileRun, + listTestProfileRuns, + getTestProfileRun, + deleteTestProfileRun, + createOrUpdateTestProfileRun, } from "./operations.js"; export { - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, StopTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + GetTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + CreateOrUpdateTestProfileRunOptionalParams, } from "./options.js"; export { createTestProfileRun, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts index 865818a82f..b3a813750e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/operations.ts @@ -27,26 +27,27 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createOrUpdateTestProfileRunSend( +export function _stopTestProfileRunSend( context: Client, testProfileRunId: string, - body: TestProfileRun, - options: CreateOrUpdateTestProfileRunOptionalParams = { requestOptions: {} }, + options: StopTestProfileRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) - .patch({ + .path("/test-profile-runs/{testProfileRunId}:stop", testProfileRunId) + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: testProfileRunSerializer(body), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _createOrUpdateTestProfileRunDeserialize( +export async function _stopTestProfileRunDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["201", "200"]; + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -54,55 +55,83 @@ export async function _createOrUpdateTestProfileRunDeserialize( return testProfileRunDeserializer(result.body); } -/** Create and start a new test profile run with the given test profile run Id. */ -export async function createOrUpdateTestProfileRun( +/** Stop test profile run for the given test profile run Id. */ +export async function stopTestProfileRun( context: Client, testProfileRunId: string, - body: TestProfileRun, - options: CreateOrUpdateTestProfileRunOptionalParams = { requestOptions: {} }, + options: StopTestProfileRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createOrUpdateTestProfileRunSend( + const result = await _stopTestProfileRunSend( context, testProfileRunId, - body, options, ); - return _createOrUpdateTestProfileRunDeserialize(result); + return _stopTestProfileRunDeserialize(result); } -export function _deleteTestProfileRunSend( +export function _listTestProfileRunsSend( context: Client, - testProfileRunId: string, - options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, + options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/test-profile-runs") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { + "api-version": context.apiVersion, + maxpagesize: options?.maxpagesize, + minStartDateTime: !options?.minStartDateTime + ? options?.minStartDateTime + : options?.minStartDateTime.toISOString(), + maxStartDateTime: !options?.maxStartDateTime + ? options?.maxStartDateTime + : options?.maxStartDateTime.toISOString(), + minEndDateTime: !options?.minEndDateTime + ? options?.minEndDateTime + : options?.minEndDateTime.toISOString(), + maxEndDateTime: !options?.maxEndDateTime + ? options?.maxEndDateTime + : options?.maxEndDateTime.toISOString(), + createdDateStartTime: !options?.createdDateStartTime + ? options?.createdDateStartTime + : options?.createdDateStartTime.toISOString(), + createdDateEndTime: !options?.createdDateEndTime + ? options?.createdDateEndTime + : options?.createdDateEndTime.toISOString(), + testProfileRunIds: options?.testProfileRunIds, + testProfileIds: options?.testProfileIds, + statuses: options?.statuses, + }, + }); } -export async function _deleteTestProfileRunDeserialize( +export async function _listTestProfileRunsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise<_PagedTestProfileRun> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return _pagedTestProfileRunDeserializer(result.body); } -/** Delete an existing load test profile run by providing the test profile run Id. */ -export async function deleteTestProfileRun( +/** Get all test profile runs for the given filters. */ +export function listTestProfileRuns( context: Client, - testProfileRunId: string, - options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteTestProfileRunSend( + options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - testProfileRunId, - options, + () => _listTestProfileRunsSend(context, options), + _listTestProfileRunsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _deleteTestProfileRunDeserialize(result); } export function _getTestProfileRunSend( @@ -112,7 +141,14 @@ export function _getTestProfileRunSend( ): StreamableMethod { return context .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _getTestProfileRunDeserialize( @@ -140,68 +176,72 @@ export async function getTestProfileRun( return _getTestProfileRunDeserialize(result); } -export function _listTestProfileRunsSend( +export function _deleteTestProfileRunSend( context: Client, - options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, + testProfileRunId: string, + options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-profile-runs") - .get({ + .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) + .delete({ ...operationOptionsToRequestParameters(options), - queryParameters: { - maxpagesize: options?.maxpagesize, - minStartDateTime: options?.minStartDateTime?.toISOString(), - maxStartDateTime: options?.maxStartDateTime?.toISOString(), - minEndDateTime: options?.minEndDateTime?.toISOString(), - maxEndDateTime: options?.maxEndDateTime?.toISOString(), - createdDateStartTime: options?.createdDateStartTime?.toISOString(), - createdDateEndTime: options?.createdDateEndTime?.toISOString(), - testProfileRunIds: options?.testProfileRunIds, - testProfileIds: options?.testProfileIds, - statuses: options?.statuses, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _listTestProfileRunsDeserialize( +export async function _deleteTestProfileRunDeserialize( result: PathUncheckedResponse, -): Promise<_PagedTestProfileRun> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedTestProfileRunDeserializer(result.body); + return; } -/** Get all test profile runs for the given filters. */ -export function listTestProfileRuns( +/** Delete an existing load test profile run by providing the test profile run Id. */ +export async function deleteTestProfileRun( context: Client, - options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( + testProfileRunId: string, + options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteTestProfileRunSend( context, - () => _listTestProfileRunsSend(context, options), - _listTestProfileRunsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + testProfileRunId, + options, ); + return _deleteTestProfileRunDeserialize(result); } -export function _stopTestProfileRunSend( +export function _createOrUpdateTestProfileRunSend( context: Client, testProfileRunId: string, - options: StopTestProfileRunOptionalParams = { requestOptions: {} }, + body: TestProfileRun, + options: CreateOrUpdateTestProfileRunOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test-profile-runs/{testProfileRunId}:stop", testProfileRunId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/test-profile-runs/{testProfileRunId}", testProfileRunId) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: testProfileRunSerializer(body), + }); } -export async function _stopTestProfileRunDeserialize( +export async function _createOrUpdateTestProfileRunDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200"]; + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -209,16 +249,18 @@ export async function _stopTestProfileRunDeserialize( return testProfileRunDeserializer(result.body); } -/** Stop test profile run for the given test profile run Id. */ -export async function stopTestProfileRun( +/** Create and start a new test profile run with the given test profile run Id. */ +export async function createOrUpdateTestProfileRun( context: Client, testProfileRunId: string, - options: StopTestProfileRunOptionalParams = { requestOptions: {} }, + body: TestProfileRun, + options: CreateOrUpdateTestProfileRunOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _stopTestProfileRunSend( + const result = await _createOrUpdateTestProfileRunSend( context, testProfileRunId, + body, options, ); - return _stopTestProfileRunDeserialize(result); + return _createOrUpdateTestProfileRunDeserialize(result); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/options.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/options.ts index 1a73b36436..b0c48446f5 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/options.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/options.ts @@ -4,17 +4,7 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface CreateOrUpdateTestProfileRunOptionalParams - extends OperationOptions { - /** This request has a JSON Merge Patch body. */ - contentType?: string; -} - -/** Optional parameters. */ -export interface DeleteTestProfileRunOptionalParams extends OperationOptions {} - -/** Optional parameters. */ -export interface GetTestProfileRunOptionalParams extends OperationOptions {} +export interface StopTestProfileRunOptionalParams extends OperationOptions {} /** Optional parameters. */ export interface ListTestProfileRunsOptionalParams extends OperationOptions { @@ -41,4 +31,11 @@ export interface ListTestProfileRunsOptionalParams extends OperationOptions { } /** Optional parameters. */ -export interface StopTestProfileRunOptionalParams extends OperationOptions {} +export interface GetTestProfileRunOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface DeleteTestProfileRunOptionalParams extends OperationOptions {} + +/** Optional parameters. */ +export interface CreateOrUpdateTestProfileRunOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts index 7cd16e05b8..80942a03d1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/api/testProfileRunContext.ts @@ -6,7 +6,11 @@ import { KnownAPIVersions } from "../../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface TestProfileRunContext extends Client {} +export interface TestProfileRunContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownAPIVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface TestProfileRunClientOptionalParams extends ClientOptions { @@ -55,5 +59,5 @@ export function createTestProfileRun( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as TestProfileRunContext; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts index 6ec95ed4ae..20c4401e86 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/index.ts @@ -3,11 +3,11 @@ export { TestProfileRunClient } from "./testProfileRunClient.js"; export { - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, StopTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + GetTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + CreateOrUpdateTestProfileRunOptionalParams, TestProfileRunContext, TestProfileRunClientOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts index 79185f89b6..b9edb097d2 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/testProfileRun/testProfileRunClient.ts @@ -2,16 +2,16 @@ // Licensed under the MIT License. import { - createOrUpdateTestProfileRun, - deleteTestProfileRun, - getTestProfileRun, - listTestProfileRuns, stopTestProfileRun, - CreateOrUpdateTestProfileRunOptionalParams, - DeleteTestProfileRunOptionalParams, - GetTestProfileRunOptionalParams, - ListTestProfileRunsOptionalParams, + listTestProfileRuns, + getTestProfileRun, + deleteTestProfileRun, + createOrUpdateTestProfileRun, StopTestProfileRunOptionalParams, + ListTestProfileRunsOptionalParams, + GetTestProfileRunOptionalParams, + DeleteTestProfileRunOptionalParams, + CreateOrUpdateTestProfileRunOptionalParams, createTestProfileRun, TestProfileRunContext, TestProfileRunClientOptionalParams, @@ -44,28 +44,19 @@ export class TestProfileRunClient { this.pipeline = this._client.pipeline; } - /** Create and start a new test profile run with the given test profile run Id. */ - createOrUpdateTestProfileRun( + /** Stop test profile run for the given test profile run Id. */ + stopTestProfileRun( testProfileRunId: string, - body: TestProfileRun, - options: CreateOrUpdateTestProfileRunOptionalParams = { - requestOptions: {}, - }, + options: StopTestProfileRunOptionalParams = { requestOptions: {} }, ): Promise { - return createOrUpdateTestProfileRun( - this._client, - testProfileRunId, - body, - options, - ); + return stopTestProfileRun(this._client, testProfileRunId, options); } - /** Delete an existing load test profile run by providing the test profile run Id. */ - deleteTestProfileRun( - testProfileRunId: string, - options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, - ): Promise { - return deleteTestProfileRun(this._client, testProfileRunId, options); + /** Get all test profile runs for the given filters. */ + listTestProfileRuns( + options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, + ): PagedAsyncIterableIterator { + return listTestProfileRuns(this._client, options); } /** Get test profile run details by test profile run Id. */ @@ -76,18 +67,27 @@ export class TestProfileRunClient { return getTestProfileRun(this._client, testProfileRunId, options); } - /** Get all test profile runs for the given filters. */ - listTestProfileRuns( - options: ListTestProfileRunsOptionalParams = { requestOptions: {} }, - ): PagedAsyncIterableIterator { - return listTestProfileRuns(this._client, options); + /** Delete an existing load test profile run by providing the test profile run Id. */ + deleteTestProfileRun( + testProfileRunId: string, + options: DeleteTestProfileRunOptionalParams = { requestOptions: {} }, + ): Promise { + return deleteTestProfileRun(this._client, testProfileRunId, options); } - /** Stop test profile run for the given test profile run Id. */ - stopTestProfileRun( + /** Create and start a new test profile run with the given test profile run Id. */ + createOrUpdateTestProfileRun( testProfileRunId: string, - options: StopTestProfileRunOptionalParams = { requestOptions: {} }, + body: TestProfileRun, + options: CreateOrUpdateTestProfileRunOptionalParams = { + requestOptions: {}, + }, ): Promise { - return stopTestProfileRun(this._client, testProfileRunId, options); + return createOrUpdateTestProfileRun( + this._client, + testProfileRunId, + body, + options, + ); } } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json b/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json index 7e28d7c96a..0beb0a835e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/package.json @@ -13,18 +13,18 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/audio/transcriptions": "./src/api/audio/transcriptions/index.ts", - "./api/audio/translations": "./src/api/audio/translations/index.ts", - "./api/chat/completions": "./src/api/chat/completions/index.ts", - "./api/fineTuning/jobs": "./src/api/fineTuning/jobs/index.ts", - "./api/completions": "./src/api/completions/index.ts", - "./api/edits": "./src/api/edits/index.ts", - "./api/embeddings": "./src/api/embeddings/index.ts", - "./api/files": "./src/api/files/index.ts", - "./api/fineTunes": "./src/api/fineTunes/index.ts", - "./api/models": "./src/api/models/index.ts", + "./api/moderations": "./src/api/moderations/index.ts", "./api/images": "./src/api/images/index.ts", - "./api/moderations": "./src/api/moderations/index.ts" + "./api/models": "./src/api/models/index.ts", + "./api/fineTunes": "./src/api/fineTunes/index.ts", + "./api/files": "./src/api/files/index.ts", + "./api/embeddings": "./src/api/embeddings/index.ts", + "./api/edits": "./src/api/edits/index.ts", + "./api/completions": "./src/api/completions/index.ts", + "./api/fineTuning/jobs": "./src/api/fineTuning/jobs/index.ts", + "./api/chat/completions": "./src/api/chat/completions/index.ts", + "./api/audio/translations": "./src/api/audio/translations/index.ts", + "./api/audio/transcriptions": "./src/api/audio/transcriptions/index.ts" }, "dialects": [ "esm", @@ -152,112 +152,94 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/audio/transcriptions": { - "browser": { - "types": "./dist/browser/api/audio/transcriptions/index.d.ts", - "default": "./dist/browser/api/audio/transcriptions/index.js" - }, - "react-native": { - "types": "./dist/react-native/api/audio/transcriptions/index.d.ts", - "default": "./dist/react-native/api/audio/transcriptions/index.js" - }, - "import": { - "types": "./dist/esm/api/audio/transcriptions/index.d.ts", - "default": "./dist/esm/api/audio/transcriptions/index.js" - }, - "require": { - "types": "./dist/commonjs/api/audio/transcriptions/index.d.ts", - "default": "./dist/commonjs/api/audio/transcriptions/index.js" - } - }, - "./api/audio/translations": { + "./api/moderations": { "browser": { - "types": "./dist/browser/api/audio/translations/index.d.ts", - "default": "./dist/browser/api/audio/translations/index.js" + "types": "./dist/browser/api/moderations/index.d.ts", + "default": "./dist/browser/api/moderations/index.js" }, "react-native": { - "types": "./dist/react-native/api/audio/translations/index.d.ts", - "default": "./dist/react-native/api/audio/translations/index.js" + "types": "./dist/react-native/api/moderations/index.d.ts", + "default": "./dist/react-native/api/moderations/index.js" }, "import": { - "types": "./dist/esm/api/audio/translations/index.d.ts", - "default": "./dist/esm/api/audio/translations/index.js" + "types": "./dist/esm/api/moderations/index.d.ts", + "default": "./dist/esm/api/moderations/index.js" }, "require": { - "types": "./dist/commonjs/api/audio/translations/index.d.ts", - "default": "./dist/commonjs/api/audio/translations/index.js" + "types": "./dist/commonjs/api/moderations/index.d.ts", + "default": "./dist/commonjs/api/moderations/index.js" } }, - "./api/chat/completions": { + "./api/images": { "browser": { - "types": "./dist/browser/api/chat/completions/index.d.ts", - "default": "./dist/browser/api/chat/completions/index.js" + "types": "./dist/browser/api/images/index.d.ts", + "default": "./dist/browser/api/images/index.js" }, "react-native": { - "types": "./dist/react-native/api/chat/completions/index.d.ts", - "default": "./dist/react-native/api/chat/completions/index.js" + "types": "./dist/react-native/api/images/index.d.ts", + "default": "./dist/react-native/api/images/index.js" }, "import": { - "types": "./dist/esm/api/chat/completions/index.d.ts", - "default": "./dist/esm/api/chat/completions/index.js" + "types": "./dist/esm/api/images/index.d.ts", + "default": "./dist/esm/api/images/index.js" }, "require": { - "types": "./dist/commonjs/api/chat/completions/index.d.ts", - "default": "./dist/commonjs/api/chat/completions/index.js" + "types": "./dist/commonjs/api/images/index.d.ts", + "default": "./dist/commonjs/api/images/index.js" } }, - "./api/fineTuning/jobs": { + "./api/models": { "browser": { - "types": "./dist/browser/api/fineTuning/jobs/index.d.ts", - "default": "./dist/browser/api/fineTuning/jobs/index.js" + "types": "./dist/browser/api/models/index.d.ts", + "default": "./dist/browser/api/models/index.js" }, "react-native": { - "types": "./dist/react-native/api/fineTuning/jobs/index.d.ts", - "default": "./dist/react-native/api/fineTuning/jobs/index.js" + "types": "./dist/react-native/api/models/index.d.ts", + "default": "./dist/react-native/api/models/index.js" }, "import": { - "types": "./dist/esm/api/fineTuning/jobs/index.d.ts", - "default": "./dist/esm/api/fineTuning/jobs/index.js" + "types": "./dist/esm/api/models/index.d.ts", + "default": "./dist/esm/api/models/index.js" }, "require": { - "types": "./dist/commonjs/api/fineTuning/jobs/index.d.ts", - "default": "./dist/commonjs/api/fineTuning/jobs/index.js" + "types": "./dist/commonjs/api/models/index.d.ts", + "default": "./dist/commonjs/api/models/index.js" } }, - "./api/completions": { + "./api/fineTunes": { "browser": { - "types": "./dist/browser/api/completions/index.d.ts", - "default": "./dist/browser/api/completions/index.js" + "types": "./dist/browser/api/fineTunes/index.d.ts", + "default": "./dist/browser/api/fineTunes/index.js" }, "react-native": { - "types": "./dist/react-native/api/completions/index.d.ts", - "default": "./dist/react-native/api/completions/index.js" + "types": "./dist/react-native/api/fineTunes/index.d.ts", + "default": "./dist/react-native/api/fineTunes/index.js" }, "import": { - "types": "./dist/esm/api/completions/index.d.ts", - "default": "./dist/esm/api/completions/index.js" + "types": "./dist/esm/api/fineTunes/index.d.ts", + "default": "./dist/esm/api/fineTunes/index.js" }, "require": { - "types": "./dist/commonjs/api/completions/index.d.ts", - "default": "./dist/commonjs/api/completions/index.js" + "types": "./dist/commonjs/api/fineTunes/index.d.ts", + "default": "./dist/commonjs/api/fineTunes/index.js" } }, - "./api/edits": { + "./api/files": { "browser": { - "types": "./dist/browser/api/edits/index.d.ts", - "default": "./dist/browser/api/edits/index.js" + "types": "./dist/browser/api/files/index.d.ts", + "default": "./dist/browser/api/files/index.js" }, "react-native": { - "types": "./dist/react-native/api/edits/index.d.ts", - "default": "./dist/react-native/api/edits/index.js" + "types": "./dist/react-native/api/files/index.d.ts", + "default": "./dist/react-native/api/files/index.js" }, "import": { - "types": "./dist/esm/api/edits/index.d.ts", - "default": "./dist/esm/api/edits/index.js" + "types": "./dist/esm/api/files/index.d.ts", + "default": "./dist/esm/api/files/index.js" }, "require": { - "types": "./dist/commonjs/api/edits/index.d.ts", - "default": "./dist/commonjs/api/edits/index.js" + "types": "./dist/commonjs/api/files/index.d.ts", + "default": "./dist/commonjs/api/files/index.js" } }, "./api/embeddings": { @@ -278,94 +260,112 @@ "default": "./dist/commonjs/api/embeddings/index.js" } }, - "./api/files": { + "./api/edits": { "browser": { - "types": "./dist/browser/api/files/index.d.ts", - "default": "./dist/browser/api/files/index.js" + "types": "./dist/browser/api/edits/index.d.ts", + "default": "./dist/browser/api/edits/index.js" }, "react-native": { - "types": "./dist/react-native/api/files/index.d.ts", - "default": "./dist/react-native/api/files/index.js" + "types": "./dist/react-native/api/edits/index.d.ts", + "default": "./dist/react-native/api/edits/index.js" }, "import": { - "types": "./dist/esm/api/files/index.d.ts", - "default": "./dist/esm/api/files/index.js" + "types": "./dist/esm/api/edits/index.d.ts", + "default": "./dist/esm/api/edits/index.js" }, "require": { - "types": "./dist/commonjs/api/files/index.d.ts", - "default": "./dist/commonjs/api/files/index.js" + "types": "./dist/commonjs/api/edits/index.d.ts", + "default": "./dist/commonjs/api/edits/index.js" } }, - "./api/fineTunes": { + "./api/completions": { "browser": { - "types": "./dist/browser/api/fineTunes/index.d.ts", - "default": "./dist/browser/api/fineTunes/index.js" + "types": "./dist/browser/api/completions/index.d.ts", + "default": "./dist/browser/api/completions/index.js" }, "react-native": { - "types": "./dist/react-native/api/fineTunes/index.d.ts", - "default": "./dist/react-native/api/fineTunes/index.js" + "types": "./dist/react-native/api/completions/index.d.ts", + "default": "./dist/react-native/api/completions/index.js" }, "import": { - "types": "./dist/esm/api/fineTunes/index.d.ts", - "default": "./dist/esm/api/fineTunes/index.js" + "types": "./dist/esm/api/completions/index.d.ts", + "default": "./dist/esm/api/completions/index.js" }, "require": { - "types": "./dist/commonjs/api/fineTunes/index.d.ts", - "default": "./dist/commonjs/api/fineTunes/index.js" + "types": "./dist/commonjs/api/completions/index.d.ts", + "default": "./dist/commonjs/api/completions/index.js" } }, - "./api/models": { + "./api/fineTuning/jobs": { "browser": { - "types": "./dist/browser/api/models/index.d.ts", - "default": "./dist/browser/api/models/index.js" + "types": "./dist/browser/api/fineTuning/jobs/index.d.ts", + "default": "./dist/browser/api/fineTuning/jobs/index.js" }, "react-native": { - "types": "./dist/react-native/api/models/index.d.ts", - "default": "./dist/react-native/api/models/index.js" + "types": "./dist/react-native/api/fineTuning/jobs/index.d.ts", + "default": "./dist/react-native/api/fineTuning/jobs/index.js" }, "import": { - "types": "./dist/esm/api/models/index.d.ts", - "default": "./dist/esm/api/models/index.js" + "types": "./dist/esm/api/fineTuning/jobs/index.d.ts", + "default": "./dist/esm/api/fineTuning/jobs/index.js" }, "require": { - "types": "./dist/commonjs/api/models/index.d.ts", - "default": "./dist/commonjs/api/models/index.js" + "types": "./dist/commonjs/api/fineTuning/jobs/index.d.ts", + "default": "./dist/commonjs/api/fineTuning/jobs/index.js" } }, - "./api/images": { + "./api/chat/completions": { "browser": { - "types": "./dist/browser/api/images/index.d.ts", - "default": "./dist/browser/api/images/index.js" + "types": "./dist/browser/api/chat/completions/index.d.ts", + "default": "./dist/browser/api/chat/completions/index.js" }, "react-native": { - "types": "./dist/react-native/api/images/index.d.ts", - "default": "./dist/react-native/api/images/index.js" + "types": "./dist/react-native/api/chat/completions/index.d.ts", + "default": "./dist/react-native/api/chat/completions/index.js" }, "import": { - "types": "./dist/esm/api/images/index.d.ts", - "default": "./dist/esm/api/images/index.js" + "types": "./dist/esm/api/chat/completions/index.d.ts", + "default": "./dist/esm/api/chat/completions/index.js" }, "require": { - "types": "./dist/commonjs/api/images/index.d.ts", - "default": "./dist/commonjs/api/images/index.js" + "types": "./dist/commonjs/api/chat/completions/index.d.ts", + "default": "./dist/commonjs/api/chat/completions/index.js" } }, - "./api/moderations": { + "./api/audio/translations": { "browser": { - "types": "./dist/browser/api/moderations/index.d.ts", - "default": "./dist/browser/api/moderations/index.js" + "types": "./dist/browser/api/audio/translations/index.d.ts", + "default": "./dist/browser/api/audio/translations/index.js" }, "react-native": { - "types": "./dist/react-native/api/moderations/index.d.ts", - "default": "./dist/react-native/api/moderations/index.js" + "types": "./dist/react-native/api/audio/translations/index.d.ts", + "default": "./dist/react-native/api/audio/translations/index.js" }, "import": { - "types": "./dist/esm/api/moderations/index.d.ts", - "default": "./dist/esm/api/moderations/index.js" + "types": "./dist/esm/api/audio/translations/index.d.ts", + "default": "./dist/esm/api/audio/translations/index.js" }, "require": { - "types": "./dist/commonjs/api/moderations/index.d.ts", - "default": "./dist/commonjs/api/moderations/index.js" + "types": "./dist/commonjs/api/audio/translations/index.d.ts", + "default": "./dist/commonjs/api/audio/translations/index.js" + } + }, + "./api/audio/transcriptions": { + "browser": { + "types": "./dist/browser/api/audio/transcriptions/index.d.ts", + "default": "./dist/browser/api/audio/transcriptions/index.js" + }, + "react-native": { + "types": "./dist/react-native/api/audio/transcriptions/index.d.ts", + "default": "./dist/react-native/api/audio/transcriptions/index.js" + }, + "import": { + "types": "./dist/esm/api/audio/transcriptions/index.d.ts", + "default": "./dist/esm/api/audio/transcriptions/index.js" + }, + "require": { + "types": "./dist/commonjs/api/audio/transcriptions/index.d.ts", + "default": "./dist/commonjs/api/audio/transcriptions/index.js" } } }, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md b/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md index fc3cda6dc5..767b0f1ff3 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/review/openai-generic.api.md @@ -19,8 +19,6 @@ export interface AudioOperations { // @public export interface AudioTranscriptionsCreateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -31,8 +29,6 @@ export interface AudioTranscriptionsOperations { // @public export interface AudioTranslationsCreateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -413,8 +409,6 @@ export interface EmbeddingsOperations { // @public export interface FilesCreateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -607,8 +601,6 @@ export interface Image { // @public export interface ImagesCreateEditOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -617,8 +609,6 @@ export interface ImagesCreateOptionalParams extends OperationOptions { // @public export interface ImagesCreateVariationOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts index 26ffb3b318..4389237d2d 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/transcriptions/index.ts @@ -27,7 +27,11 @@ export function _createSend( .path("/audio/transcriptions") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createTranscriptionRequestSerializer(audio), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts index 876f9d3989..6505ddb7db 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/audio/translations/index.ts @@ -27,7 +27,11 @@ export function _createSend( .path("/audio/translations") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createTranslationRequestSerializer(audio), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts index 780f78bc69..2467b4d106 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/chat/completions/index.ts @@ -27,6 +27,11 @@ export function _createSend( .path("/chat/completions") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createChatCompletionRequestSerializer(body), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts index c30a9b41b5..5bbaa6597a 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/completions/index.ts @@ -27,6 +27,11 @@ export function _createSend( .path("/completions") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createCompletionRequestSerializer(body), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts index 5d2b38bb1e..ced0da9379 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/edits/index.ts @@ -27,6 +27,11 @@ export function _createSend( .path("/edits") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createEditRequestSerializer(edit), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts index ba2da39b80..9b00a2cf98 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/embeddings/index.ts @@ -27,6 +27,11 @@ export function _createSend( .path("/embeddings") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createEmbeddingRequestSerializer(embedding), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts index 899412257a..6edf072989 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/files/index.ts @@ -26,66 +26,81 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _listSend( +export function _downloadSend( context: Client, - options: FilesListOptionalParams = { requestOptions: {} }, + fileId: string, + options: FilesDownloadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/files/files/{file_id}/content", fileId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _listDeserialize( +export async function _downloadDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFilesResponseDeserializer(result.body); + return result.body; } -export async function list( +export async function download( context: Client, - options: FilesListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + fileId: string, + options: FilesDownloadOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _downloadSend(context, fileId, options); + return _downloadDeserialize(result); } -export function _createSend( +export function _$deleteSend( context: Client, - file: CreateFileRequest, - options: FilesCreateOptionalParams = { requestOptions: {} }, + fileId: string, + options: FilesDeleteOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files") - .post({ + .path("/files/files/{file_id}", fileId) + .delete({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: createFileRequestSerializer(file), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createDeserialize( +export async function _$deleteDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIFileDeserializer(result.body); + return deleteFileResponseDeserializer(result.body); } -export async function create( +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( context: Client, - file: CreateFileRequest, - options: FilesCreateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createSend(context, file, options); - return _createDeserialize(result); + fileId: string, + options: FilesDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend(context, fileId, options); + return _$deleteDeserialize(result); } export function _retrieveSend( @@ -95,7 +110,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/files/files/{file_id}", fileId) - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -118,67 +139,74 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _$deleteSend( +export function _createSend( context: Client, - fileId: string, - options: FilesDeleteOptionalParams = { requestOptions: {} }, + file: CreateFileRequest, + options: FilesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/files/{file_id}", fileId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/files") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createFileRequestSerializer(file), + }); } -export async function _$deleteDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return deleteFileResponseDeserializer(result.body); + return openAIFileDeserializer(result.body); } -/** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ -export async function $delete( +export async function create( context: Client, - fileId: string, - options: FilesDeleteOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _$deleteSend(context, fileId, options); - return _$deleteDeserialize(result); + file: CreateFileRequest, + options: FilesCreateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createSend(context, file, options); + return _createDeserialize(result); } -export function _downloadSend( +export function _listSend( context: Client, - fileId: string, - options: FilesDownloadOptionalParams = { requestOptions: {} }, + options: FilesListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/files/{file_id}/content", fileId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/files") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _downloadDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body; + return listFilesResponseDeserializer(result.body); } -export async function download( +export async function list( context: Client, - fileId: string, - options: FilesDownloadOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _downloadSend(context, fileId, options); - return _downloadDeserialize(result); + options: FilesListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts index aa5de3fc20..6764d79401 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTunes/index.ts @@ -26,20 +26,23 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createSend( +export function _cancelSend( context: Client, - fineTune: CreateFineTuneRequest, - options: FineTunesCreateOptionalParams = { requestOptions: {} }, + fineTuneId: string, + options: FineTunesCancelOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes") + .path("/fine-tunes/{fine_tune_id}/cancel", fineTuneId) .post({ ...operationOptionsToRequestParameters(options), - body: createFineTuneRequestSerializer(fineTune), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createDeserialize( +export async function _cancelDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -50,41 +53,50 @@ export async function _createDeserialize( return fineTuneDeserializer(result.body); } -export async function create( +export async function cancel( context: Client, - fineTune: CreateFineTuneRequest, - options: FineTunesCreateOptionalParams = { requestOptions: {} }, + fineTuneId: string, + options: FineTunesCancelOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createSend(context, fineTune, options); - return _createDeserialize(result); + const result = await _cancelSend(context, fineTuneId, options); + return _cancelDeserialize(result); } -export function _listSend( +export function _listEventsSend( context: Client, - options: FineTunesListOptionalParams = { requestOptions: {} }, + fineTuneId: string, + options: FineTunesListEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/fine-tunes/{fine_tune_id}/events", fineTuneId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { stream: options?.stream }, + }); } -export async function _listDeserialize( +export async function _listEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFineTunesResponseDeserializer(result.body); + return listFineTuneEventsResponseDeserializer(result.body); } -export async function list( +export async function listEvents( context: Client, - options: FineTunesListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + fineTuneId: string, + options: FineTunesListEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listEventsSend(context, fineTuneId, options); + return _listEventsDeserialize(result); } export function _retrieveSend( @@ -94,7 +106,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/fine-tunes/{fine_tune_id}", fineTuneId) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -117,50 +135,59 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _listEventsSend( +export function _listSend( context: Client, - fineTuneId: string, - options: FineTunesListEventsOptionalParams = { requestOptions: {} }, + options: FineTunesListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes/{fine_tune_id}/events", fineTuneId) + .path("/fine-tunes") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { stream: options?.stream }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _listEventsDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFineTuneEventsResponseDeserializer(result.body); + return listFineTunesResponseDeserializer(result.body); } -export async function listEvents( +export async function list( context: Client, - fineTuneId: string, - options: FineTunesListEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listEventsSend(context, fineTuneId, options); - return _listEventsDeserialize(result); + options: FineTunesListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } -export function _cancelSend( +export function _createSend( context: Client, - fineTuneId: string, - options: FineTunesCancelOptionalParams = { requestOptions: {} }, + fineTune: CreateFineTuneRequest, + options: FineTunesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes/{fine_tune_id}/cancel", fineTuneId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/fine-tunes") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createFineTuneRequestSerializer(fineTune), + }); } -export async function _cancelDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -171,11 +198,11 @@ export async function _cancelDeserialize( return fineTuneDeserializer(result.body); } -export async function cancel( +export async function create( context: Client, - fineTuneId: string, - options: FineTunesCancelOptionalParams = { requestOptions: {} }, + fineTune: CreateFineTuneRequest, + options: FineTunesCreateOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _cancelSend(context, fineTuneId, options); - return _cancelDeserialize(result); + const result = await _createSend(context, fineTune, options); + return _createDeserialize(result); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts index 07d9c5e064..f38bf271ac 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/fineTuning/jobs/index.ts @@ -26,20 +26,23 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createSend( +export function _cancelSend( context: Client, - job: CreateFineTuningJobRequest, - options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, + fineTuningJobId: string, + options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs") + .path("/fine_tuning/jobs/{fine_tuning_job_id}/cancel", fineTuningJobId) .post({ ...operationOptionsToRequestParameters(options), - body: createFineTuningJobRequestSerializer(job), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createDeserialize( +export async function _cancelDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -50,52 +53,50 @@ export async function _createDeserialize( return fineTuningJobDeserializer(result.body); } -/** - * Creates a job that fine-tunes a specified model from a given dataset. - * - * Response includes details of the enqueued job including job status and the name of the - * fine-tuned models once complete. - * - * [Learn more about fine-tuning](/docs/guides/fine-tuning) - */ -export async function create( +export async function cancel( context: Client, - job: CreateFineTuningJobRequest, - options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, + fineTuningJobId: string, + options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createSend(context, job, options); - return _createDeserialize(result); + const result = await _cancelSend(context, fineTuningJobId, options); + return _cancelDeserialize(result); } -export function _listSend( +export function _listEventsSend( context: Client, - options: FineTuningJobsListOptionalParams = { requestOptions: {} }, + fineTuningJobId: string, + options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs") + .path("/fine_tuning/jobs/{fine_tuning_job_id}/events", fineTuningJobId) .get({ ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { after: options?.after, limit: options?.limit }, }); } -export async function _listDeserialize( +export async function _listEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listPaginatedFineTuningJobsResponseDeserializer(result.body); + return listFineTuningJobEventsResponseDeserializer(result.body); } -export async function list( +export async function listEvents( context: Client, - options: FineTuningJobsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + fineTuningJobId: string, + options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listEventsSend(context, fineTuningJobId, options); + return _listEventsDeserialize(result); } export function _retrieveSend( @@ -105,7 +106,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/fine_tuning/jobs/{fine_tuning_job_id}", fineTuningJobId) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -128,50 +135,60 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _listEventsSend( +export function _listSend( context: Client, - fineTuningJobId: string, - options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, + options: FineTuningJobsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs/{fine_tuning_job_id}/events", fineTuningJobId) + .path("/fine_tuning/jobs") .get({ ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { after: options?.after, limit: options?.limit }, }); } -export async function _listEventsDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFineTuningJobEventsResponseDeserializer(result.body); + return listPaginatedFineTuningJobsResponseDeserializer(result.body); } -export async function listEvents( +export async function list( context: Client, - fineTuningJobId: string, - options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listEventsSend(context, fineTuningJobId, options); - return _listEventsDeserialize(result); + options: FineTuningJobsListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } -export function _cancelSend( +export function _createSend( context: Client, - fineTuningJobId: string, - options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, + job: CreateFineTuningJobRequest, + options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs/{fine_tuning_job_id}/cancel", fineTuningJobId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/fine_tuning/jobs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createFineTuningJobRequestSerializer(job), + }); } -export async function _cancelDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -182,11 +199,19 @@ export async function _cancelDeserialize( return fineTuningJobDeserializer(result.body); } -export async function cancel( +/** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ +export async function create( context: Client, - fineTuningJobId: string, - options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, + job: CreateFineTuningJobRequest, + options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _cancelSend(context, fineTuningJobId, options); - return _cancelDeserialize(result); + const result = await _createSend(context, job, options); + return _createDeserialize(result); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts index edb0ad1832..8a3d1e8f9e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/images/index.ts @@ -24,20 +24,25 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _createSend( +export function _createVariationSend( context: Client, - image: CreateImageRequest, - options: ImagesCreateOptionalParams = { requestOptions: {} }, + image: CreateImageVariationRequest, + options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/images/generations") + .path("/images/variations") .post({ ...operationOptionsToRequestParameters(options), - body: createImageRequestSerializer(image), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createImageVariationRequestSerializer(image), }); } -export async function _createDeserialize( +export async function _createVariationDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -48,13 +53,13 @@ export async function _createDeserialize( return imagesResponseDeserializer(result.body); } -export async function create( +export async function createVariation( context: Client, - image: CreateImageRequest, - options: ImagesCreateOptionalParams = { requestOptions: {} }, + image: CreateImageVariationRequest, + options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createSend(context, image, options); - return _createDeserialize(result); + const result = await _createVariationSend(context, image, options); + return _createVariationDeserialize(result); } export function _createEditSend( @@ -66,7 +71,11 @@ export function _createEditSend( .path("/images/edits") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createImageEditRequestSerializer(image), }); } @@ -91,21 +100,25 @@ export async function createEdit( return _createEditDeserialize(result); } -export function _createVariationSend( +export function _createSend( context: Client, - image: CreateImageVariationRequest, - options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, + image: CreateImageRequest, + options: ImagesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/images/variations") + .path("/images/generations") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: createImageVariationRequestSerializer(image), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createImageRequestSerializer(image), }); } -export async function _createVariationDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -116,11 +129,11 @@ export async function _createVariationDeserialize( return imagesResponseDeserializer(result.body); } -export async function createVariation( +export async function create( context: Client, - image: CreateImageVariationRequest, - options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, + image: CreateImageRequest, + options: ImagesCreateOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createVariationSend(context, image, options); - return _createVariationDeserialize(result); + const result = await _createSend(context, image, options); + return _createDeserialize(result); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts index 2f0d3bb507..454d813f96 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/index.ts @@ -7,32 +7,32 @@ export { OpenAIClientOptionalParams, } from "./openAIContext.js"; export { - AudioTranscriptionsCreateOptionalParams, - AudioTranslationsCreateOptionalParams, - ChatCompletionsCreateOptionalParams, - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, - CompletionsCreateOptionalParams, - EditsCreateOptionalParams, - EmbeddingsCreateOptionalParams, - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, ModerationsCreateOptionalParams, + ImagesCreateVariationOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, + ModelsDeleteOptionalParams, + ModelsRetrieveOptionalParams, + ModelsListOptionalParams, + FineTunesCancelOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListOptionalParams, + FineTunesCreateOptionalParams, + FilesDownloadOptionalParams, + FilesDeleteOptionalParams, + FilesRetrieveOptionalParams, + FilesCreateOptionalParams, + FilesListOptionalParams, + EmbeddingsCreateOptionalParams, + EditsCreateOptionalParams, + CompletionsCreateOptionalParams, + FineTuningJobsCancelOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsCreateOptionalParams, + ChatCompletionsCreateOptionalParams, + AudioTranslationsCreateOptionalParams, + AudioTranscriptionsCreateOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts index 1192f91414..bd67b66367 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/models/index.ts @@ -22,32 +22,45 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _listSend( +export function _$deleteSend( context: Client, - options: ModelsListOptionalParams = { requestOptions: {} }, + model: string, + options: ModelsDeleteOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/models") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/models/{model}", model) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _listDeserialize( +export async function _$deleteDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listModelsResponseDeserializer(result.body); + return deleteModelResponseDeserializer(result.body); } -export async function list( +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( context: Client, - options: ModelsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + model: string, + options: ModelsDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend(context, model, options); + return _$deleteDeserialize(result); } export function _retrieveSend( @@ -57,7 +70,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/models/{model}", model) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -80,37 +99,36 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _$deleteSend( +export function _listSend( context: Client, - model: string, - options: ModelsDeleteOptionalParams = { requestOptions: {} }, + options: ModelsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/models/{model}", model) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/models") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _$deleteDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return deleteModelResponseDeserializer(result.body); + return listModelsResponseDeserializer(result.body); } -/** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ -export async function $delete( +export async function list( context: Client, - model: string, - options: ModelsDeleteOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _$deleteSend(context, model, options); - return _$deleteDeserialize(result); + options: ModelsListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts index b8bbbdc014..0efa0c54ce 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/moderations/index.ts @@ -27,6 +27,11 @@ export function _createSend( .path("/moderations") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createModerationRequestSerializer(content), }); } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts index ed669d35e4..7039d46e8e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/openAIContext.ts @@ -17,7 +17,7 @@ export function createOpenAI( options: OpenAIClientOptionalParams = {}, ): OpenAIContext { const endpointUrl = - options.endpoint ?? options.baseUrl ?? `https://api.openai.com/v1`; + options.endpoint ?? options.baseUrl ?? "https://api.openai.com/v1"; const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-openai-generic/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/options.ts index e5b8e43472..338edd5c86 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/api/options.ts @@ -4,120 +4,110 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface AudioTranscriptionsCreateOptionalParams - extends OperationOptions { - contentType?: string; -} +export interface ModerationsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AudioTranslationsCreateOptionalParams - extends OperationOptions { - contentType?: string; -} +export interface ImagesCreateVariationOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ChatCompletionsCreateOptionalParams extends OperationOptions {} +export interface ImagesCreateEditOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsCreateOptionalParams extends OperationOptions {} +export interface ImagesCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsListOptionalParams extends OperationOptions { - /** Identifier for the last job from the previous pagination request. */ - after?: string; - /** Number of fine-tuning jobs to retrieve. */ - limit?: number; -} +export interface ModelsDeleteOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsRetrieveOptionalParams - extends OperationOptions {} +export interface ModelsRetrieveOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsListEventsOptionalParams - extends OperationOptions { - /** Identifier for the last event from the previous pagination request. */ - after?: string; - /** Number of events to retrieve. */ - limit?: number; -} +export interface ModelsListOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsCancelOptionalParams extends OperationOptions {} +export interface FineTunesCancelOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface CompletionsCreateOptionalParams extends OperationOptions {} +export interface FineTunesListEventsOptionalParams extends OperationOptions { + /** + * Whether to stream events for the fine-tune job. If set to true, events will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available. The stream will terminate with a `data: [DONE]` message when the + * job is finished (succeeded, cancelled, or failed). + * + * If set to false, only events generated so far will be returned. + */ + stream?: boolean; +} /** Optional parameters. */ -export interface EditsCreateOptionalParams extends OperationOptions {} +export interface FineTunesRetrieveOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface EmbeddingsCreateOptionalParams extends OperationOptions {} +export interface FineTunesListOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesListOptionalParams extends OperationOptions {} +export interface FineTunesCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesCreateOptionalParams extends OperationOptions { - contentType?: string; -} +export interface FilesDownloadOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesRetrieveOptionalParams extends OperationOptions {} +export interface FilesDeleteOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesDeleteOptionalParams extends OperationOptions {} +export interface FilesRetrieveOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesDownloadOptionalParams extends OperationOptions {} +export interface FilesCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesCreateOptionalParams extends OperationOptions {} +export interface FilesListOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesListOptionalParams extends OperationOptions {} +export interface EmbeddingsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesRetrieveOptionalParams extends OperationOptions {} +export interface EditsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesListEventsOptionalParams extends OperationOptions { - /** - * Whether to stream events for the fine-tune job. If set to true, events will be sent as - * data-only - * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - * as they become available. The stream will terminate with a `data: [DONE]` message when the - * job is finished (succeeded, cancelled, or failed). - * - * If set to false, only events generated so far will be returned. - */ - stream?: boolean; -} +export interface CompletionsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesCancelOptionalParams extends OperationOptions {} +export interface FineTuningJobsCancelOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ModelsListOptionalParams extends OperationOptions {} +export interface FineTuningJobsListEventsOptionalParams + extends OperationOptions { + /** Identifier for the last event from the previous pagination request. */ + after?: string; + /** Number of events to retrieve. */ + limit?: number; +} /** Optional parameters. */ -export interface ModelsRetrieveOptionalParams extends OperationOptions {} +export interface FineTuningJobsRetrieveOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ModelsDeleteOptionalParams extends OperationOptions {} +export interface FineTuningJobsListOptionalParams extends OperationOptions { + /** Identifier for the last job from the previous pagination request. */ + after?: string; + /** Number of fine-tuning jobs to retrieve. */ + limit?: number; +} /** Optional parameters. */ -export interface ImagesCreateOptionalParams extends OperationOptions {} +export interface FineTuningJobsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ImagesCreateEditOptionalParams extends OperationOptions { - contentType?: string; -} +export interface ChatCompletionsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ImagesCreateVariationOptionalParams extends OperationOptions { - contentType?: string; -} +export interface AudioTranslationsCreateOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ModerationsCreateOptionalParams extends OperationOptions {} +export interface AudioTranscriptionsCreateOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts index a86bb79fc7..d11286f91e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/audio/index.ts @@ -13,13 +13,13 @@ import { /** Interface representing a Audio operations. */ export interface AudioOperations { - transcriptions: AudioTranscriptionsOperations; translations: AudioTranslationsOperations; + transcriptions: AudioTranscriptionsOperations; } export function getAudioOperations(context: OpenAIContext): AudioOperations { return { - transcriptions: getAudioTranscriptionsOperations(context), translations: getAudioTranslationsOperations(context), + transcriptions: getAudioTranscriptionsOperations(context), }; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts index 3cb48b2f67..1f3f8e2890 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/files/index.ts @@ -3,11 +3,11 @@ import { OpenAIContext } from "../../api/openAIContext.js"; import { - list, - create, - retrieve, - $delete, download, + $delete, + retrieve, + create, + list, } from "../../api/files/index.js"; import { OpenAIFile, @@ -16,24 +16,19 @@ import { DeleteFileResponse, } from "../../models/models.js"; import { - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, FilesDownloadOptionalParams, + FilesDeleteOptionalParams, + FilesRetrieveOptionalParams, + FilesCreateOptionalParams, + FilesListOptionalParams, } from "../../api/options.js"; /** Interface representing a Files operations. */ export interface FilesOperations { - list: (options?: FilesListOptionalParams) => Promise; - create: ( - file: CreateFileRequest, - options?: FilesCreateOptionalParams, - ) => Promise; - retrieve: ( + download: ( fileId: string, - options?: FilesRetrieveOptionalParams, - ) => Promise; + options?: FilesDownloadOptionalParams, + ) => Promise; /** * @fixme delete is a reserved word that cannot be used as an operation name. * Please add @clientName("clientName") or @clientName("", "javascript") @@ -43,23 +38,28 @@ export interface FilesOperations { fileId: string, options?: FilesDeleteOptionalParams, ) => Promise; - download: ( + retrieve: ( fileId: string, - options?: FilesDownloadOptionalParams, - ) => Promise; + options?: FilesRetrieveOptionalParams, + ) => Promise; + create: ( + file: CreateFileRequest, + options?: FilesCreateOptionalParams, + ) => Promise; + list: (options?: FilesListOptionalParams) => Promise; } export function getFiles(context: OpenAIContext) { return { - list: (options?: FilesListOptionalParams) => list(context, options), - create: (file: CreateFileRequest, options?: FilesCreateOptionalParams) => - create(context, file, options), - retrieve: (fileId: string, options?: FilesRetrieveOptionalParams) => - retrieve(context, fileId, options), - delete: (fileId: string, options?: FilesDeleteOptionalParams) => - $delete(context, fileId, options), download: (fileId: string, options?: FilesDownloadOptionalParams) => download(context, fileId, options), + delete: (fileId: string, options?: FilesDeleteOptionalParams) => + $delete(context, fileId, options), + retrieve: (fileId: string, options?: FilesRetrieveOptionalParams) => + retrieve(context, fileId, options), + create: (file: CreateFileRequest, options?: FilesCreateOptionalParams) => + create(context, file, options), + list: (options?: FilesListOptionalParams) => list(context, options), }; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts index c30d9578f6..37f6dd176f 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTunes/index.ts @@ -3,11 +3,11 @@ import { OpenAIContext } from "../../api/openAIContext.js"; import { - create, - list, - retrieve, - listEvents, cancel, + listEvents, + retrieve, + list, + create, } from "../../api/fineTunes/index.js"; import { CreateFineTuneRequest, @@ -16,51 +16,51 @@ import { ListFineTuneEventsResponse, } from "../../models/models.js"; import { - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, FineTunesCancelOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListOptionalParams, + FineTunesCreateOptionalParams, } from "../../api/options.js"; /** Interface representing a FineTunes operations. */ export interface FineTunesOperations { - create: ( - fineTune: CreateFineTuneRequest, - options?: FineTunesCreateOptionalParams, - ) => Promise; - list: ( - options?: FineTunesListOptionalParams, - ) => Promise; - retrieve: ( + cancel: ( fineTuneId: string, - options?: FineTunesRetrieveOptionalParams, + options?: FineTunesCancelOptionalParams, ) => Promise; listEvents: ( fineTuneId: string, options?: FineTunesListEventsOptionalParams, ) => Promise; - cancel: ( + retrieve: ( fineTuneId: string, - options?: FineTunesCancelOptionalParams, + options?: FineTunesRetrieveOptionalParams, + ) => Promise; + list: ( + options?: FineTunesListOptionalParams, + ) => Promise; + create: ( + fineTune: CreateFineTuneRequest, + options?: FineTunesCreateOptionalParams, ) => Promise; } export function getFineTunes(context: OpenAIContext) { return { - create: ( - fineTune: CreateFineTuneRequest, - options?: FineTunesCreateOptionalParams, - ) => create(context, fineTune, options), - list: (options?: FineTunesListOptionalParams) => list(context, options), - retrieve: (fineTuneId: string, options?: FineTunesRetrieveOptionalParams) => - retrieve(context, fineTuneId, options), + cancel: (fineTuneId: string, options?: FineTunesCancelOptionalParams) => + cancel(context, fineTuneId, options), listEvents: ( fineTuneId: string, options?: FineTunesListEventsOptionalParams, ) => listEvents(context, fineTuneId, options), - cancel: (fineTuneId: string, options?: FineTunesCancelOptionalParams) => - cancel(context, fineTuneId, options), + retrieve: (fineTuneId: string, options?: FineTunesRetrieveOptionalParams) => + retrieve(context, fineTuneId, options), + list: (options?: FineTunesListOptionalParams) => list(context, options), + create: ( + fineTune: CreateFineTuneRequest, + options?: FineTunesCreateOptionalParams, + ) => create(context, fineTune, options), }; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts index 9013f8af67..deb200203e 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts @@ -3,11 +3,11 @@ import { OpenAIContext } from "../../../api/openAIContext.js"; import { - create, - list, - retrieve, - listEvents, cancel, + listEvents, + retrieve, + list, + create, } from "../../../api/fineTuning/jobs/index.js"; import { CreateFineTuningJobRequest, @@ -16,15 +16,30 @@ import { ListFineTuningJobEventsResponse, } from "../../../models/models.js"; import { - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, FineTuningJobsCancelOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsCreateOptionalParams, } from "../../../api/options.js"; /** Interface representing a FineTuningJobs operations. */ export interface FineTuningJobsOperations { + cancel: ( + fineTuningJobId: string, + options?: FineTuningJobsCancelOptionalParams, + ) => Promise; + listEvents: ( + fineTuningJobId: string, + options?: FineTuningJobsListEventsOptionalParams, + ) => Promise; + retrieve: ( + fineTuningJobId: string, + options?: FineTuningJobsRetrieveOptionalParams, + ) => Promise; + list: ( + options?: FineTuningJobsListOptionalParams, + ) => Promise; /** * Creates a job that fine-tunes a specified model from a given dataset. * @@ -37,43 +52,28 @@ export interface FineTuningJobsOperations { job: CreateFineTuningJobRequest, options?: FineTuningJobsCreateOptionalParams, ) => Promise; - list: ( - options?: FineTuningJobsListOptionalParams, - ) => Promise; - retrieve: ( - fineTuningJobId: string, - options?: FineTuningJobsRetrieveOptionalParams, - ) => Promise; - listEvents: ( - fineTuningJobId: string, - options?: FineTuningJobsListEventsOptionalParams, - ) => Promise; - cancel: ( - fineTuningJobId: string, - options?: FineTuningJobsCancelOptionalParams, - ) => Promise; } export function getFineTuningJobs(context: OpenAIContext) { return { - create: ( - job: CreateFineTuningJobRequest, - options?: FineTuningJobsCreateOptionalParams, - ) => create(context, job, options), - list: (options?: FineTuningJobsListOptionalParams) => - list(context, options), - retrieve: ( + cancel: ( fineTuningJobId: string, - options?: FineTuningJobsRetrieveOptionalParams, - ) => retrieve(context, fineTuningJobId, options), + options?: FineTuningJobsCancelOptionalParams, + ) => cancel(context, fineTuningJobId, options), listEvents: ( fineTuningJobId: string, options?: FineTuningJobsListEventsOptionalParams, ) => listEvents(context, fineTuningJobId, options), - cancel: ( + retrieve: ( fineTuningJobId: string, - options?: FineTuningJobsCancelOptionalParams, - ) => cancel(context, fineTuningJobId, options), + options?: FineTuningJobsRetrieveOptionalParams, + ) => retrieve(context, fineTuningJobId, options), + list: (options?: FineTuningJobsListOptionalParams) => + list(context, options), + create: ( + job: CreateFineTuningJobRequest, + options?: FineTuningJobsCreateOptionalParams, + ) => create(context, job, options), }; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts index 0e0f93f1f7..5d32d46bd0 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/images/index.ts @@ -2,7 +2,7 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { create, createEdit, createVariation } from "../../api/images/index.js"; +import { createVariation, createEdit, create } from "../../api/images/index.js"; import { CreateImageRequest, ImagesResponse, @@ -10,39 +10,39 @@ import { CreateImageVariationRequest, } from "../../models/models.js"; import { - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, ImagesCreateVariationOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, } from "../../api/options.js"; /** Interface representing a Images operations. */ export interface ImagesOperations { - create: ( - image: CreateImageRequest, - options?: ImagesCreateOptionalParams, + createVariation: ( + image: CreateImageVariationRequest, + options?: ImagesCreateVariationOptionalParams, ) => Promise; createEdit: ( image: CreateImageEditRequest, options?: ImagesCreateEditOptionalParams, ) => Promise; - createVariation: ( - image: CreateImageVariationRequest, - options?: ImagesCreateVariationOptionalParams, + create: ( + image: CreateImageRequest, + options?: ImagesCreateOptionalParams, ) => Promise; } export function getImages(context: OpenAIContext) { return { - create: (image: CreateImageRequest, options?: ImagesCreateOptionalParams) => - create(context, image, options), - createEdit: ( - image: CreateImageEditRequest, - options?: ImagesCreateEditOptionalParams, - ) => createEdit(context, image, options), createVariation: ( image: CreateImageVariationRequest, options?: ImagesCreateVariationOptionalParams, ) => createVariation(context, image, options), + createEdit: ( + image: CreateImageEditRequest, + options?: ImagesCreateEditOptionalParams, + ) => createEdit(context, image, options), + create: (image: CreateImageRequest, options?: ImagesCreateOptionalParams) => + create(context, image, options), }; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts index 8c6f78bdc4..38b996ece4 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/classic/models/index.ts @@ -2,25 +2,20 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { list, retrieve, $delete } from "../../api/models/index.js"; +import { $delete, retrieve, list } from "../../api/models/index.js"; import { ListModelsResponse, Model, DeleteModelResponse, } from "../../models/models.js"; import { - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, ModelsDeleteOptionalParams, + ModelsRetrieveOptionalParams, + ModelsListOptionalParams, } from "../../api/options.js"; /** Interface representing a Models operations. */ export interface ModelsOperations { - list: (options?: ModelsListOptionalParams) => Promise; - retrieve: ( - model: string, - options?: ModelsRetrieveOptionalParams, - ) => Promise; /** * @fixme delete is a reserved word that cannot be used as an operation name. * Please add @clientName("clientName") or @clientName("", "javascript") @@ -30,15 +25,20 @@ export interface ModelsOperations { model: string, options?: ModelsDeleteOptionalParams, ) => Promise; + retrieve: ( + model: string, + options?: ModelsRetrieveOptionalParams, + ) => Promise; + list: (options?: ModelsListOptionalParams) => Promise; } export function getModels(context: OpenAIContext) { return { - list: (options?: ModelsListOptionalParams) => list(context, options), - retrieve: (model: string, options?: ModelsRetrieveOptionalParams) => - retrieve(context, model, options), delete: (model: string, options?: ModelsDeleteOptionalParams) => $delete(context, model, options), + retrieve: (model: string, options?: ModelsRetrieveOptionalParams) => + retrieve(context, model, options), + list: (options?: ModelsListOptionalParams) => list(context, options), }; } diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts index e67b5edf9f..700934d6b7 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/index.ts @@ -51,34 +51,34 @@ export { } from "./models/index.js"; export { OpenAIClientOptionalParams, - AudioTranscriptionsCreateOptionalParams, - AudioTranslationsCreateOptionalParams, - ChatCompletionsCreateOptionalParams, - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, - CompletionsCreateOptionalParams, - EditsCreateOptionalParams, - EmbeddingsCreateOptionalParams, - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, ModerationsCreateOptionalParams, + ImagesCreateVariationOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, + ModelsDeleteOptionalParams, + ModelsRetrieveOptionalParams, + ModelsListOptionalParams, + FineTunesCancelOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListOptionalParams, + FineTunesCreateOptionalParams, + FilesDownloadOptionalParams, + FilesDeleteOptionalParams, + FilesRetrieveOptionalParams, + FilesCreateOptionalParams, + FilesListOptionalParams, + EmbeddingsCreateOptionalParams, + EditsCreateOptionalParams, + CompletionsCreateOptionalParams, + FineTuningJobsCancelOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsCreateOptionalParams, + ChatCompletionsCreateOptionalParams, + AudioTranslationsCreateOptionalParams, + AudioTranscriptionsCreateOptionalParams, } from "./api/index.js"; export { AudioOperations, diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts index dda8339c3e..792a7a3674 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/models/models.ts @@ -1180,13 +1180,13 @@ export function createCompletionRequestSerializer( ): any { return { model: item["model"], - prompt: item["prompt"], + prompt: !item["prompt"] ? item["prompt"] : promptSerializer(item["prompt"]), suffix: item["suffix"], temperature: item["temperature"], top_p: item["top_p"], n: item["n"], max_tokens: item["max_tokens"], - stop: item["stop"], + stop: !item["stop"] ? item["stop"] : stopSerializer(item["stop"]), presence_penalty: item["presence_penalty"], frequency_penalty: item["frequency_penalty"], logit_bias: item["logit_bias"], @@ -1289,7 +1289,9 @@ export function _createCompletionResponseChoiceDeserializer( return { index: item["index"], text: item["text"], - logprobs: item["logprobs"], + logprobs: !item["logprobs"] + ? item["logprobs"] + : _createCompletionResponseChoiceLogprobsDeserializer(item["logprobs"]), finish_reason: item["finish_reason"], }; } @@ -1489,9 +1491,7 @@ export function fineTuningJobDeserializer(item: any): FineTuningJob { created_at: new Date(item["created_at"] * 1000), finished_at: !item["finished_at"] ? item["finished_at"] - : !item["finished_at"] - ? item["finished_at"] - : new Date(item["finished_at"] * 1000), + : new Date(item["finished_at"] * 1000), model: item["model"], fine_tuned_model: item["fine_tuned_model"], organization_id: item["organization_id"], @@ -1505,7 +1505,9 @@ export function fineTuningJobDeserializer(item: any): FineTuningJob { return p; }), trained_tokens: item["trained_tokens"], - error: item["error"], + error: !item["error"] + ? item["error"] + : _fineTuningJobErrorDeserializer(item["error"]), }; } @@ -1750,7 +1752,7 @@ export function createChatCompletionRequestSerializer( top_p: item["top_p"], n: item["n"], max_tokens: item["max_tokens"], - stop: item["stop"], + stop: !item["stop"] ? item["stop"] : stopSerializer(item["stop"]), presence_penalty: item["presence_penalty"], frequency_penalty: item["frequency_penalty"], logit_bias: item["logit_bias"], diff --git a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts index 8552a6504d..78a6912612 100644 --- a/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai_generic/generated/typespec-ts/src/openAIClient.ts @@ -1,38 +1,38 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { getAudioOperations, AudioOperations } from "./classic/audio/index.js"; -import { getChatOperations, ChatOperations } from "./classic/chat/index.js"; import { - getFineTuningOperations, - FineTuningOperations, -} from "./classic/fineTuning/index.js"; + getModerationsOperations, + ModerationsOperations, +} from "./classic/moderations/index.js"; import { - getCompletionsOperations, - CompletionsOperations, -} from "./classic/completions/index.js"; -import { getEditsOperations, EditsOperations } from "./classic/edits/index.js"; + getImagesOperations, + ImagesOperations, +} from "./classic/images/index.js"; import { - getEmbeddingsOperations, - EmbeddingsOperations, -} from "./classic/embeddings/index.js"; -import { getFilesOperations, FilesOperations } from "./classic/files/index.js"; + getModelsOperations, + ModelsOperations, +} from "./classic/models/index.js"; import { getFineTunesOperations, FineTunesOperations, } from "./classic/fineTunes/index.js"; +import { getFilesOperations, FilesOperations } from "./classic/files/index.js"; import { - getModelsOperations, - ModelsOperations, -} from "./classic/models/index.js"; + getEmbeddingsOperations, + EmbeddingsOperations, +} from "./classic/embeddings/index.js"; +import { getEditsOperations, EditsOperations } from "./classic/edits/index.js"; import { - getImagesOperations, - ImagesOperations, -} from "./classic/images/index.js"; + getCompletionsOperations, + CompletionsOperations, +} from "./classic/completions/index.js"; import { - getModerationsOperations, - ModerationsOperations, -} from "./classic/moderations/index.js"; + getFineTuningOperations, + FineTuningOperations, +} from "./classic/fineTuning/index.js"; +import { getChatOperations, ChatOperations } from "./classic/chat/index.js"; +import { getAudioOperations, AudioOperations } from "./classic/audio/index.js"; import { createOpenAI, OpenAIContext, @@ -62,39 +62,39 @@ export class OpenAIClient { userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; - this.audio = getAudioOperations(this._client); - this.chat = getChatOperations(this._client); - this.fineTuning = getFineTuningOperations(this._client); - this.completions = getCompletionsOperations(this._client); - this.edits = getEditsOperations(this._client); - this.embeddings = getEmbeddingsOperations(this._client); - this.files = getFilesOperations(this._client); - this.fineTunes = getFineTunesOperations(this._client); - this.models = getModelsOperations(this._client); - this.images = getImagesOperations(this._client); this.moderations = getModerationsOperations(this._client); + this.images = getImagesOperations(this._client); + this.models = getModelsOperations(this._client); + this.fineTunes = getFineTunesOperations(this._client); + this.files = getFilesOperations(this._client); + this.embeddings = getEmbeddingsOperations(this._client); + this.edits = getEditsOperations(this._client); + this.completions = getCompletionsOperations(this._client); + this.fineTuning = getFineTuningOperations(this._client); + this.chat = getChatOperations(this._client); + this.audio = getAudioOperations(this._client); } - /** The operation groups for AudioTranscriptions */ - public readonly audio: AudioOperations; - /** The operation groups for ChatCompletions */ - public readonly chat: ChatOperations; - /** The operation groups for FineTuningJobs */ - public readonly fineTuning: FineTuningOperations; - /** The operation groups for Completions */ - public readonly completions: CompletionsOperations; - /** The operation groups for Edits */ - public readonly edits: EditsOperations; - /** The operation groups for Embeddings */ - public readonly embeddings: EmbeddingsOperations; - /** The operation groups for Files */ - public readonly files: FilesOperations; - /** The operation groups for FineTunes */ - public readonly fineTunes: FineTunesOperations; - /** The operation groups for Models */ - public readonly models: ModelsOperations; - /** The operation groups for Images */ - public readonly images: ImagesOperations; - /** The operation groups for Moderations */ + /** The operation groups for moderations */ public readonly moderations: ModerationsOperations; + /** The operation groups for images */ + public readonly images: ImagesOperations; + /** The operation groups for models */ + public readonly models: ModelsOperations; + /** The operation groups for fineTunes */ + public readonly fineTunes: FineTunesOperations; + /** The operation groups for files */ + public readonly files: FilesOperations; + /** The operation groups for embeddings */ + public readonly embeddings: EmbeddingsOperations; + /** The operation groups for edits */ + public readonly edits: EditsOperations; + /** The operation groups for completions */ + public readonly completions: CompletionsOperations; + /** The operation groups for fineTuning */ + public readonly fineTuning: FineTuningOperations; + /** The operation groups for chat */ + public readonly chat: ChatOperations; + /** The operation groups for audio */ + public readonly audio: AudioOperations; } diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md b/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md index 1e61a43099..4766f76ba8 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/review/openai_modular.api.md @@ -732,22 +732,18 @@ export interface GenerateSpeechFromTextOptionalParams extends OperationOptions { // @public export interface GetAudioTranscriptionAsPlainTextOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface GetAudioTranscriptionAsResponseObjectOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface GetAudioTranslationAsPlainTextOptionalParams extends OperationOptions { - contentType?: string; } // @public export interface GetAudioTranslationAsResponseObjectOptionalParams extends OperationOptions { - contentType?: string; } // @public diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts index 1c4edce4d8..9d3fdfbcdd 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/index.ts @@ -7,24 +7,24 @@ export { OpenAIClientOptionalParams, } from "./openAIContext.js"; export { - getAudioTranscriptionAsPlainText, - getAudioTranscriptionAsResponseObject, - getAudioTranslationAsPlainText, - getAudioTranslationAsResponseObject, - getCompletions, - getChatCompletions, - getImageGenerations, - generateSpeechFromText, getEmbeddings, + generateSpeechFromText, + getImageGenerations, + getChatCompletions, + getCompletions, + getAudioTranslationAsResponseObject, + getAudioTranslationAsPlainText, + getAudioTranscriptionAsResponseObject, + getAudioTranscriptionAsPlainText, } from "./operations.js"; export { - GetAudioTranscriptionAsPlainTextOptionalParams, - GetAudioTranscriptionAsResponseObjectOptionalParams, - GetAudioTranslationAsPlainTextOptionalParams, - GetAudioTranslationAsResponseObjectOptionalParams, - GetCompletionsOptionalParams, - GetChatCompletionsOptionalParams, - GetImageGenerationsOptionalParams, - GenerateSpeechFromTextOptionalParams, GetEmbeddingsOptionalParams, + GenerateSpeechFromTextOptionalParams, + GetImageGenerationsOptionalParams, + GetChatCompletionsOptionalParams, + GetCompletionsOptionalParams, + GetAudioTranslationAsResponseObjectOptionalParams, + GetAudioTranslationAsPlainTextOptionalParams, + GetAudioTranscriptionAsResponseObjectOptionalParams, + GetAudioTranscriptionAsPlainTextOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts index 5f3f4b9ed2..54bcbc5408 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/openAIContext.ts @@ -6,7 +6,11 @@ import { KnownServiceApiVersions } from "../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { KeyCredential, TokenCredential } from "@azure/core-auth"; -export interface OpenAIContext extends Client {} +export interface OpenAIContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownServiceApiVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface OpenAIClientOptionalParams extends ClientOptions { @@ -56,5 +60,5 @@ export function createOpenAI( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as OpenAIContext; } diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts index 76da673e8d..c96810fc39 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/operations.ts @@ -48,194 +48,191 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _getAudioTranscriptionAsPlainTextSend( +export function _getEmbeddingsSend( context: Client, deploymentId: string, - body: AudioTranscriptionOptions, - options: GetAudioTranscriptionAsPlainTextOptionalParams = { - requestOptions: {}, - }, + body: EmbeddingsOptions, + options: GetEmbeddingsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/audio/transcriptions", deploymentId) + .path("/deployments/{deploymentId}/embeddings", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: audioTranscriptionOptionsSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: embeddingsOptionsSerializer(body), }); } -export async function _getAudioTranscriptionAsPlainTextDeserialize( +export async function _getEmbeddingsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body; + return embeddingsDeserializer(result.body); } -/** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. - */ -export async function getAudioTranscriptionAsPlainText( +/** Return the embeddings for a given prompt. */ +export async function getEmbeddings( context: Client, deploymentId: string, - body: AudioTranscriptionOptions, - options: GetAudioTranscriptionAsPlainTextOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranscriptionAsPlainTextSend( - context, - deploymentId, - body, - options, - ); - return _getAudioTranscriptionAsPlainTextDeserialize(result); + body: EmbeddingsOptions, + options: GetEmbeddingsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getEmbeddingsSend(context, deploymentId, body, options); + return _getEmbeddingsDeserialize(result); } -export function _getAudioTranscriptionAsResponseObjectSend( +export function _generateSpeechFromTextSend( context: Client, deploymentId: string, - body: AudioTranscriptionOptions, - options: GetAudioTranscriptionAsResponseObjectOptionalParams = { - requestOptions: {}, - }, + body: SpeechGenerationOptions, + options: GenerateSpeechFromTextOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/audio/transcriptions", deploymentId) + .path("/deployments/{deploymentId}/audio/speech", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: audioTranscriptionOptionsSerializer(body), + contentType: "application/json", + headers: { + accept: "application/octet-stream", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: speechGenerationOptionsSerializer(body), }); } -export async function _getAudioTranscriptionAsResponseObjectDeserialize( +export async function _generateSpeechFromTextDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return audioTranscriptionDeserializer(result.body); + return result.body; } -/** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. - */ -export async function getAudioTranscriptionAsResponseObject( +/** Generates text-to-speech audio from the input text. */ +export async function generateSpeechFromText( context: Client, deploymentId: string, - body: AudioTranscriptionOptions, - options: GetAudioTranscriptionAsResponseObjectOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranscriptionAsResponseObjectSend( + body: SpeechGenerationOptions, + options: GenerateSpeechFromTextOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _generateSpeechFromTextSend( context, deploymentId, body, options, ); - return _getAudioTranscriptionAsResponseObjectDeserialize(result); + return _generateSpeechFromTextDeserialize(result); } -export function _getAudioTranslationAsPlainTextSend( +export function _getImageGenerationsSend( context: Client, deploymentId: string, - body: AudioTranslationOptions, - options: GetAudioTranslationAsPlainTextOptionalParams = { - requestOptions: {}, - }, + body: ImageGenerationOptions, + options: GetImageGenerationsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/audio/translations", deploymentId) + .path("/deployments/{deploymentId}/images/generations", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: audioTranslationOptionsSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: imageGenerationOptionsSerializer(body), }); } -export async function _getAudioTranslationAsPlainTextDeserialize( +export async function _getImageGenerationsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body; + return imageGenerationsDeserializer(result.body); } -/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ -export async function getAudioTranslationAsPlainText( +/** Creates an image given a prompt. */ +export async function getImageGenerations( context: Client, deploymentId: string, - body: AudioTranslationOptions, - options: GetAudioTranslationAsPlainTextOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranslationAsPlainTextSend( + body: ImageGenerationOptions, + options: GetImageGenerationsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getImageGenerationsSend( context, deploymentId, body, options, ); - return _getAudioTranslationAsPlainTextDeserialize(result); + return _getImageGenerationsDeserialize(result); } -export function _getAudioTranslationAsResponseObjectSend( +export function _getChatCompletionsSend( context: Client, deploymentId: string, - body: AudioTranslationOptions, - options: GetAudioTranslationAsResponseObjectOptionalParams = { - requestOptions: {}, - }, + body: ChatCompletionsOptions, + options: GetChatCompletionsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/audio/translations", deploymentId) + .path("/deployments/{deploymentId}/chat/completions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: audioTranslationOptionsSerializer(body), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: chatCompletionsOptionsSerializer(body), }); } -export async function _getAudioTranslationAsResponseObjectDeserialize( +export async function _getChatCompletionsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return audioTranslationDeserializer(result.body); + return chatCompletionsDeserializer(result.body); } -/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ -export async function getAudioTranslationAsResponseObject( +/** + * Gets chat completions for the provided chat messages. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ +export async function getChatCompletions( context: Client, deploymentId: string, - body: AudioTranslationOptions, - options: GetAudioTranslationAsResponseObjectOptionalParams = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranslationAsResponseObjectSend( + body: ChatCompletionsOptions, + options: GetChatCompletionsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getChatCompletionsSend( context, deploymentId, body, options, ); - return _getAudioTranslationAsResponseObjectDeserialize(result); + return _getChatCompletionsDeserialize(result); } export function _getCompletionsSend( @@ -248,6 +245,12 @@ export function _getCompletionsSend( .path("/deployments/{deploymentId}/completions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: completionsOptionsSerializer(body), }); } @@ -283,165 +286,206 @@ export async function getCompletions( return _getCompletionsDeserialize(result); } -export function _getChatCompletionsSend( +export function _getAudioTranslationAsResponseObjectSend( context: Client, deploymentId: string, - body: ChatCompletionsOptions, - options: GetChatCompletionsOptionalParams = { requestOptions: {} }, + body: AudioTranslationOptions, + options: GetAudioTranslationAsResponseObjectOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/chat/completions", deploymentId) + .path("/deployments/{deploymentId}/audio/translations", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: chatCompletionsOptionsSerializer(body), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: audioTranslationOptionsSerializer(body), }); } -export async function _getChatCompletionsDeserialize( +export async function _getAudioTranslationAsResponseObjectDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return chatCompletionsDeserializer(result.body); + return audioTranslationDeserializer(result.body); } -/** - * Gets chat completions for the provided chat messages. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export async function getChatCompletions( +/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ +export async function getAudioTranslationAsResponseObject( context: Client, deploymentId: string, - body: ChatCompletionsOptions, - options: GetChatCompletionsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getChatCompletionsSend( + body: AudioTranslationOptions, + options: GetAudioTranslationAsResponseObjectOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _getAudioTranslationAsResponseObjectSend( context, deploymentId, body, options, ); - return _getChatCompletionsDeserialize(result); + return _getAudioTranslationAsResponseObjectDeserialize(result); } -export function _getImageGenerationsSend( +export function _getAudioTranslationAsPlainTextSend( context: Client, deploymentId: string, - body: ImageGenerationOptions, - options: GetImageGenerationsOptionalParams = { requestOptions: {} }, + body: AudioTranslationOptions, + options: GetAudioTranslationAsPlainTextOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/images/generations", deploymentId) + .path("/deployments/{deploymentId}/audio/translations", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: imageGenerationOptionsSerializer(body), + contentType: "multipart/form-data", + headers: { accept: "text/plain", ...options.requestOptions?.headers }, + queryParameters: { "api-version": context.apiVersion }, + body: audioTranslationOptionsSerializer(body), }); } -export async function _getImageGenerationsDeserialize( +export async function _getAudioTranslationAsPlainTextDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return imageGenerationsDeserializer(result.body); + return result.body; } -/** Creates an image given a prompt. */ -export async function getImageGenerations( +/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ +export async function getAudioTranslationAsPlainText( context: Client, deploymentId: string, - body: ImageGenerationOptions, - options: GetImageGenerationsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getImageGenerationsSend( + body: AudioTranslationOptions, + options: GetAudioTranslationAsPlainTextOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _getAudioTranslationAsPlainTextSend( context, deploymentId, body, options, ); - return _getImageGenerationsDeserialize(result); + return _getAudioTranslationAsPlainTextDeserialize(result); } -export function _generateSpeechFromTextSend( +export function _getAudioTranscriptionAsResponseObjectSend( context: Client, deploymentId: string, - body: SpeechGenerationOptions, - options: GenerateSpeechFromTextOptionalParams = { requestOptions: {} }, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsResponseObjectOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/audio/speech", deploymentId) + .path("/deployments/{deploymentId}/audio/transcriptions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: speechGenerationOptionsSerializer(body), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: audioTranscriptionOptionsSerializer(body), }); } -export async function _generateSpeechFromTextDeserialize( +export async function _getAudioTranscriptionAsResponseObjectDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body; + return audioTranscriptionDeserializer(result.body); } -/** Generates text-to-speech audio from the input text. */ -export async function generateSpeechFromText( +/** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ +export async function getAudioTranscriptionAsResponseObject( context: Client, deploymentId: string, - body: SpeechGenerationOptions, - options: GenerateSpeechFromTextOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _generateSpeechFromTextSend( + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsResponseObjectOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _getAudioTranscriptionAsResponseObjectSend( context, deploymentId, body, options, ); - return _generateSpeechFromTextDeserialize(result); + return _getAudioTranscriptionAsResponseObjectDeserialize(result); } -export function _getEmbeddingsSend( +export function _getAudioTranscriptionAsPlainTextSend( context: Client, deploymentId: string, - body: EmbeddingsOptions, - options: GetEmbeddingsOptionalParams = { requestOptions: {} }, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsPlainTextOptionalParams = { + requestOptions: {}, + }, ): StreamableMethod { return context - .path("/deployments/{deploymentId}/embeddings", deploymentId) + .path("/deployments/{deploymentId}/audio/transcriptions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), - body: embeddingsOptionsSerializer(body), + contentType: "multipart/form-data", + headers: { accept: "text/plain", ...options.requestOptions?.headers }, + queryParameters: { "api-version": context.apiVersion }, + body: audioTranscriptionOptionsSerializer(body), }); } -export async function _getEmbeddingsDeserialize( +export async function _getAudioTranscriptionAsPlainTextDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return embeddingsDeserializer(result.body); + return result.body; } -/** Return the embeddings for a given prompt. */ -export async function getEmbeddings( +/** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ +export async function getAudioTranscriptionAsPlainText( context: Client, deploymentId: string, - body: EmbeddingsOptions, - options: GetEmbeddingsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getEmbeddingsSend(context, deploymentId, body, options); - return _getEmbeddingsDeserialize(result); + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsPlainTextOptionalParams = { + requestOptions: {}, + }, +): Promise { + const result = await _getAudioTranscriptionAsPlainTextSend( + context, + deploymentId, + body, + options, + ); + return _getAudioTranscriptionAsPlainTextDeserialize(result); } diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/options.ts index 9b47a834bd..7dd03a88ac 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/api/options.ts @@ -4,45 +4,33 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface GetAudioTranscriptionAsPlainTextOptionalParams - extends OperationOptions { - /** The content type for the operation. Always multipart/form-data for this operation. */ - contentType?: string; -} +export interface GetEmbeddingsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetAudioTranscriptionAsResponseObjectOptionalParams - extends OperationOptions { - /** The content type for the operation. Always multipart/form-data for this operation. */ - contentType?: string; -} +export interface GenerateSpeechFromTextOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface GetAudioTranslationAsPlainTextOptionalParams - extends OperationOptions { - /** The content type for the operation. Always multipart/form-data for this operation. */ - contentType?: string; -} +export interface GetImageGenerationsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetAudioTranslationAsResponseObjectOptionalParams - extends OperationOptions { - /** The content type for the operation. Always multipart/form-data for this operation. */ - contentType?: string; -} +export interface GetChatCompletionsOptionalParams extends OperationOptions {} /** Optional parameters. */ export interface GetCompletionsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetChatCompletionsOptionalParams extends OperationOptions {} +export interface GetAudioTranslationAsResponseObjectOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface GetImageGenerationsOptionalParams extends OperationOptions {} +export interface GetAudioTranslationAsPlainTextOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface GenerateSpeechFromTextOptionalParams +export interface GetAudioTranscriptionAsResponseObjectOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface GetEmbeddingsOptionalParams extends OperationOptions {} +export interface GetAudioTranscriptionAsPlainTextOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts index 62b0893cbf..9d384be0c3 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/index.ts @@ -147,13 +147,13 @@ export { } from "./models/index.js"; export { OpenAIClientOptionalParams, - GetAudioTranscriptionAsPlainTextOptionalParams, - GetAudioTranscriptionAsResponseObjectOptionalParams, - GetAudioTranslationAsPlainTextOptionalParams, - GetAudioTranslationAsResponseObjectOptionalParams, - GetCompletionsOptionalParams, - GetChatCompletionsOptionalParams, - GetImageGenerationsOptionalParams, - GenerateSpeechFromTextOptionalParams, GetEmbeddingsOptionalParams, + GenerateSpeechFromTextOptionalParams, + GetImageGenerationsOptionalParams, + GetChatCompletionsOptionalParams, + GetCompletionsOptionalParams, + GetAudioTranslationAsResponseObjectOptionalParams, + GetAudioTranslationAsPlainTextOptionalParams, + GetAudioTranscriptionAsResponseObjectOptionalParams, + GetAudioTranscriptionAsPlainTextOptionalParams, } from "./api/index.js"; diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts index cd8bded763..75c3fd4e82 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/models/models.ts @@ -715,7 +715,9 @@ export function choiceDeserializer(item: any): Choice { : contentFilterResultsForChoiceDeserializer( item["content_filter_results"], ), - logprobs: item["logprobs"], + logprobs: !item["logprobs"] + ? item["logprobs"] + : completionsLogProbabilityModelDeserializer(item["logprobs"]), finishReason: item["finish_reason"], }; } @@ -2971,7 +2973,9 @@ export function chatChoiceDeserializer(item: any): ChatChoice { message: !item["message"] ? item["message"] : chatResponseMessageDeserializer(item["message"]), - logprobs: item["logprobs"], + logprobs: !item["logprobs"] + ? item["logprobs"] + : chatChoiceLogProbabilityInfoDeserializer(item["logprobs"]), index: item["index"], finishReason: item["finish_reason"], finishDetails: !item["finish_details"] @@ -3176,11 +3180,7 @@ export function chatChoiceLogProbabilityInfoDeserializer( return { content: !item["content"] ? item["content"] - : !item["content"] - ? item["content"] - : item["content"].map((p: any) => { - return chatTokenLogProbabilityResultDeserializer(p); - }), + : chatTokenLogProbabilityResultArrayDeserializer(item["content"]), }; } @@ -3212,18 +3212,12 @@ export function chatTokenLogProbabilityResultDeserializer( logprob: item["logprob"], bytes: !item["bytes"] ? item["bytes"] - : !item["bytes"] - ? item["bytes"] - : item["bytes"].map((p: any) => { - return p; - }), + : item["bytes"].map((p: any) => { + return p; + }), topLogprobs: !item["top_logprobs"] ? item["top_logprobs"] - : !item["top_logprobs"] - ? item["top_logprobs"] - : item["top_logprobs"].map((p: any) => { - return chatTokenLogProbabilityInfoDeserializer(p); - }), + : chatTokenLogProbabilityInfoArrayDeserializer(item["top_logprobs"]), }; } @@ -3253,11 +3247,9 @@ export function chatTokenLogProbabilityInfoDeserializer( logprob: item["logprob"], bytes: !item["bytes"] ? item["bytes"] - : !item["bytes"] - ? item["bytes"] - : item["bytes"].map((p: any) => { - return p; - }), + : item["bytes"].map((p: any) => { + return p; + }), }; } diff --git a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts index 854e3de96e..756a6a7c9e 100644 --- a/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai_modular/generated/typespec-ts/src/openAIClient.ts @@ -5,24 +5,24 @@ import { createOpenAI, OpenAIContext, OpenAIClientOptionalParams, - getAudioTranscriptionAsPlainText, - getAudioTranscriptionAsResponseObject, - getAudioTranslationAsPlainText, - getAudioTranslationAsResponseObject, - getCompletions, - getChatCompletions, - getImageGenerations, - generateSpeechFromText, getEmbeddings, - GetAudioTranscriptionAsPlainTextOptionalParams, - GetAudioTranscriptionAsResponseObjectOptionalParams, - GetAudioTranslationAsPlainTextOptionalParams, - GetAudioTranslationAsResponseObjectOptionalParams, - GetCompletionsOptionalParams, - GetChatCompletionsOptionalParams, - GetImageGenerationsOptionalParams, - GenerateSpeechFromTextOptionalParams, + generateSpeechFromText, + getImageGenerations, + getChatCompletions, + getCompletions, + getAudioTranslationAsResponseObject, + getAudioTranslationAsPlainText, + getAudioTranscriptionAsResponseObject, + getAudioTranscriptionAsPlainText, GetEmbeddingsOptionalParams, + GenerateSpeechFromTextOptionalParams, + GetImageGenerationsOptionalParams, + GetChatCompletionsOptionalParams, + GetCompletionsOptionalParams, + GetAudioTranslationAsResponseObjectOptionalParams, + GetAudioTranslationAsPlainTextOptionalParams, + GetAudioTranscriptionAsResponseObjectOptionalParams, + GetAudioTranscriptionAsPlainTextOptionalParams, } from "./api/index.js"; import { AudioTranscriptionOptions, @@ -65,37 +65,68 @@ export class OpenAIClient { this.pipeline = this._client.pipeline; } + /** Return the embeddings for a given prompt. */ + getEmbeddings( + deploymentId: string, + body: EmbeddingsOptions, + options: GetEmbeddingsOptionalParams = { requestOptions: {} }, + ): Promise { + return getEmbeddings(this._client, deploymentId, body, options); + } + + /** Generates text-to-speech audio from the input text. */ + generateSpeechFromText( + deploymentId: string, + body: SpeechGenerationOptions, + options: GenerateSpeechFromTextOptionalParams = { requestOptions: {} }, + ): Promise { + return generateSpeechFromText(this._client, deploymentId, body, options); + } + + /** Creates an image given a prompt. */ + getImageGenerations( + deploymentId: string, + body: ImageGenerationOptions, + options: GetImageGenerationsOptionalParams = { requestOptions: {} }, + ): Promise { + return getImageGenerations(this._client, deploymentId, body, options); + } + /** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. + * Gets chat completions for the provided chat messages. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. */ - getAudioTranscriptionAsPlainText( + getChatCompletions( deploymentId: string, - body: AudioTranscriptionOptions, - options: GetAudioTranscriptionAsPlainTextOptionalParams = { - requestOptions: {}, - }, - ): Promise { - return getAudioTranscriptionAsPlainText( - this._client, - deploymentId, - body, - options, - ); + body: ChatCompletionsOptions, + options: GetChatCompletionsOptionalParams = { requestOptions: {} }, + ): Promise { + return getChatCompletions(this._client, deploymentId, body, options); } /** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. + * Gets completions for the provided input prompts. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. */ - getAudioTranscriptionAsResponseObject( + getCompletions( deploymentId: string, - body: AudioTranscriptionOptions, - options: GetAudioTranscriptionAsResponseObjectOptionalParams = { + body: CompletionsOptions, + options: GetCompletionsOptionalParams = { requestOptions: {} }, + ): Promise { + return getCompletions(this._client, deploymentId, body, options); + } + + /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ + getAudioTranslationAsResponseObject( + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsResponseObjectOptionalParams = { requestOptions: {}, }, - ): Promise { - return getAudioTranscriptionAsResponseObject( + ): Promise { + return getAudioTranslationAsResponseObject( this._client, deploymentId, body, @@ -119,15 +150,18 @@ export class OpenAIClient { ); } - /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ - getAudioTranslationAsResponseObject( + /** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ + getAudioTranscriptionAsResponseObject( deploymentId: string, - body: AudioTranslationOptions, - options: GetAudioTranslationAsResponseObjectOptionalParams = { + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsResponseObjectOptionalParams = { requestOptions: {}, }, - ): Promise { - return getAudioTranslationAsResponseObject( + ): Promise { + return getAudioTranscriptionAsResponseObject( this._client, deploymentId, body, @@ -136,55 +170,21 @@ export class OpenAIClient { } /** - * Gets completions for the provided input prompts. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ - getCompletions( - deploymentId: string, - body: CompletionsOptions, - options: GetCompletionsOptionalParams = { requestOptions: {} }, - ): Promise { - return getCompletions(this._client, deploymentId, body, options); - } - - /** - * Gets chat completions for the provided chat messages. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. */ - getChatCompletions( - deploymentId: string, - body: ChatCompletionsOptions, - options: GetChatCompletionsOptionalParams = { requestOptions: {} }, - ): Promise { - return getChatCompletions(this._client, deploymentId, body, options); - } - - /** Creates an image given a prompt. */ - getImageGenerations( - deploymentId: string, - body: ImageGenerationOptions, - options: GetImageGenerationsOptionalParams = { requestOptions: {} }, - ): Promise { - return getImageGenerations(this._client, deploymentId, body, options); - } - - /** Generates text-to-speech audio from the input text. */ - generateSpeechFromText( - deploymentId: string, - body: SpeechGenerationOptions, - options: GenerateSpeechFromTextOptionalParams = { requestOptions: {} }, - ): Promise { - return generateSpeechFromText(this._client, deploymentId, body, options); - } - - /** Return the embeddings for a given prompt. */ - getEmbeddings( + getAudioTranscriptionAsPlainText( deploymentId: string, - body: EmbeddingsOptions, - options: GetEmbeddingsOptionalParams = { requestOptions: {} }, - ): Promise { - return getEmbeddings(this._client, deploymentId, body, options); + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsPlainTextOptionalParams = { + requestOptions: {}, + }, + ): Promise { + return getAudioTranscriptionAsPlainText( + this._client, + deploymentId, + body, + options, + ); } } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/package.json b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/package.json index add2293a1b..3dae102ff3 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/package.json @@ -13,18 +13,18 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/audio/transcriptions": "./src/api/audio/transcriptions/index.ts", - "./api/audio/translations": "./src/api/audio/translations/index.ts", - "./api/chat/completions": "./src/api/chat/completions/index.ts", - "./api/fineTuning/jobs": "./src/api/fineTuning/jobs/index.ts", - "./api/completions": "./src/api/completions/index.ts", - "./api/edits": "./src/api/edits/index.ts", - "./api/embeddings": "./src/api/embeddings/index.ts", - "./api/files": "./src/api/files/index.ts", - "./api/fineTunes": "./src/api/fineTunes/index.ts", - "./api/models": "./src/api/models/index.ts", + "./api/moderations": "./src/api/moderations/index.ts", "./api/images": "./src/api/images/index.ts", - "./api/moderations": "./src/api/moderations/index.ts" + "./api/models": "./src/api/models/index.ts", + "./api/fineTunes": "./src/api/fineTunes/index.ts", + "./api/files": "./src/api/files/index.ts", + "./api/embeddings": "./src/api/embeddings/index.ts", + "./api/edits": "./src/api/edits/index.ts", + "./api/completions": "./src/api/completions/index.ts", + "./api/fineTuning/jobs": "./src/api/fineTuning/jobs/index.ts", + "./api/chat/completions": "./src/api/chat/completions/index.ts", + "./api/audio/translations": "./src/api/audio/translations/index.ts", + "./api/audio/transcriptions": "./src/api/audio/transcriptions/index.ts" }, "dialects": [ "esm", @@ -114,112 +114,94 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/audio/transcriptions": { - "browser": { - "types": "./dist/browser/api/audio/transcriptions/index.d.ts", - "default": "./dist/browser/api/audio/transcriptions/index.js" - }, - "react-native": { - "types": "./dist/react-native/api/audio/transcriptions/index.d.ts", - "default": "./dist/react-native/api/audio/transcriptions/index.js" - }, - "import": { - "types": "./dist/esm/api/audio/transcriptions/index.d.ts", - "default": "./dist/esm/api/audio/transcriptions/index.js" - }, - "require": { - "types": "./dist/commonjs/api/audio/transcriptions/index.d.ts", - "default": "./dist/commonjs/api/audio/transcriptions/index.js" - } - }, - "./api/audio/translations": { + "./api/moderations": { "browser": { - "types": "./dist/browser/api/audio/translations/index.d.ts", - "default": "./dist/browser/api/audio/translations/index.js" + "types": "./dist/browser/api/moderations/index.d.ts", + "default": "./dist/browser/api/moderations/index.js" }, "react-native": { - "types": "./dist/react-native/api/audio/translations/index.d.ts", - "default": "./dist/react-native/api/audio/translations/index.js" + "types": "./dist/react-native/api/moderations/index.d.ts", + "default": "./dist/react-native/api/moderations/index.js" }, "import": { - "types": "./dist/esm/api/audio/translations/index.d.ts", - "default": "./dist/esm/api/audio/translations/index.js" + "types": "./dist/esm/api/moderations/index.d.ts", + "default": "./dist/esm/api/moderations/index.js" }, "require": { - "types": "./dist/commonjs/api/audio/translations/index.d.ts", - "default": "./dist/commonjs/api/audio/translations/index.js" + "types": "./dist/commonjs/api/moderations/index.d.ts", + "default": "./dist/commonjs/api/moderations/index.js" } }, - "./api/chat/completions": { + "./api/images": { "browser": { - "types": "./dist/browser/api/chat/completions/index.d.ts", - "default": "./dist/browser/api/chat/completions/index.js" + "types": "./dist/browser/api/images/index.d.ts", + "default": "./dist/browser/api/images/index.js" }, "react-native": { - "types": "./dist/react-native/api/chat/completions/index.d.ts", - "default": "./dist/react-native/api/chat/completions/index.js" + "types": "./dist/react-native/api/images/index.d.ts", + "default": "./dist/react-native/api/images/index.js" }, "import": { - "types": "./dist/esm/api/chat/completions/index.d.ts", - "default": "./dist/esm/api/chat/completions/index.js" + "types": "./dist/esm/api/images/index.d.ts", + "default": "./dist/esm/api/images/index.js" }, "require": { - "types": "./dist/commonjs/api/chat/completions/index.d.ts", - "default": "./dist/commonjs/api/chat/completions/index.js" + "types": "./dist/commonjs/api/images/index.d.ts", + "default": "./dist/commonjs/api/images/index.js" } }, - "./api/fineTuning/jobs": { + "./api/models": { "browser": { - "types": "./dist/browser/api/fineTuning/jobs/index.d.ts", - "default": "./dist/browser/api/fineTuning/jobs/index.js" + "types": "./dist/browser/api/models/index.d.ts", + "default": "./dist/browser/api/models/index.js" }, "react-native": { - "types": "./dist/react-native/api/fineTuning/jobs/index.d.ts", - "default": "./dist/react-native/api/fineTuning/jobs/index.js" + "types": "./dist/react-native/api/models/index.d.ts", + "default": "./dist/react-native/api/models/index.js" }, "import": { - "types": "./dist/esm/api/fineTuning/jobs/index.d.ts", - "default": "./dist/esm/api/fineTuning/jobs/index.js" + "types": "./dist/esm/api/models/index.d.ts", + "default": "./dist/esm/api/models/index.js" }, "require": { - "types": "./dist/commonjs/api/fineTuning/jobs/index.d.ts", - "default": "./dist/commonjs/api/fineTuning/jobs/index.js" + "types": "./dist/commonjs/api/models/index.d.ts", + "default": "./dist/commonjs/api/models/index.js" } }, - "./api/completions": { + "./api/fineTunes": { "browser": { - "types": "./dist/browser/api/completions/index.d.ts", - "default": "./dist/browser/api/completions/index.js" + "types": "./dist/browser/api/fineTunes/index.d.ts", + "default": "./dist/browser/api/fineTunes/index.js" }, "react-native": { - "types": "./dist/react-native/api/completions/index.d.ts", - "default": "./dist/react-native/api/completions/index.js" + "types": "./dist/react-native/api/fineTunes/index.d.ts", + "default": "./dist/react-native/api/fineTunes/index.js" }, "import": { - "types": "./dist/esm/api/completions/index.d.ts", - "default": "./dist/esm/api/completions/index.js" + "types": "./dist/esm/api/fineTunes/index.d.ts", + "default": "./dist/esm/api/fineTunes/index.js" }, "require": { - "types": "./dist/commonjs/api/completions/index.d.ts", - "default": "./dist/commonjs/api/completions/index.js" + "types": "./dist/commonjs/api/fineTunes/index.d.ts", + "default": "./dist/commonjs/api/fineTunes/index.js" } }, - "./api/edits": { + "./api/files": { "browser": { - "types": "./dist/browser/api/edits/index.d.ts", - "default": "./dist/browser/api/edits/index.js" + "types": "./dist/browser/api/files/index.d.ts", + "default": "./dist/browser/api/files/index.js" }, "react-native": { - "types": "./dist/react-native/api/edits/index.d.ts", - "default": "./dist/react-native/api/edits/index.js" + "types": "./dist/react-native/api/files/index.d.ts", + "default": "./dist/react-native/api/files/index.js" }, "import": { - "types": "./dist/esm/api/edits/index.d.ts", - "default": "./dist/esm/api/edits/index.js" + "types": "./dist/esm/api/files/index.d.ts", + "default": "./dist/esm/api/files/index.js" }, "require": { - "types": "./dist/commonjs/api/edits/index.d.ts", - "default": "./dist/commonjs/api/edits/index.js" + "types": "./dist/commonjs/api/files/index.d.ts", + "default": "./dist/commonjs/api/files/index.js" } }, "./api/embeddings": { @@ -240,94 +222,112 @@ "default": "./dist/commonjs/api/embeddings/index.js" } }, - "./api/files": { + "./api/edits": { "browser": { - "types": "./dist/browser/api/files/index.d.ts", - "default": "./dist/browser/api/files/index.js" + "types": "./dist/browser/api/edits/index.d.ts", + "default": "./dist/browser/api/edits/index.js" }, "react-native": { - "types": "./dist/react-native/api/files/index.d.ts", - "default": "./dist/react-native/api/files/index.js" + "types": "./dist/react-native/api/edits/index.d.ts", + "default": "./dist/react-native/api/edits/index.js" }, "import": { - "types": "./dist/esm/api/files/index.d.ts", - "default": "./dist/esm/api/files/index.js" + "types": "./dist/esm/api/edits/index.d.ts", + "default": "./dist/esm/api/edits/index.js" }, "require": { - "types": "./dist/commonjs/api/files/index.d.ts", - "default": "./dist/commonjs/api/files/index.js" + "types": "./dist/commonjs/api/edits/index.d.ts", + "default": "./dist/commonjs/api/edits/index.js" } }, - "./api/fineTunes": { + "./api/completions": { "browser": { - "types": "./dist/browser/api/fineTunes/index.d.ts", - "default": "./dist/browser/api/fineTunes/index.js" + "types": "./dist/browser/api/completions/index.d.ts", + "default": "./dist/browser/api/completions/index.js" }, "react-native": { - "types": "./dist/react-native/api/fineTunes/index.d.ts", - "default": "./dist/react-native/api/fineTunes/index.js" + "types": "./dist/react-native/api/completions/index.d.ts", + "default": "./dist/react-native/api/completions/index.js" }, "import": { - "types": "./dist/esm/api/fineTunes/index.d.ts", - "default": "./dist/esm/api/fineTunes/index.js" + "types": "./dist/esm/api/completions/index.d.ts", + "default": "./dist/esm/api/completions/index.js" }, "require": { - "types": "./dist/commonjs/api/fineTunes/index.d.ts", - "default": "./dist/commonjs/api/fineTunes/index.js" + "types": "./dist/commonjs/api/completions/index.d.ts", + "default": "./dist/commonjs/api/completions/index.js" } }, - "./api/models": { + "./api/fineTuning/jobs": { "browser": { - "types": "./dist/browser/api/models/index.d.ts", - "default": "./dist/browser/api/models/index.js" + "types": "./dist/browser/api/fineTuning/jobs/index.d.ts", + "default": "./dist/browser/api/fineTuning/jobs/index.js" }, "react-native": { - "types": "./dist/react-native/api/models/index.d.ts", - "default": "./dist/react-native/api/models/index.js" + "types": "./dist/react-native/api/fineTuning/jobs/index.d.ts", + "default": "./dist/react-native/api/fineTuning/jobs/index.js" }, "import": { - "types": "./dist/esm/api/models/index.d.ts", - "default": "./dist/esm/api/models/index.js" + "types": "./dist/esm/api/fineTuning/jobs/index.d.ts", + "default": "./dist/esm/api/fineTuning/jobs/index.js" }, "require": { - "types": "./dist/commonjs/api/models/index.d.ts", - "default": "./dist/commonjs/api/models/index.js" + "types": "./dist/commonjs/api/fineTuning/jobs/index.d.ts", + "default": "./dist/commonjs/api/fineTuning/jobs/index.js" } }, - "./api/images": { + "./api/chat/completions": { "browser": { - "types": "./dist/browser/api/images/index.d.ts", - "default": "./dist/browser/api/images/index.js" + "types": "./dist/browser/api/chat/completions/index.d.ts", + "default": "./dist/browser/api/chat/completions/index.js" }, "react-native": { - "types": "./dist/react-native/api/images/index.d.ts", - "default": "./dist/react-native/api/images/index.js" + "types": "./dist/react-native/api/chat/completions/index.d.ts", + "default": "./dist/react-native/api/chat/completions/index.js" }, "import": { - "types": "./dist/esm/api/images/index.d.ts", - "default": "./dist/esm/api/images/index.js" + "types": "./dist/esm/api/chat/completions/index.d.ts", + "default": "./dist/esm/api/chat/completions/index.js" }, "require": { - "types": "./dist/commonjs/api/images/index.d.ts", - "default": "./dist/commonjs/api/images/index.js" + "types": "./dist/commonjs/api/chat/completions/index.d.ts", + "default": "./dist/commonjs/api/chat/completions/index.js" } }, - "./api/moderations": { + "./api/audio/translations": { "browser": { - "types": "./dist/browser/api/moderations/index.d.ts", - "default": "./dist/browser/api/moderations/index.js" + "types": "./dist/browser/api/audio/translations/index.d.ts", + "default": "./dist/browser/api/audio/translations/index.js" }, "react-native": { - "types": "./dist/react-native/api/moderations/index.d.ts", - "default": "./dist/react-native/api/moderations/index.js" + "types": "./dist/react-native/api/audio/translations/index.d.ts", + "default": "./dist/react-native/api/audio/translations/index.js" }, "import": { - "types": "./dist/esm/api/moderations/index.d.ts", - "default": "./dist/esm/api/moderations/index.js" + "types": "./dist/esm/api/audio/translations/index.d.ts", + "default": "./dist/esm/api/audio/translations/index.js" }, "require": { - "types": "./dist/commonjs/api/moderations/index.d.ts", - "default": "./dist/commonjs/api/moderations/index.js" + "types": "./dist/commonjs/api/audio/translations/index.d.ts", + "default": "./dist/commonjs/api/audio/translations/index.js" + } + }, + "./api/audio/transcriptions": { + "browser": { + "types": "./dist/browser/api/audio/transcriptions/index.d.ts", + "default": "./dist/browser/api/audio/transcriptions/index.js" + }, + "react-native": { + "types": "./dist/react-native/api/audio/transcriptions/index.d.ts", + "default": "./dist/react-native/api/audio/transcriptions/index.js" + }, + "import": { + "types": "./dist/esm/api/audio/transcriptions/index.d.ts", + "default": "./dist/esm/api/audio/transcriptions/index.js" + }, + "require": { + "types": "./dist/commonjs/api/audio/transcriptions/index.d.ts", + "default": "./dist/commonjs/api/audio/transcriptions/index.js" } } }, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md index 7c737452c6..8f54a36e38 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/review/openai-non-branded.api.md @@ -19,8 +19,6 @@ export interface AudioOperations { // @public export interface AudioTranscriptionsCreateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -31,8 +29,6 @@ export interface AudioTranscriptionsOperations { // @public export interface AudioTranslationsCreateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -413,8 +409,6 @@ export interface EmbeddingsOperations { // @public export interface FilesCreateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -607,8 +601,6 @@ export interface Image { // @public export interface ImagesCreateEditOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public @@ -617,8 +609,6 @@ export interface ImagesCreateOptionalParams extends OperationOptions { // @public export interface ImagesCreateVariationOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts index 838d4b582a..4fa70bbb6a 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/transcriptions/index.ts @@ -26,7 +26,11 @@ export function _createSend( .path("/audio/transcriptions") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createTranscriptionRequestSerializer(audio), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts index 3ea71814e4..621c6a3a6c 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/audio/translations/index.ts @@ -26,7 +26,11 @@ export function _createSend( .path("/audio/translations") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createTranslationRequestSerializer(audio), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts index 9c44d2c245..b9fd1eb069 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/chat/completions/index.ts @@ -26,6 +26,11 @@ export function _createSend( .path("/chat/completions") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createChatCompletionRequestSerializer(body), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts index ae8fa55f21..feda7690d9 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/completions/index.ts @@ -26,6 +26,11 @@ export function _createSend( .path("/completions") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createCompletionRequestSerializer(body), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts index 732bc9d9a8..35227cbc86 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/edits/index.ts @@ -26,6 +26,11 @@ export function _createSend( .path("/edits") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createEditRequestSerializer(edit), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts index 091d9c344d..458506734e 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/embeddings/index.ts @@ -26,6 +26,11 @@ export function _createSend( .path("/embeddings") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createEmbeddingRequestSerializer(embedding), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts index 8b00a519c6..50184f9c4d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/files/index.ts @@ -25,66 +25,81 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _listSend( +export function _downloadSend( context: Client, - options: FilesListOptionalParams = { requestOptions: {} }, + fileId: string, + options: FilesDownloadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/files/files/{file_id}/content", fileId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _listDeserialize( +export async function _downloadDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFilesResponseDeserializer(result.body); + return result.body; } -export async function list( +export async function download( context: Client, - options: FilesListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + fileId: string, + options: FilesDownloadOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _downloadSend(context, fileId, options); + return _downloadDeserialize(result); } -export function _createSend( +export function _$deleteSend( context: Client, - file: CreateFileRequest, - options: FilesCreateOptionalParams = { requestOptions: {} }, + fileId: string, + options: FilesDeleteOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files") - .post({ + .path("/files/files/{file_id}", fileId) + .delete({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: createFileRequestSerializer(file), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createDeserialize( +export async function _$deleteDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return openAIFileDeserializer(result.body); + return deleteFileResponseDeserializer(result.body); } -export async function create( +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( context: Client, - file: CreateFileRequest, - options: FilesCreateOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _createSend(context, file, options); - return _createDeserialize(result); + fileId: string, + options: FilesDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend(context, fileId, options); + return _$deleteDeserialize(result); } export function _retrieveSend( @@ -94,7 +109,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/files/files/{file_id}", fileId) - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -117,67 +138,74 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _$deleteSend( +export function _createSend( context: Client, - fileId: string, - options: FilesDeleteOptionalParams = { requestOptions: {} }, + file: CreateFileRequest, + options: FilesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/files/{file_id}", fileId) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/files") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createFileRequestSerializer(file), + }); } -export async function _$deleteDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return deleteFileResponseDeserializer(result.body); + return openAIFileDeserializer(result.body); } -/** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ -export async function $delete( +export async function create( context: Client, - fileId: string, - options: FilesDeleteOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _$deleteSend(context, fileId, options); - return _$deleteDeserialize(result); + file: CreateFileRequest, + options: FilesCreateOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _createSend(context, file, options); + return _createDeserialize(result); } -export function _downloadSend( +export function _listSend( context: Client, - fileId: string, - options: FilesDownloadOptionalParams = { requestOptions: {} }, + options: FilesListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/files/files/{file_id}/content", fileId) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/files") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _downloadDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return result.body; + return listFilesResponseDeserializer(result.body); } -export async function download( +export async function list( context: Client, - fileId: string, - options: FilesDownloadOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _downloadSend(context, fileId, options); - return _downloadDeserialize(result); + options: FilesListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts index 75574deb85..46a98e774c 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTunes/index.ts @@ -25,20 +25,23 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _createSend( +export function _cancelSend( context: Client, - fineTune: CreateFineTuneRequest, - options: FineTunesCreateOptionalParams = { requestOptions: {} }, + fineTuneId: string, + options: FineTunesCancelOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes") + .path("/fine-tunes/{fine_tune_id}/cancel", fineTuneId) .post({ ...operationOptionsToRequestParameters(options), - body: createFineTuneRequestSerializer(fineTune), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createDeserialize( +export async function _cancelDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -49,41 +52,50 @@ export async function _createDeserialize( return fineTuneDeserializer(result.body); } -export async function create( +export async function cancel( context: Client, - fineTune: CreateFineTuneRequest, - options: FineTunesCreateOptionalParams = { requestOptions: {} }, + fineTuneId: string, + options: FineTunesCancelOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createSend(context, fineTune, options); - return _createDeserialize(result); + const result = await _cancelSend(context, fineTuneId, options); + return _cancelDeserialize(result); } -export function _listSend( +export function _listEventsSend( context: Client, - options: FineTunesListOptionalParams = { requestOptions: {} }, + fineTuneId: string, + options: FineTunesListEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/fine-tunes/{fine_tune_id}/events", fineTuneId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { stream: options?.stream }, + }); } -export async function _listDeserialize( +export async function _listEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFineTunesResponseDeserializer(result.body); + return listFineTuneEventsResponseDeserializer(result.body); } -export async function list( +export async function listEvents( context: Client, - options: FineTunesListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + fineTuneId: string, + options: FineTunesListEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listEventsSend(context, fineTuneId, options); + return _listEventsDeserialize(result); } export function _retrieveSend( @@ -93,7 +105,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/fine-tunes/{fine_tune_id}", fineTuneId) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -116,50 +134,59 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _listEventsSend( +export function _listSend( context: Client, - fineTuneId: string, - options: FineTunesListEventsOptionalParams = { requestOptions: {} }, + options: FineTunesListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes/{fine_tune_id}/events", fineTuneId) + .path("/fine-tunes") .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { stream: options?.stream }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _listEventsDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFineTuneEventsResponseDeserializer(result.body); + return listFineTunesResponseDeserializer(result.body); } -export async function listEvents( +export async function list( context: Client, - fineTuneId: string, - options: FineTunesListEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listEventsSend(context, fineTuneId, options); - return _listEventsDeserialize(result); + options: FineTunesListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } -export function _cancelSend( +export function _createSend( context: Client, - fineTuneId: string, - options: FineTunesCancelOptionalParams = { requestOptions: {} }, + fineTune: CreateFineTuneRequest, + options: FineTunesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine-tunes/{fine_tune_id}/cancel", fineTuneId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/fine-tunes") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createFineTuneRequestSerializer(fineTune), + }); } -export async function _cancelDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -170,11 +197,11 @@ export async function _cancelDeserialize( return fineTuneDeserializer(result.body); } -export async function cancel( +export async function create( context: Client, - fineTuneId: string, - options: FineTunesCancelOptionalParams = { requestOptions: {} }, + fineTune: CreateFineTuneRequest, + options: FineTunesCreateOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _cancelSend(context, fineTuneId, options); - return _cancelDeserialize(result); + const result = await _createSend(context, fineTune, options); + return _createDeserialize(result); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts index 868832e3c3..3a711104a9 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/fineTuning/jobs/index.ts @@ -25,20 +25,23 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _createSend( +export function _cancelSend( context: Client, - job: CreateFineTuningJobRequest, - options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, + fineTuningJobId: string, + options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs") + .path("/fine_tuning/jobs/{fine_tuning_job_id}/cancel", fineTuningJobId) .post({ ...operationOptionsToRequestParameters(options), - body: createFineTuningJobRequestSerializer(job), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createDeserialize( +export async function _cancelDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -49,52 +52,50 @@ export async function _createDeserialize( return fineTuningJobDeserializer(result.body); } -/** - * Creates a job that fine-tunes a specified model from a given dataset. - * - * Response includes details of the enqueued job including job status and the name of the - * fine-tuned models once complete. - * - * [Learn more about fine-tuning](/docs/guides/fine-tuning) - */ -export async function create( +export async function cancel( context: Client, - job: CreateFineTuningJobRequest, - options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, + fineTuningJobId: string, + options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createSend(context, job, options); - return _createDeserialize(result); + const result = await _cancelSend(context, fineTuningJobId, options); + return _cancelDeserialize(result); } -export function _listSend( +export function _listEventsSend( context: Client, - options: FineTuningJobsListOptionalParams = { requestOptions: {} }, + fineTuningJobId: string, + options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs") + .path("/fine_tuning/jobs/{fine_tuning_job_id}/events", fineTuningJobId) .get({ ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { after: options?.after, limit: options?.limit }, }); } -export async function _listDeserialize( +export async function _listEventsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listPaginatedFineTuningJobsResponseDeserializer(result.body); + return listFineTuningJobEventsResponseDeserializer(result.body); } -export async function list( +export async function listEvents( context: Client, - options: FineTuningJobsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + fineTuningJobId: string, + options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listEventsSend(context, fineTuningJobId, options); + return _listEventsDeserialize(result); } export function _retrieveSend( @@ -104,7 +105,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/fine_tuning/jobs/{fine_tuning_job_id}", fineTuningJobId) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -127,50 +134,60 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _listEventsSend( +export function _listSend( context: Client, - fineTuningJobId: string, - options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, + options: FineTuningJobsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs/{fine_tuning_job_id}/events", fineTuningJobId) + .path("/fine_tuning/jobs") .get({ ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { after: options?.after, limit: options?.limit }, }); } -export async function _listEventsDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listFineTuningJobEventsResponseDeserializer(result.body); + return listPaginatedFineTuningJobsResponseDeserializer(result.body); } -export async function listEvents( +export async function list( context: Client, - fineTuningJobId: string, - options: FineTuningJobsListEventsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listEventsSend(context, fineTuningJobId, options); - return _listEventsDeserialize(result); + options: FineTuningJobsListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } -export function _cancelSend( +export function _createSend( context: Client, - fineTuningJobId: string, - options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, + job: CreateFineTuningJobRequest, + options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/fine_tuning/jobs/{fine_tuning_job_id}/cancel", fineTuningJobId) - .post({ ...operationOptionsToRequestParameters(options) }); + .path("/fine_tuning/jobs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createFineTuningJobRequestSerializer(job), + }); } -export async function _cancelDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -181,11 +198,19 @@ export async function _cancelDeserialize( return fineTuningJobDeserializer(result.body); } -export async function cancel( +/** + * Creates a job that fine-tunes a specified model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name of the + * fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/fine-tuning) + */ +export async function create( context: Client, - fineTuningJobId: string, - options: FineTuningJobsCancelOptionalParams = { requestOptions: {} }, + job: CreateFineTuningJobRequest, + options: FineTuningJobsCreateOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _cancelSend(context, fineTuningJobId, options); - return _cancelDeserialize(result); + const result = await _createSend(context, job, options); + return _createDeserialize(result); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts index 66640eae39..5948ebf223 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/images/index.ts @@ -23,20 +23,25 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _createSend( +export function _createVariationSend( context: Client, - image: CreateImageRequest, - options: ImagesCreateOptionalParams = { requestOptions: {} }, + image: CreateImageVariationRequest, + options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/images/generations") + .path("/images/variations") .post({ ...operationOptionsToRequestParameters(options), - body: createImageRequestSerializer(image), + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createImageVariationRequestSerializer(image), }); } -export async function _createDeserialize( +export async function _createVariationDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -47,13 +52,13 @@ export async function _createDeserialize( return imagesResponseDeserializer(result.body); } -export async function create( +export async function createVariation( context: Client, - image: CreateImageRequest, - options: ImagesCreateOptionalParams = { requestOptions: {} }, + image: CreateImageVariationRequest, + options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createSend(context, image, options); - return _createDeserialize(result); + const result = await _createVariationSend(context, image, options); + return _createVariationDeserialize(result); } export function _createEditSend( @@ -65,7 +70,11 @@ export function _createEditSend( .path("/images/edits") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", + contentType: "multipart/form-data", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createImageEditRequestSerializer(image), }); } @@ -90,21 +99,25 @@ export async function createEdit( return _createEditDeserialize(result); } -export function _createVariationSend( +export function _createSend( context: Client, - image: CreateImageVariationRequest, - options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, + image: CreateImageRequest, + options: ImagesCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/images/variations") + .path("/images/generations") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: createImageVariationRequestSerializer(image), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: createImageRequestSerializer(image), }); } -export async function _createVariationDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; @@ -115,11 +128,11 @@ export async function _createVariationDeserialize( return imagesResponseDeserializer(result.body); } -export async function createVariation( +export async function create( context: Client, - image: CreateImageVariationRequest, - options: ImagesCreateVariationOptionalParams = { requestOptions: {} }, + image: CreateImageRequest, + options: ImagesCreateOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _createVariationSend(context, image, options); - return _createVariationDeserialize(result); + const result = await _createSend(context, image, options); + return _createDeserialize(result); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts index 0676bdf731..439f5da06c 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/index.ts @@ -6,32 +6,32 @@ export { OpenAIClientOptionalParams, } from "./openAIContext.js"; export { - AudioTranscriptionsCreateOptionalParams, - AudioTranslationsCreateOptionalParams, - ChatCompletionsCreateOptionalParams, - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, - CompletionsCreateOptionalParams, - EditsCreateOptionalParams, - EmbeddingsCreateOptionalParams, - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, ModerationsCreateOptionalParams, + ImagesCreateVariationOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, + ModelsDeleteOptionalParams, + ModelsRetrieveOptionalParams, + ModelsListOptionalParams, + FineTunesCancelOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListOptionalParams, + FineTunesCreateOptionalParams, + FilesDownloadOptionalParams, + FilesDeleteOptionalParams, + FilesRetrieveOptionalParams, + FilesCreateOptionalParams, + FilesListOptionalParams, + EmbeddingsCreateOptionalParams, + EditsCreateOptionalParams, + CompletionsCreateOptionalParams, + FineTuningJobsCancelOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsCreateOptionalParams, + ChatCompletionsCreateOptionalParams, + AudioTranslationsCreateOptionalParams, + AudioTranscriptionsCreateOptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts index ac1bd7ae38..3e03c2837c 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/models/index.ts @@ -21,32 +21,45 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _listSend( +export function _$deleteSend( context: Client, - options: ModelsListOptionalParams = { requestOptions: {} }, + model: string, + options: ModelsDeleteOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/models") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/models/{model}", model) + .delete({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _listDeserialize( +export async function _$deleteDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return listModelsResponseDeserializer(result.body); + return deleteModelResponseDeserializer(result.body); } -export async function list( +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( context: Client, - options: ModelsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + model: string, + options: ModelsDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend(context, model, options); + return _$deleteDeserialize(result); } export function _retrieveSend( @@ -56,7 +69,13 @@ export function _retrieveSend( ): StreamableMethod { return context .path("/models/{model}", model) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _retrieveDeserialize( @@ -79,37 +98,36 @@ export async function retrieve( return _retrieveDeserialize(result); } -export function _$deleteSend( +export function _listSend( context: Client, - model: string, - options: ModelsDeleteOptionalParams = { requestOptions: {} }, + options: ModelsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/models/{model}", model) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/models") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _$deleteDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return deleteModelResponseDeserializer(result.body); + return listModelsResponseDeserializer(result.body); } -/** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ -export async function $delete( +export async function list( context: Client, - model: string, - options: ModelsDeleteOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _$deleteSend(context, model, options); - return _$deleteDeserialize(result); + options: ModelsListOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listSend(context, options); + return _listDeserialize(result); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts index db0953fec8..5e216ad436 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/moderations/index.ts @@ -26,6 +26,11 @@ export function _createSend( .path("/moderations") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: createModerationRequestSerializer(content), }); } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts index 542614a006..826fd72f7d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/openAIContext.ts @@ -19,7 +19,7 @@ export function createOpenAI( credential: KeyCredential, options: OpenAIClientOptionalParams = {}, ): OpenAIContext { - const endpointUrl = options.endpoint ?? `https://api.openai.com/v1`; + const endpointUrl = options.endpoint ?? "https://api.openai.com/v1"; const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-openai-non-branded/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/options.ts index 74f7da4d43..b49d3a0dee 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/api/options.ts @@ -3,120 +3,110 @@ import { OperationOptions } from "@typespec/ts-http-runtime"; /** Optional parameters. */ -export interface AudioTranscriptionsCreateOptionalParams - extends OperationOptions { - contentType?: string; -} +export interface ModerationsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface AudioTranslationsCreateOptionalParams - extends OperationOptions { - contentType?: string; -} +export interface ImagesCreateVariationOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ChatCompletionsCreateOptionalParams extends OperationOptions {} +export interface ImagesCreateEditOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsCreateOptionalParams extends OperationOptions {} +export interface ImagesCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsListOptionalParams extends OperationOptions { - /** Identifier for the last job from the previous pagination request. */ - after?: string; - /** Number of fine-tuning jobs to retrieve. */ - limit?: number; -} +export interface ModelsDeleteOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsRetrieveOptionalParams - extends OperationOptions {} +export interface ModelsRetrieveOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsListEventsOptionalParams - extends OperationOptions { - /** Identifier for the last event from the previous pagination request. */ - after?: string; - /** Number of events to retrieve. */ - limit?: number; -} +export interface ModelsListOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTuningJobsCancelOptionalParams extends OperationOptions {} +export interface FineTunesCancelOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface CompletionsCreateOptionalParams extends OperationOptions {} +export interface FineTunesListEventsOptionalParams extends OperationOptions { + /** + * Whether to stream events for the fine-tune job. If set to true, events will be sent as + * data-only + * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + * as they become available. The stream will terminate with a `data: [DONE]` message when the + * job is finished (succeeded, cancelled, or failed). + * + * If set to false, only events generated so far will be returned. + */ + stream?: boolean; +} /** Optional parameters. */ -export interface EditsCreateOptionalParams extends OperationOptions {} +export interface FineTunesRetrieveOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface EmbeddingsCreateOptionalParams extends OperationOptions {} +export interface FineTunesListOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesListOptionalParams extends OperationOptions {} +export interface FineTunesCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesCreateOptionalParams extends OperationOptions { - contentType?: string; -} +export interface FilesDownloadOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesRetrieveOptionalParams extends OperationOptions {} +export interface FilesDeleteOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesDeleteOptionalParams extends OperationOptions {} +export interface FilesRetrieveOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FilesDownloadOptionalParams extends OperationOptions {} +export interface FilesCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesCreateOptionalParams extends OperationOptions {} +export interface FilesListOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesListOptionalParams extends OperationOptions {} +export interface EmbeddingsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesRetrieveOptionalParams extends OperationOptions {} +export interface EditsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesListEventsOptionalParams extends OperationOptions { - /** - * Whether to stream events for the fine-tune job. If set to true, events will be sent as - * data-only - * [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - * as they become available. The stream will terminate with a `data: [DONE]` message when the - * job is finished (succeeded, cancelled, or failed). - * - * If set to false, only events generated so far will be returned. - */ - stream?: boolean; -} +export interface CompletionsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface FineTunesCancelOptionalParams extends OperationOptions {} +export interface FineTuningJobsCancelOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ModelsListOptionalParams extends OperationOptions {} +export interface FineTuningJobsListEventsOptionalParams + extends OperationOptions { + /** Identifier for the last event from the previous pagination request. */ + after?: string; + /** Number of events to retrieve. */ + limit?: number; +} /** Optional parameters. */ -export interface ModelsRetrieveOptionalParams extends OperationOptions {} +export interface FineTuningJobsRetrieveOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ModelsDeleteOptionalParams extends OperationOptions {} +export interface FineTuningJobsListOptionalParams extends OperationOptions { + /** Identifier for the last job from the previous pagination request. */ + after?: string; + /** Number of fine-tuning jobs to retrieve. */ + limit?: number; +} /** Optional parameters. */ -export interface ImagesCreateOptionalParams extends OperationOptions {} +export interface FineTuningJobsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ImagesCreateEditOptionalParams extends OperationOptions { - contentType?: string; -} +export interface ChatCompletionsCreateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ImagesCreateVariationOptionalParams extends OperationOptions { - contentType?: string; -} +export interface AudioTranslationsCreateOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface ModerationsCreateOptionalParams extends OperationOptions {} +export interface AudioTranscriptionsCreateOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts index 9273df0eda..f41cb3f14d 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/audio/index.ts @@ -12,13 +12,13 @@ import { /** Interface representing a Audio operations. */ export interface AudioOperations { - transcriptions: AudioTranscriptionsOperations; translations: AudioTranslationsOperations; + transcriptions: AudioTranscriptionsOperations; } export function getAudioOperations(context: OpenAIContext): AudioOperations { return { - transcriptions: getAudioTranscriptionsOperations(context), translations: getAudioTranslationsOperations(context), + transcriptions: getAudioTranscriptionsOperations(context), }; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts index 3b6ba9fabb..1e672fd0c5 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/files/index.ts @@ -2,11 +2,11 @@ import { OpenAIContext } from "../../api/openAIContext.js"; import { - list, - create, - retrieve, - $delete, download, + $delete, + retrieve, + create, + list, } from "../../api/files/index.js"; import { OpenAIFile, @@ -15,24 +15,19 @@ import { DeleteFileResponse, } from "../../models/models.js"; import { - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, FilesDownloadOptionalParams, + FilesDeleteOptionalParams, + FilesRetrieveOptionalParams, + FilesCreateOptionalParams, + FilesListOptionalParams, } from "../../api/options.js"; /** Interface representing a Files operations. */ export interface FilesOperations { - list: (options?: FilesListOptionalParams) => Promise; - create: ( - file: CreateFileRequest, - options?: FilesCreateOptionalParams, - ) => Promise; - retrieve: ( + download: ( fileId: string, - options?: FilesRetrieveOptionalParams, - ) => Promise; + options?: FilesDownloadOptionalParams, + ) => Promise; /** * @fixme delete is a reserved word that cannot be used as an operation name. * Please add @clientName("clientName") or @clientName("", "javascript") @@ -42,23 +37,28 @@ export interface FilesOperations { fileId: string, options?: FilesDeleteOptionalParams, ) => Promise; - download: ( + retrieve: ( fileId: string, - options?: FilesDownloadOptionalParams, - ) => Promise; + options?: FilesRetrieveOptionalParams, + ) => Promise; + create: ( + file: CreateFileRequest, + options?: FilesCreateOptionalParams, + ) => Promise; + list: (options?: FilesListOptionalParams) => Promise; } export function getFiles(context: OpenAIContext) { return { - list: (options?: FilesListOptionalParams) => list(context, options), - create: (file: CreateFileRequest, options?: FilesCreateOptionalParams) => - create(context, file, options), - retrieve: (fileId: string, options?: FilesRetrieveOptionalParams) => - retrieve(context, fileId, options), - delete: (fileId: string, options?: FilesDeleteOptionalParams) => - $delete(context, fileId, options), download: (fileId: string, options?: FilesDownloadOptionalParams) => download(context, fileId, options), + delete: (fileId: string, options?: FilesDeleteOptionalParams) => + $delete(context, fileId, options), + retrieve: (fileId: string, options?: FilesRetrieveOptionalParams) => + retrieve(context, fileId, options), + create: (file: CreateFileRequest, options?: FilesCreateOptionalParams) => + create(context, file, options), + list: (options?: FilesListOptionalParams) => list(context, options), }; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts index bed4951bbc..4398eb0dee 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTunes/index.ts @@ -2,11 +2,11 @@ import { OpenAIContext } from "../../api/openAIContext.js"; import { - create, - list, - retrieve, - listEvents, cancel, + listEvents, + retrieve, + list, + create, } from "../../api/fineTunes/index.js"; import { CreateFineTuneRequest, @@ -15,51 +15,51 @@ import { ListFineTuneEventsResponse, } from "../../models/models.js"; import { - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, FineTunesCancelOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListOptionalParams, + FineTunesCreateOptionalParams, } from "../../api/options.js"; /** Interface representing a FineTunes operations. */ export interface FineTunesOperations { - create: ( - fineTune: CreateFineTuneRequest, - options?: FineTunesCreateOptionalParams, - ) => Promise; - list: ( - options?: FineTunesListOptionalParams, - ) => Promise; - retrieve: ( + cancel: ( fineTuneId: string, - options?: FineTunesRetrieveOptionalParams, + options?: FineTunesCancelOptionalParams, ) => Promise; listEvents: ( fineTuneId: string, options?: FineTunesListEventsOptionalParams, ) => Promise; - cancel: ( + retrieve: ( fineTuneId: string, - options?: FineTunesCancelOptionalParams, + options?: FineTunesRetrieveOptionalParams, + ) => Promise; + list: ( + options?: FineTunesListOptionalParams, + ) => Promise; + create: ( + fineTune: CreateFineTuneRequest, + options?: FineTunesCreateOptionalParams, ) => Promise; } export function getFineTunes(context: OpenAIContext) { return { - create: ( - fineTune: CreateFineTuneRequest, - options?: FineTunesCreateOptionalParams, - ) => create(context, fineTune, options), - list: (options?: FineTunesListOptionalParams) => list(context, options), - retrieve: (fineTuneId: string, options?: FineTunesRetrieveOptionalParams) => - retrieve(context, fineTuneId, options), + cancel: (fineTuneId: string, options?: FineTunesCancelOptionalParams) => + cancel(context, fineTuneId, options), listEvents: ( fineTuneId: string, options?: FineTunesListEventsOptionalParams, ) => listEvents(context, fineTuneId, options), - cancel: (fineTuneId: string, options?: FineTunesCancelOptionalParams) => - cancel(context, fineTuneId, options), + retrieve: (fineTuneId: string, options?: FineTunesRetrieveOptionalParams) => + retrieve(context, fineTuneId, options), + list: (options?: FineTunesListOptionalParams) => list(context, options), + create: ( + fineTune: CreateFineTuneRequest, + options?: FineTunesCreateOptionalParams, + ) => create(context, fineTune, options), }; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts index b6f4048954..4f7c0c6b31 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/fineTuning/jobs/index.ts @@ -2,11 +2,11 @@ import { OpenAIContext } from "../../../api/openAIContext.js"; import { - create, - list, - retrieve, - listEvents, cancel, + listEvents, + retrieve, + list, + create, } from "../../../api/fineTuning/jobs/index.js"; import { CreateFineTuningJobRequest, @@ -15,15 +15,30 @@ import { ListFineTuningJobEventsResponse, } from "../../../models/models.js"; import { - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, FineTuningJobsCancelOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsCreateOptionalParams, } from "../../../api/options.js"; /** Interface representing a FineTuningJobs operations. */ export interface FineTuningJobsOperations { + cancel: ( + fineTuningJobId: string, + options?: FineTuningJobsCancelOptionalParams, + ) => Promise; + listEvents: ( + fineTuningJobId: string, + options?: FineTuningJobsListEventsOptionalParams, + ) => Promise; + retrieve: ( + fineTuningJobId: string, + options?: FineTuningJobsRetrieveOptionalParams, + ) => Promise; + list: ( + options?: FineTuningJobsListOptionalParams, + ) => Promise; /** * Creates a job that fine-tunes a specified model from a given dataset. * @@ -36,43 +51,28 @@ export interface FineTuningJobsOperations { job: CreateFineTuningJobRequest, options?: FineTuningJobsCreateOptionalParams, ) => Promise; - list: ( - options?: FineTuningJobsListOptionalParams, - ) => Promise; - retrieve: ( - fineTuningJobId: string, - options?: FineTuningJobsRetrieveOptionalParams, - ) => Promise; - listEvents: ( - fineTuningJobId: string, - options?: FineTuningJobsListEventsOptionalParams, - ) => Promise; - cancel: ( - fineTuningJobId: string, - options?: FineTuningJobsCancelOptionalParams, - ) => Promise; } export function getFineTuningJobs(context: OpenAIContext) { return { - create: ( - job: CreateFineTuningJobRequest, - options?: FineTuningJobsCreateOptionalParams, - ) => create(context, job, options), - list: (options?: FineTuningJobsListOptionalParams) => - list(context, options), - retrieve: ( + cancel: ( fineTuningJobId: string, - options?: FineTuningJobsRetrieveOptionalParams, - ) => retrieve(context, fineTuningJobId, options), + options?: FineTuningJobsCancelOptionalParams, + ) => cancel(context, fineTuningJobId, options), listEvents: ( fineTuningJobId: string, options?: FineTuningJobsListEventsOptionalParams, ) => listEvents(context, fineTuningJobId, options), - cancel: ( + retrieve: ( fineTuningJobId: string, - options?: FineTuningJobsCancelOptionalParams, - ) => cancel(context, fineTuningJobId, options), + options?: FineTuningJobsRetrieveOptionalParams, + ) => retrieve(context, fineTuningJobId, options), + list: (options?: FineTuningJobsListOptionalParams) => + list(context, options), + create: ( + job: CreateFineTuningJobRequest, + options?: FineTuningJobsCreateOptionalParams, + ) => create(context, job, options), }; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts index fe1069ee65..729687dfc9 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/images/index.ts @@ -1,7 +1,7 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { create, createEdit, createVariation } from "../../api/images/index.js"; +import { createVariation, createEdit, create } from "../../api/images/index.js"; import { CreateImageRequest, ImagesResponse, @@ -9,39 +9,39 @@ import { CreateImageVariationRequest, } from "../../models/models.js"; import { - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, ImagesCreateVariationOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, } from "../../api/options.js"; /** Interface representing a Images operations. */ export interface ImagesOperations { - create: ( - image: CreateImageRequest, - options?: ImagesCreateOptionalParams, + createVariation: ( + image: CreateImageVariationRequest, + options?: ImagesCreateVariationOptionalParams, ) => Promise; createEdit: ( image: CreateImageEditRequest, options?: ImagesCreateEditOptionalParams, ) => Promise; - createVariation: ( - image: CreateImageVariationRequest, - options?: ImagesCreateVariationOptionalParams, + create: ( + image: CreateImageRequest, + options?: ImagesCreateOptionalParams, ) => Promise; } export function getImages(context: OpenAIContext) { return { - create: (image: CreateImageRequest, options?: ImagesCreateOptionalParams) => - create(context, image, options), - createEdit: ( - image: CreateImageEditRequest, - options?: ImagesCreateEditOptionalParams, - ) => createEdit(context, image, options), createVariation: ( image: CreateImageVariationRequest, options?: ImagesCreateVariationOptionalParams, ) => createVariation(context, image, options), + createEdit: ( + image: CreateImageEditRequest, + options?: ImagesCreateEditOptionalParams, + ) => createEdit(context, image, options), + create: (image: CreateImageRequest, options?: ImagesCreateOptionalParams) => + create(context, image, options), }; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts index 44118ec4e1..ed612205af 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/classic/models/index.ts @@ -1,25 +1,20 @@ // Licensed under the MIT License. import { OpenAIContext } from "../../api/openAIContext.js"; -import { list, retrieve, $delete } from "../../api/models/index.js"; +import { $delete, retrieve, list } from "../../api/models/index.js"; import { ListModelsResponse, Model, DeleteModelResponse, } from "../../models/models.js"; import { - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, ModelsDeleteOptionalParams, + ModelsRetrieveOptionalParams, + ModelsListOptionalParams, } from "../../api/options.js"; /** Interface representing a Models operations. */ export interface ModelsOperations { - list: (options?: ModelsListOptionalParams) => Promise; - retrieve: ( - model: string, - options?: ModelsRetrieveOptionalParams, - ) => Promise; /** * @fixme delete is a reserved word that cannot be used as an operation name. * Please add @clientName("clientName") or @clientName("", "javascript") @@ -29,15 +24,20 @@ export interface ModelsOperations { model: string, options?: ModelsDeleteOptionalParams, ) => Promise; + retrieve: ( + model: string, + options?: ModelsRetrieveOptionalParams, + ) => Promise; + list: (options?: ModelsListOptionalParams) => Promise; } export function getModels(context: OpenAIContext) { return { - list: (options?: ModelsListOptionalParams) => list(context, options), - retrieve: (model: string, options?: ModelsRetrieveOptionalParams) => - retrieve(context, model, options), delete: (model: string, options?: ModelsDeleteOptionalParams) => $delete(context, model, options), + retrieve: (model: string, options?: ModelsRetrieveOptionalParams) => + retrieve(context, model, options), + list: (options?: ModelsListOptionalParams) => list(context, options), }; } diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts index 03f8ddb9d2..2a75996e5a 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/index.ts @@ -50,34 +50,34 @@ export { } from "./models/index.js"; export { OpenAIClientOptionalParams, - AudioTranscriptionsCreateOptionalParams, - AudioTranslationsCreateOptionalParams, - ChatCompletionsCreateOptionalParams, - FineTuningJobsCreateOptionalParams, - FineTuningJobsListOptionalParams, - FineTuningJobsRetrieveOptionalParams, - FineTuningJobsListEventsOptionalParams, - FineTuningJobsCancelOptionalParams, - CompletionsCreateOptionalParams, - EditsCreateOptionalParams, - EmbeddingsCreateOptionalParams, - FilesListOptionalParams, - FilesCreateOptionalParams, - FilesRetrieveOptionalParams, - FilesDeleteOptionalParams, - FilesDownloadOptionalParams, - FineTunesCreateOptionalParams, - FineTunesListOptionalParams, - FineTunesRetrieveOptionalParams, - FineTunesListEventsOptionalParams, - FineTunesCancelOptionalParams, - ModelsListOptionalParams, - ModelsRetrieveOptionalParams, - ModelsDeleteOptionalParams, - ImagesCreateOptionalParams, - ImagesCreateEditOptionalParams, - ImagesCreateVariationOptionalParams, ModerationsCreateOptionalParams, + ImagesCreateVariationOptionalParams, + ImagesCreateEditOptionalParams, + ImagesCreateOptionalParams, + ModelsDeleteOptionalParams, + ModelsRetrieveOptionalParams, + ModelsListOptionalParams, + FineTunesCancelOptionalParams, + FineTunesListEventsOptionalParams, + FineTunesRetrieveOptionalParams, + FineTunesListOptionalParams, + FineTunesCreateOptionalParams, + FilesDownloadOptionalParams, + FilesDeleteOptionalParams, + FilesRetrieveOptionalParams, + FilesCreateOptionalParams, + FilesListOptionalParams, + EmbeddingsCreateOptionalParams, + EditsCreateOptionalParams, + CompletionsCreateOptionalParams, + FineTuningJobsCancelOptionalParams, + FineTuningJobsListEventsOptionalParams, + FineTuningJobsRetrieveOptionalParams, + FineTuningJobsListOptionalParams, + FineTuningJobsCreateOptionalParams, + ChatCompletionsCreateOptionalParams, + AudioTranslationsCreateOptionalParams, + AudioTranscriptionsCreateOptionalParams, } from "./api/index.js"; export { AudioOperations, diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts index ea930d16aa..db2a532e2c 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/models/models.ts @@ -1182,13 +1182,13 @@ export function createCompletionRequestSerializer( ): any { return { model: item["model"], - prompt: item["prompt"], + prompt: !item["prompt"] ? item["prompt"] : promptSerializer(item["prompt"]), suffix: item["suffix"], temperature: item["temperature"], top_p: item["topP"], n: item["n"], max_tokens: item["maxTokens"], - stop: item["stop"], + stop: !item["stop"] ? item["stop"] : stopSerializer(item["stop"]), presence_penalty: item["presencePenalty"], frequency_penalty: item["frequencyPenalty"], logit_bias: item["logitBias"], @@ -1291,7 +1291,9 @@ export function _createCompletionResponseChoiceDeserializer( return { index: item["index"], text: item["text"], - logprobs: item["logprobs"], + logprobs: !item["logprobs"] + ? item["logprobs"] + : _createCompletionResponseChoiceLogprobsDeserializer(item["logprobs"]), finishReason: item["finish_reason"], }; } @@ -1491,9 +1493,7 @@ export function fineTuningJobDeserializer(item: any): FineTuningJob { createdAt: new Date(item["created_at"] * 1000), finishedAt: !item["finished_at"] ? item["finished_at"] - : !item["finished_at"] - ? item["finished_at"] - : new Date(item["finished_at"] * 1000), + : new Date(item["finished_at"] * 1000), model: item["model"], fineTunedModel: item["fine_tuned_model"], organizationId: item["organization_id"], @@ -1507,7 +1507,9 @@ export function fineTuningJobDeserializer(item: any): FineTuningJob { return p; }), trainedTokens: item["trained_tokens"], - error: item["error"], + error: !item["error"] + ? item["error"] + : _fineTuningJobErrorDeserializer(item["error"]), }; } @@ -1752,7 +1754,7 @@ export function createChatCompletionRequestSerializer( top_p: item["topP"], n: item["n"], max_tokens: item["maxTokens"], - stop: item["stop"], + stop: !item["stop"] ? item["stop"] : stopSerializer(item["stop"]), presence_penalty: item["presencePenalty"], frequency_penalty: item["frequencyPenalty"], logit_bias: item["logitBias"], diff --git a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts index 4aeb70305a..9afbc19c16 100644 --- a/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts +++ b/packages/typespec-test/test/openai_non_branded/generated/typespec-ts/src/openAIClient.ts @@ -1,37 +1,37 @@ // Licensed under the MIT License. -import { getAudioOperations, AudioOperations } from "./classic/audio/index.js"; -import { getChatOperations, ChatOperations } from "./classic/chat/index.js"; import { - getFineTuningOperations, - FineTuningOperations, -} from "./classic/fineTuning/index.js"; + getModerationsOperations, + ModerationsOperations, +} from "./classic/moderations/index.js"; import { - getCompletionsOperations, - CompletionsOperations, -} from "./classic/completions/index.js"; -import { getEditsOperations, EditsOperations } from "./classic/edits/index.js"; + getImagesOperations, + ImagesOperations, +} from "./classic/images/index.js"; import { - getEmbeddingsOperations, - EmbeddingsOperations, -} from "./classic/embeddings/index.js"; -import { getFilesOperations, FilesOperations } from "./classic/files/index.js"; + getModelsOperations, + ModelsOperations, +} from "./classic/models/index.js"; import { getFineTunesOperations, FineTunesOperations, } from "./classic/fineTunes/index.js"; +import { getFilesOperations, FilesOperations } from "./classic/files/index.js"; import { - getModelsOperations, - ModelsOperations, -} from "./classic/models/index.js"; + getEmbeddingsOperations, + EmbeddingsOperations, +} from "./classic/embeddings/index.js"; +import { getEditsOperations, EditsOperations } from "./classic/edits/index.js"; import { - getImagesOperations, - ImagesOperations, -} from "./classic/images/index.js"; + getCompletionsOperations, + CompletionsOperations, +} from "./classic/completions/index.js"; import { - getModerationsOperations, - ModerationsOperations, -} from "./classic/moderations/index.js"; + getFineTuningOperations, + FineTuningOperations, +} from "./classic/fineTuning/index.js"; +import { getChatOperations, ChatOperations } from "./classic/chat/index.js"; +import { getAudioOperations, AudioOperations } from "./classic/audio/index.js"; import { createOpenAI, OpenAIContext, @@ -60,39 +60,39 @@ export class OpenAIClient { userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; - this.audio = getAudioOperations(this._client); - this.chat = getChatOperations(this._client); - this.fineTuning = getFineTuningOperations(this._client); - this.completions = getCompletionsOperations(this._client); - this.edits = getEditsOperations(this._client); - this.embeddings = getEmbeddingsOperations(this._client); - this.files = getFilesOperations(this._client); - this.fineTunes = getFineTunesOperations(this._client); - this.models = getModelsOperations(this._client); - this.images = getImagesOperations(this._client); this.moderations = getModerationsOperations(this._client); + this.images = getImagesOperations(this._client); + this.models = getModelsOperations(this._client); + this.fineTunes = getFineTunesOperations(this._client); + this.files = getFilesOperations(this._client); + this.embeddings = getEmbeddingsOperations(this._client); + this.edits = getEditsOperations(this._client); + this.completions = getCompletionsOperations(this._client); + this.fineTuning = getFineTuningOperations(this._client); + this.chat = getChatOperations(this._client); + this.audio = getAudioOperations(this._client); } - /** The operation groups for AudioTranscriptions */ - public readonly audio: AudioOperations; - /** The operation groups for ChatCompletions */ - public readonly chat: ChatOperations; - /** The operation groups for FineTuningJobs */ - public readonly fineTuning: FineTuningOperations; - /** The operation groups for Completions */ - public readonly completions: CompletionsOperations; - /** The operation groups for Edits */ - public readonly edits: EditsOperations; - /** The operation groups for Embeddings */ - public readonly embeddings: EmbeddingsOperations; - /** The operation groups for Files */ - public readonly files: FilesOperations; - /** The operation groups for FineTunes */ - public readonly fineTunes: FineTunesOperations; - /** The operation groups for Models */ - public readonly models: ModelsOperations; - /** The operation groups for Images */ - public readonly images: ImagesOperations; - /** The operation groups for Moderations */ + /** The operation groups for moderations */ public readonly moderations: ModerationsOperations; + /** The operation groups for images */ + public readonly images: ImagesOperations; + /** The operation groups for models */ + public readonly models: ModelsOperations; + /** The operation groups for fineTunes */ + public readonly fineTunes: FineTunesOperations; + /** The operation groups for files */ + public readonly files: FilesOperations; + /** The operation groups for embeddings */ + public readonly embeddings: EmbeddingsOperations; + /** The operation groups for edits */ + public readonly edits: EditsOperations; + /** The operation groups for completions */ + public readonly completions: CompletionsOperations; + /** The operation groups for fineTuning */ + public readonly fineTuning: FineTuningOperations; + /** The operation groups for chat */ + public readonly chat: ChatOperations; + /** The operation groups for audio */ + public readonly audio: AudioOperations; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md index e764bed764..5eeac5fad9 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/review/overload_modular.api.md @@ -12,14 +12,10 @@ import { TokenCredential } from '@azure/core-auth'; // @public export interface FooOperationsGetAvatarAsJpegOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public export interface FooOperationsGetAvatarAsPngOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts index 861a3f759b..fd8a10431a 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/fooOperations/index.ts @@ -13,21 +13,26 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _getAvatarAsPngSend( +export function _getAvatarAsJpegSend( context: Client, image: Uint8Array, - options: FooOperationsGetAvatarAsPngOptionalParams = { requestOptions: {} }, + options: FooOperationsGetAvatarAsJpegOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/avatar") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "image/png", + contentType: "image/jpeg", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: image, }); } -export async function _getAvatarAsPngDeserialize( +export async function _getAvatarAsJpegDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; @@ -39,30 +44,35 @@ export async function _getAvatarAsPngDeserialize( } /** A remote procedure call (RPC) operation. */ -export async function getAvatarAsPng( +export async function getAvatarAsJpeg( context: Client, image: Uint8Array, - options: FooOperationsGetAvatarAsPngOptionalParams = { requestOptions: {} }, + options: FooOperationsGetAvatarAsJpegOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _getAvatarAsPngSend(context, image, options); - return _getAvatarAsPngDeserialize(result); + const result = await _getAvatarAsJpegSend(context, image, options); + return _getAvatarAsJpegDeserialize(result); } -export function _getAvatarAsJpegSend( +export function _getAvatarAsPngSend( context: Client, image: Uint8Array, - options: FooOperationsGetAvatarAsJpegOptionalParams = { requestOptions: {} }, + options: FooOperationsGetAvatarAsPngOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/avatar") .post({ ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "image/jpeg", + contentType: "image/png", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: image, }); } -export async function _getAvatarAsJpegDeserialize( +export async function _getAvatarAsPngDeserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; @@ -74,11 +84,11 @@ export async function _getAvatarAsJpegDeserialize( } /** A remote procedure call (RPC) operation. */ -export async function getAvatarAsJpeg( +export async function getAvatarAsPng( context: Client, image: Uint8Array, - options: FooOperationsGetAvatarAsJpegOptionalParams = { requestOptions: {} }, + options: FooOperationsGetAvatarAsPngOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _getAvatarAsJpegSend(context, image, options); - return _getAvatarAsJpegDeserialize(result); + const result = await _getAvatarAsPngSend(context, image, options); + return _getAvatarAsPngDeserialize(result); } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts index d8a62d530d..5e1123755e 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/index.ts @@ -2,8 +2,8 @@ // Licensed under the MIT License. export { - FooOperationsGetAvatarAsPngOptionalParams, FooOperationsGetAvatarAsJpegOptionalParams, + FooOperationsGetAvatarAsPngOptionalParams, } from "./options.js"; export { createWidgetManager, diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/options.ts index a7043fb8fb..8ef35a5960 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/options.ts @@ -4,13 +4,9 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface FooOperationsGetAvatarAsPngOptionalParams - extends OperationOptions { - contentType?: string; -} +export interface FooOperationsGetAvatarAsJpegOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface FooOperationsGetAvatarAsJpegOptionalParams - extends OperationOptions { - contentType?: string; -} +export interface FooOperationsGetAvatarAsPngOptionalParams + extends OperationOptions {} diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts index 80b3dfbdf9..efb6eda878 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/api/widgetManagerContext.ts @@ -6,7 +6,11 @@ import { KnownVersions } from "../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { KeyCredential, TokenCredential } from "@azure/core-auth"; -export interface WidgetManagerContext extends Client {} +export interface WidgetManagerContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface WidgetManagerClientOptionalParams extends ClientOptions { @@ -56,5 +60,5 @@ export function createWidgetManager( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as WidgetManagerContext; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts index b321233d9b..0fe429b499 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/classic/fooOperations/index.ts @@ -3,38 +3,38 @@ import { WidgetManagerContext } from "../../api/widgetManagerContext.js"; import { - getAvatarAsPng, getAvatarAsJpeg, + getAvatarAsPng, } from "../../api/fooOperations/index.js"; import { - FooOperationsGetAvatarAsPngOptionalParams, FooOperationsGetAvatarAsJpegOptionalParams, + FooOperationsGetAvatarAsPngOptionalParams, } from "../../api/options.js"; /** Interface representing a FooOperations operations. */ export interface FooOperationsOperations { /** A remote procedure call (RPC) operation. */ - getAvatarAsPng: ( + getAvatarAsJpeg: ( image: Uint8Array, - options?: FooOperationsGetAvatarAsPngOptionalParams, + options?: FooOperationsGetAvatarAsJpegOptionalParams, ) => Promise; /** A remote procedure call (RPC) operation. */ - getAvatarAsJpeg: ( + getAvatarAsPng: ( image: Uint8Array, - options?: FooOperationsGetAvatarAsJpegOptionalParams, + options?: FooOperationsGetAvatarAsPngOptionalParams, ) => Promise; } export function getFooOperations(context: WidgetManagerContext) { return { - getAvatarAsPng: ( - image: Uint8Array, - options?: FooOperationsGetAvatarAsPngOptionalParams, - ) => getAvatarAsPng(context, image, options), getAvatarAsJpeg: ( image: Uint8Array, options?: FooOperationsGetAvatarAsJpegOptionalParams, ) => getAvatarAsJpeg(context, image, options), + getAvatarAsPng: ( + image: Uint8Array, + options?: FooOperationsGetAvatarAsPngOptionalParams, + ) => getAvatarAsPng(context, image, options), }; } diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts index 1d607692c5..dec3753750 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/index.ts @@ -4,8 +4,8 @@ export { WidgetManagerClient } from "./widgetManagerClient.js"; export { KnownVersions } from "./models/index.js"; export { - FooOperationsGetAvatarAsPngOptionalParams, FooOperationsGetAvatarAsJpegOptionalParams, + FooOperationsGetAvatarAsPngOptionalParams, WidgetManagerClientOptionalParams, } from "./api/index.js"; export { FooOperationsOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts index b3a2a06aca..6ae5b2b9dc 100644 --- a/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts +++ b/packages/typespec-test/test/overloads_modular/generated/typespec-ts/src/widgetManagerClient.ts @@ -37,6 +37,6 @@ export class WidgetManagerClient { this.fooOperations = getFooOperationsOperations(this._client); } - /** The operation groups for FooOperations */ + /** The operation groups for fooOperations */ public readonly fooOperations: FooOperationsOperations; } diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts index 01c4c89c3f..865c4d6ba7 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/confidentialLedger/index.ts @@ -24,7 +24,14 @@ export function _listCollectionsSend( ): StreamableMethod { return context .path("/app/collections") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _listCollectionsDeserialize( diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts index ec4eb1f7da..844be33683 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/api/parametrizedHostContext.ts @@ -5,7 +5,10 @@ import { logger } from "../logger.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; -export interface ParametrizedHostContext extends Client {} +export interface ParametrizedHostContext extends Client { + /** The API version to use for this operation. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface ParametrizedHostClientOptionalParams extends ClientOptions { @@ -56,5 +59,5 @@ export function createParametrizedHost( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as ParametrizedHostContext; } diff --git a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts index 16c6763305..fe76fef84e 100644 --- a/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts +++ b/packages/typespec-test/test/parametrizedHost/generated/typespec-ts/src/parametrizedHostClient.ts @@ -37,6 +37,6 @@ export class ParametrizedHostClient { this.confidentialLedger = getConfidentialLedgerOperations(this._client); } - /** The operation groups for ConfidentialLedger */ + /** The operation groups for confidentialLedger */ public readonly confidentialLedger: ConfidentialLedgerOperations; } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md index 73f2602824..ee7ac86e36 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/review/schema-registry.api.md @@ -80,7 +80,7 @@ export interface SchemaOperationsOperations { getSchemaIdByContent: (groupName: string, name: string, contentType: SchemaContentTypeValues, schemaContent: Uint8Array, options?: SchemaOperationsGetSchemaIdByContentOptionalParams) => Promise; listSchemaGroups: (options?: SchemaOperationsListSchemaGroupsOptionalParams) => PagedAsyncIterableIterator; listSchemaVersions: (groupName: string, name: string, options?: SchemaOperationsListSchemaVersionsOptionalParams) => PagedAsyncIterableIterator; - registerSchema: (groupName: string, name: string, contentType: SchemaContentTypeValues, content: Uint8Array, options?: SchemaOperationsRegisterSchemaOptionalParams) => Promise; + registerSchema: (groupName: string, name: string, content: Uint8Array, contentType: SchemaContentTypeValues, options?: SchemaOperationsRegisterSchemaOptionalParams) => Promise; } // @public @@ -98,7 +98,7 @@ export interface SchemaProperties { // @public (undocumented) export class SchemaRegistryClient { - constructor(fullyQualifiedNamespace: string, credential: TokenCredential, options?: SchemaRegistryClientOptionalParams); + constructor(endpointParam: string, credential: TokenCredential, options?: SchemaRegistryClientOptionalParams); readonly pipeline: Pipeline; readonly schemaOperations: SchemaOperationsOperations; } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts index 40c815f457..50953abc14 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/index.ts @@ -2,12 +2,12 @@ // Licensed under the MIT License. export { - SchemaOperationsListSchemaGroupsOptionalParams, - SchemaOperationsGetSchemaByIdOptionalParams, - SchemaOperationsListSchemaVersionsOptionalParams, - SchemaOperationsGetSchemaByVersionOptionalParams, - SchemaOperationsGetSchemaIdByContentOptionalParams, SchemaOperationsRegisterSchemaOptionalParams, + SchemaOperationsGetSchemaIdByContentOptionalParams, + SchemaOperationsGetSchemaByVersionOptionalParams, + SchemaOperationsListSchemaVersionsOptionalParams, + SchemaOperationsGetSchemaByIdOptionalParams, + SchemaOperationsListSchemaGroupsOptionalParams, } from "./options.js"; export { createSchemaRegistry, diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/options.ts index 0ebd859522..1749b37fe6 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/options.ts @@ -4,25 +4,25 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface SchemaOperationsListSchemaGroupsOptionalParams +export interface SchemaOperationsRegisterSchemaOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface SchemaOperationsGetSchemaByIdOptionalParams +export interface SchemaOperationsGetSchemaIdByContentOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface SchemaOperationsListSchemaVersionsOptionalParams +export interface SchemaOperationsGetSchemaByVersionOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface SchemaOperationsGetSchemaByVersionOptionalParams +export interface SchemaOperationsListSchemaVersionsOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface SchemaOperationsGetSchemaIdByContentOptionalParams +export interface SchemaOperationsGetSchemaByIdOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface SchemaOperationsRegisterSchemaOptionalParams +export interface SchemaOperationsListSchemaGroupsOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts index b710d15559..810abe3750 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaOperations/index.ts @@ -29,119 +29,119 @@ import { createRestError, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; -export function _listSchemaGroupsSend( +export function _registerSchemaSend( context: Client, - options: SchemaOperationsListSchemaGroupsOptionalParams = { + groupName: string, + name: string, + content: Uint8Array, + contentType: SchemaContentTypeValues, + options: SchemaOperationsRegisterSchemaOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/$schemaGroups") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/$schemaGroups/{groupName}/schemas/{name}", groupName, name) + .put({ + ...operationOptionsToRequestParameters(options), + contentType: contentType, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: content, + }); } -export async function _listSchemaGroupsDeserialize( +export async function _registerSchemaDeserialize( result: PathUncheckedResponse, -): Promise<_PagedSchemaGroup> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedSchemaGroupDeserializer(result.body); + return; } -/** Gets the list of schema groups user is authorized to access. */ -export function listSchemaGroups( +/** Register new schema. If schema of specified name does not exist in specified group, schema is created at version 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. */ +export async function registerSchema( context: Client, - options: SchemaOperationsListSchemaGroupsOptionalParams = { + groupName: string, + name: string, + content: Uint8Array, + contentType: SchemaContentTypeValues, + options: SchemaOperationsRegisterSchemaOptionalParams = { requestOptions: {}, }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( +): Promise { + const result = await _registerSchemaSend( context, - () => _listSchemaGroupsSend(context, options), - _listSchemaGroupsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + groupName, + name, + content, + contentType, + options, ); + return _registerSchemaDeserialize(result); } -export function _getSchemaByIdSend( - context: Client, - id: string, - options: SchemaOperationsGetSchemaByIdOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/$schemaGroups/$schemas/{id}", id) - .get({ ...operationOptionsToRequestParameters(options) }); -} - -export async function _getSchemaByIdDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return typeof result.body === "string" - ? stringToUint8Array(result.body, "base64") - : result.body; -} - -/** Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. Operation response type is based on serialization of schema requested. */ -export async function getSchemaById( - context: Client, - id: string, - options: SchemaOperationsGetSchemaByIdOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getSchemaByIdSend(context, id, options); - return _getSchemaByIdDeserialize(result); -} - -export function _listSchemaVersionsSend( +export function _getSchemaIdByContentSend( context: Client, groupName: string, name: string, - options: SchemaOperationsListSchemaVersionsOptionalParams = { + contentType: SchemaContentTypeValues, + schemaContent: Uint8Array, + options: SchemaOperationsGetSchemaIdByContentOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/$schemaGroups/{groupName}/schemas/{name}/versions", groupName, name) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/$schemaGroups/{groupName}/schemas/{name}:get-id", groupName, name) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: contentType, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: schemaContent, + }); } -export async function _listSchemaVersionsDeserialize( +export async function _getSchemaIdByContentDeserialize( result: PathUncheckedResponse, -): Promise<_PagedVersion> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _pagedVersionDeserializer(result.body); + return; } -/** Gets the list of all versions of one schema. */ -export function listSchemaVersions( +/** Gets the ID referencing an existing schema within the specified schema group, as matched by schema content comparison. */ +export async function getSchemaIdByContent( context: Client, groupName: string, name: string, - options: SchemaOperationsListSchemaVersionsOptionalParams = { + contentType: SchemaContentTypeValues, + schemaContent: Uint8Array, + options: SchemaOperationsGetSchemaIdByContentOptionalParams = { requestOptions: {}, }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( +): Promise { + const result = await _getSchemaIdByContentSend( context, - () => _listSchemaVersionsSend(context, groupName, name, options), - _listSchemaVersionsDeserialize, - ["200"], - { itemName: "value", nextLinkName: "nextLink" }, + groupName, + name, + contentType, + schemaContent, + options, ); + return _getSchemaIdByContentDeserialize(result); } export function _getSchemaByVersionSend( @@ -160,7 +160,10 @@ export function _getSchemaByVersionSend( name, schemaVersion, ) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { "api-version": context.apiVersion }, + }); } export async function _getSchemaByVersionDeserialize( @@ -171,9 +174,7 @@ export async function _getSchemaByVersionDeserialize( throw createRestError(result); } - return typeof result.body === "string" - ? stringToUint8Array(result.body, "base64") - : result.body; + return result.body; } /** Gets one specific version of one schema. */ @@ -196,106 +197,130 @@ export async function getSchemaByVersion( return _getSchemaByVersionDeserialize(result); } -export function _getSchemaIdByContentSend( +export function _listSchemaVersionsSend( context: Client, groupName: string, name: string, - contentType: SchemaContentTypeValues, - schemaContent: Uint8Array, - options: SchemaOperationsGetSchemaIdByContentOptionalParams = { + options: SchemaOperationsListSchemaVersionsOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/$schemaGroups/{groupName}/schemas/{name}:get-id", groupName, name) - .post({ + .path("/$schemaGroups/{groupName}/schemas/{name}/versions", groupName, name) + .get({ ...operationOptionsToRequestParameters(options), - contentType: contentType, - body: uint8ArrayToString(schemaContent, "base64"), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _getSchemaIdByContentDeserialize( +export async function _listSchemaVersionsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise<_PagedVersion> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return _pagedVersionDeserializer(result.body); } -/** Gets the ID referencing an existing schema within the specified schema group, as matched by schema content comparison. */ -export async function getSchemaIdByContent( +/** Gets the list of all versions of one schema. */ +export function listSchemaVersions( context: Client, groupName: string, name: string, - contentType: SchemaContentTypeValues, - schemaContent: Uint8Array, - options: SchemaOperationsGetSchemaIdByContentOptionalParams = { + options: SchemaOperationsListSchemaVersionsOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _getSchemaIdByContentSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - groupName, - name, - contentType, - schemaContent, - options, + () => _listSchemaVersionsSend(context, groupName, name, options), + _listSchemaVersionsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _getSchemaIdByContentDeserialize(result); } -export function _registerSchemaSend( +export function _getSchemaByIdSend( context: Client, - groupName: string, - name: string, - contentType: SchemaContentTypeValues, - content: Uint8Array, - options: SchemaOperationsRegisterSchemaOptionalParams = { + id: string, + options: SchemaOperationsGetSchemaByIdOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/$schemaGroups/$schemas/{id}", id) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { "api-version": context.apiVersion }, + }); +} + +export async function _getSchemaByIdDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return result.body; +} + +/** Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. Operation response type is based on serialization of schema requested. */ +export async function getSchemaById( + context: Client, + id: string, + options: SchemaOperationsGetSchemaByIdOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getSchemaByIdSend(context, id, options); + return _getSchemaByIdDeserialize(result); +} + +export function _listSchemaGroupsSend( + context: Client, + options: SchemaOperationsListSchemaGroupsOptionalParams = { requestOptions: {}, }, ): StreamableMethod { return context - .path("/$schemaGroups/{groupName}/schemas/{name}", groupName, name) - .put({ + .path("/$schemaGroups") + .get({ ...operationOptionsToRequestParameters(options), - contentType: contentType, - body: uint8ArrayToString(content, "base64"), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, }); } -export async function _registerSchemaDeserialize( +export async function _listSchemaGroupsDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise<_PagedSchemaGroup> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return _pagedSchemaGroupDeserializer(result.body); } -/** Register new schema. If schema of specified name does not exist in specified group, schema is created at version 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. */ -export async function registerSchema( +/** Gets the list of schema groups user is authorized to access. */ +export function listSchemaGroups( context: Client, - groupName: string, - name: string, - contentType: SchemaContentTypeValues, - content: Uint8Array, - options: SchemaOperationsRegisterSchemaOptionalParams = { + options: SchemaOperationsListSchemaGroupsOptionalParams = { requestOptions: {}, }, -): Promise { - const result = await _registerSchemaSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - groupName, - name, - contentType, - content, - options, + () => _listSchemaGroupsSend(context, options), + _listSchemaGroupsDeserialize, + ["200"], + { itemName: "value", nextLinkName: "nextLink" }, ); - return _registerSchemaDeserialize(result); } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts index e3990f380e..81ce18cfbc 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/api/schemaRegistryContext.ts @@ -7,7 +7,11 @@ import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { TokenCredential } from "@azure/core-auth"; /** SchemaRegistryClient is a client for registering and retrieving schemas from the Azure Schema Registry service. */ -export interface SchemaRegistryContext extends Client {} +export interface SchemaRegistryContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownServiceApiVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface SchemaRegistryClientOptionalParams extends ClientOptions { @@ -18,12 +22,12 @@ export interface SchemaRegistryClientOptionalParams extends ClientOptions { /** SchemaRegistryClient is a client for registering and retrieving schemas from the Azure Schema Registry service. */ export function createSchemaRegistry( - fullyQualifiedNamespace: string, + endpointParam: string, credential: TokenCredential, options: SchemaRegistryClientOptionalParams = {}, ): SchemaRegistryContext { const endpointUrl = - options.endpoint ?? options.baseUrl ?? `${fullyQualifiedNamespace}`; + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-schema-registry/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -57,5 +61,5 @@ export function createSchemaRegistry( return next(req); }, }); - return clientContext; + return { ...clientContext, apiVersion } as SchemaRegistryContext; } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts index 75322c6473..bf3ee8e35c 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/classic/schemaOperations/index.ts @@ -3,12 +3,12 @@ import { SchemaRegistryContext } from "../../api/schemaRegistryContext.js"; import { - listSchemaGroups, - getSchemaById, - listSchemaVersions, - getSchemaByVersion, - getSchemaIdByContent, registerSchema, + getSchemaIdByContent, + getSchemaByVersion, + listSchemaVersions, + getSchemaById, + listSchemaGroups, } from "../../api/schemaOperations/index.js"; import { SchemaGroup, @@ -17,38 +17,24 @@ import { } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { - SchemaOperationsListSchemaGroupsOptionalParams, - SchemaOperationsGetSchemaByIdOptionalParams, - SchemaOperationsListSchemaVersionsOptionalParams, - SchemaOperationsGetSchemaByVersionOptionalParams, - SchemaOperationsGetSchemaIdByContentOptionalParams, SchemaOperationsRegisterSchemaOptionalParams, + SchemaOperationsGetSchemaIdByContentOptionalParams, + SchemaOperationsGetSchemaByVersionOptionalParams, + SchemaOperationsListSchemaVersionsOptionalParams, + SchemaOperationsGetSchemaByIdOptionalParams, + SchemaOperationsListSchemaGroupsOptionalParams, } from "../../api/options.js"; /** Interface representing a SchemaOperations operations. */ export interface SchemaOperationsOperations { - /** Gets the list of schema groups user is authorized to access. */ - listSchemaGroups: ( - options?: SchemaOperationsListSchemaGroupsOptionalParams, - ) => PagedAsyncIterableIterator; - /** Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. Operation response type is based on serialization of schema requested. */ - getSchemaById: ( - id: string, - options?: SchemaOperationsGetSchemaByIdOptionalParams, - ) => Promise; - /** Gets the list of all versions of one schema. */ - listSchemaVersions: ( - groupName: string, - name: string, - options?: SchemaOperationsListSchemaVersionsOptionalParams, - ) => PagedAsyncIterableIterator; - /** Gets one specific version of one schema. */ - getSchemaByVersion: ( + /** Register new schema. If schema of specified name does not exist in specified group, schema is created at version 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. */ + registerSchema: ( groupName: string, name: string, - schemaVersion: number, - options?: SchemaOperationsGetSchemaByVersionOptionalParams, - ) => Promise; + content: Uint8Array, + contentType: SchemaContentTypeValues, + options?: SchemaOperationsRegisterSchemaOptionalParams, + ) => Promise; /** Gets the ID referencing an existing schema within the specified schema group, as matched by schema content comparison. */ getSchemaIdByContent: ( groupName: string, @@ -57,36 +43,40 @@ export interface SchemaOperationsOperations { schemaContent: Uint8Array, options?: SchemaOperationsGetSchemaIdByContentOptionalParams, ) => Promise; - /** Register new schema. If schema of specified name does not exist in specified group, schema is created at version 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. */ - registerSchema: ( + /** Gets one specific version of one schema. */ + getSchemaByVersion: ( groupName: string, name: string, - contentType: SchemaContentTypeValues, - content: Uint8Array, - options?: SchemaOperationsRegisterSchemaOptionalParams, - ) => Promise; + schemaVersion: number, + options?: SchemaOperationsGetSchemaByVersionOptionalParams, + ) => Promise; + /** Gets the list of all versions of one schema. */ + listSchemaVersions: ( + groupName: string, + name: string, + options?: SchemaOperationsListSchemaVersionsOptionalParams, + ) => PagedAsyncIterableIterator; + /** Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. Operation response type is based on serialization of schema requested. */ + getSchemaById: ( + id: string, + options?: SchemaOperationsGetSchemaByIdOptionalParams, + ) => Promise; + /** Gets the list of schema groups user is authorized to access. */ + listSchemaGroups: ( + options?: SchemaOperationsListSchemaGroupsOptionalParams, + ) => PagedAsyncIterableIterator; } export function getSchemaOperations(context: SchemaRegistryContext) { return { - listSchemaGroups: ( - options?: SchemaOperationsListSchemaGroupsOptionalParams, - ) => listSchemaGroups(context, options), - getSchemaById: ( - id: string, - options?: SchemaOperationsGetSchemaByIdOptionalParams, - ) => getSchemaById(context, id, options), - listSchemaVersions: ( - groupName: string, - name: string, - options?: SchemaOperationsListSchemaVersionsOptionalParams, - ) => listSchemaVersions(context, groupName, name, options), - getSchemaByVersion: ( + registerSchema: ( groupName: string, name: string, - schemaVersion: number, - options?: SchemaOperationsGetSchemaByVersionOptionalParams, - ) => getSchemaByVersion(context, groupName, name, schemaVersion, options), + content: Uint8Array, + contentType: SchemaContentTypeValues, + options?: SchemaOperationsRegisterSchemaOptionalParams, + ) => + registerSchema(context, groupName, name, content, contentType, options), getSchemaIdByContent: ( groupName: string, name: string, @@ -102,14 +92,24 @@ export function getSchemaOperations(context: SchemaRegistryContext) { schemaContent, options, ), - registerSchema: ( + getSchemaByVersion: ( groupName: string, name: string, - contentType: SchemaContentTypeValues, - content: Uint8Array, - options?: SchemaOperationsRegisterSchemaOptionalParams, - ) => - registerSchema(context, groupName, name, contentType, content, options), + schemaVersion: number, + options?: SchemaOperationsGetSchemaByVersionOptionalParams, + ) => getSchemaByVersion(context, groupName, name, schemaVersion, options), + listSchemaVersions: ( + groupName: string, + name: string, + options?: SchemaOperationsListSchemaVersionsOptionalParams, + ) => listSchemaVersions(context, groupName, name, options), + getSchemaById: ( + id: string, + options?: SchemaOperationsGetSchemaByIdOptionalParams, + ) => getSchemaById(context, id, options), + listSchemaGroups: ( + options?: SchemaOperationsListSchemaGroupsOptionalParams, + ) => listSchemaGroups(context, options), }; } diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts index 660a47371d..0312e63491 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/index.ts @@ -19,12 +19,12 @@ export { ContentTypeEnum, } from "./models/index.js"; export { - SchemaOperationsListSchemaGroupsOptionalParams, - SchemaOperationsGetSchemaByIdOptionalParams, - SchemaOperationsListSchemaVersionsOptionalParams, - SchemaOperationsGetSchemaByVersionOptionalParams, - SchemaOperationsGetSchemaIdByContentOptionalParams, SchemaOperationsRegisterSchemaOptionalParams, + SchemaOperationsGetSchemaIdByContentOptionalParams, + SchemaOperationsGetSchemaByVersionOptionalParams, + SchemaOperationsListSchemaVersionsOptionalParams, + SchemaOperationsGetSchemaByIdOptionalParams, + SchemaOperationsListSchemaGroupsOptionalParams, SchemaRegistryClientOptionalParams, } from "./api/index.js"; export { SchemaOperationsOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts index 51a9895f01..acd2227947 100644 --- a/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts +++ b/packages/typespec-test/test/schemaRegistry/generated/typespec-ts/src/schemaRegistryClient.ts @@ -22,7 +22,7 @@ export class SchemaRegistryClient { /** SchemaRegistryClient is a client for registering and retrieving schemas from the Azure Schema Registry service. */ constructor( - fullyQualifiedNamespace: string, + endpointParam: string, credential: TokenCredential, options: SchemaRegistryClientOptionalParams = {}, ) { @@ -30,7 +30,7 @@ export class SchemaRegistryClient { const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-client` : `azsdk-js-client`; - this._client = createSchemaRegistry(fullyQualifiedNamespace, credential, { + this._client = createSchemaRegistry(endpointParam, credential, { ...options, userAgentOptions: { userAgentPrefix }, }); @@ -38,6 +38,6 @@ export class SchemaRegistryClient { this.schemaOperations = getSchemaOperationsOperations(this._client); } - /** The operation groups for SchemaOperations */ + /** The operation groups for schemaOperations */ public readonly schemaOperations: SchemaOperationsOperations; } diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts index 97e4919687..d4cbdf16a9 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/a/index.ts @@ -19,22 +19,23 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _test1Send( +export function _test4Send( context: Client, - a: string, - b: string, - c: string, - options: ATest1OptionalParams = { requestOptions: {} }, + body: { + prop: string; + }, + options: ATest4OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test1") + .path("/test4") .post({ ...operationOptionsToRequestParameters(options), - body: { a: a, b: b, c: c }, + contentType: "application/json", + body: _test4RequestSerializer(body), }); } -export async function _test1Deserialize( +export async function _test4Deserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; @@ -45,31 +46,34 @@ export async function _test1Deserialize( return; } -export async function test1( +export async function test4( context: Client, - a: string, - b: string, - c: string, - options: ATest1OptionalParams = { requestOptions: {} }, + body: { + prop: string; + }, + options: ATest4OptionalParams = { requestOptions: {} }, ): Promise { - const result = await _test1Send(context, a, b, c, options); - return _test1Deserialize(result); + const result = await _test4Send(context, body, options); + return _test4Deserialize(result); } -export function _test2Send( +export function _test3Send( context: Client, - prop: string, - options: ATest2OptionalParams = { requestOptions: {} }, + body: { + prop: string; + }, + options: ATest3OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test2") + .path("/test3") .post({ ...operationOptionsToRequestParameters(options), - body: { prop: prop }, + contentType: "application/json", + body: _test3RequestSerializer(body), }); } -export async function _test2Deserialize( +export async function _test3Deserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; @@ -80,31 +84,32 @@ export async function _test2Deserialize( return; } -export async function test2( - context: Client, - prop: string, - options: ATest2OptionalParams = { requestOptions: {} }, -): Promise { - const result = await _test2Send(context, prop, options); - return _test2Deserialize(result); -} - -export function _test3Send( +export async function test3( context: Client, body: { prop: string; }, options: ATest3OptionalParams = { requestOptions: {} }, +): Promise { + const result = await _test3Send(context, body, options); + return _test3Deserialize(result); +} + +export function _test2Send( + context: Client, + prop: string, + options: ATest2OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test3") + .path("/test2") .post({ ...operationOptionsToRequestParameters(options), - body: _test3RequestSerializer(body), + contentType: "application/json", + body: { prop: prop }, }); } -export async function _test3Deserialize( +export async function _test2Deserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; @@ -115,33 +120,32 @@ export async function _test3Deserialize( return; } -export async function test3( +export async function test2( context: Client, - body: { - prop: string; - }, - options: ATest3OptionalParams = { requestOptions: {} }, + prop: string, + options: ATest2OptionalParams = { requestOptions: {} }, ): Promise { - const result = await _test3Send(context, body, options); - return _test3Deserialize(result); + const result = await _test2Send(context, prop, options); + return _test2Deserialize(result); } -export function _test4Send( +export function _test1Send( context: Client, - body: { - prop: string; - }, - options: ATest4OptionalParams = { requestOptions: {} }, + a: string, + b: string, + c: string, + options: ATest1OptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test4") + .path("/test1") .post({ ...operationOptionsToRequestParameters(options), - body: _test4RequestSerializer(body), + contentType: "application/json", + body: { a: a, b: b, c: c }, }); } -export async function _test4Deserialize( +export async function _test1Deserialize( result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; @@ -152,13 +156,13 @@ export async function _test4Deserialize( return; } -export async function test4( +export async function test1( context: Client, - body: { - prop: string; - }, - options: ATest4OptionalParams = { requestOptions: {} }, + a: string, + b: string, + c: string, + options: ATest1OptionalParams = { requestOptions: {} }, ): Promise { - const result = await _test4Send(context, body, options); - return _test4Deserialize(result); + const result = await _test1Send(context, a, b, c, options); + return _test1Deserialize(result); } diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts index aab8578bd7..206a6d7d53 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/demoServiceContext.ts @@ -13,6 +13,8 @@ export function createDemoService( endpointParam: string, options: DemoServiceClientOptionalParams = {}, ): DemoServiceContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-spread/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -23,11 +25,7 @@ export function createDemoService( userAgentOptions: { userAgentPrefix }, loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; - const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? String(endpointParam), - undefined, - updatedOptions, - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); if (options.apiVersion) { logger.warning( diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts index a17e02a052..161ce3ac82 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/index.ts @@ -7,8 +7,8 @@ export { DemoServiceClientOptionalParams, } from "./demoServiceContext.js"; export { - ATest1OptionalParams, - ATest2OptionalParams, - ATest3OptionalParams, ATest4OptionalParams, + ATest3OptionalParams, + ATest2OptionalParams, + ATest1OptionalParams, } from "./options.js"; diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/options.ts index fd9fdadb12..1b6c30253a 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/api/options.ts @@ -4,13 +4,13 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface ATest1OptionalParams extends OperationOptions {} +export interface ATest4OptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ATest2OptionalParams extends OperationOptions {} +export interface ATest3OptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ATest3OptionalParams extends OperationOptions {} +export interface ATest2OptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface ATest4OptionalParams extends OperationOptions {} +export interface ATest1OptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts index bf9e266999..4ff35f4960 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/classic/a/index.ts @@ -2,55 +2,55 @@ // Licensed under the MIT License. import { DemoServiceContext } from "../../api/demoServiceContext.js"; -import { test1, test2, test3, test4 } from "../../api/a/index.js"; +import { test4, test3, test2, test1 } from "../../api/a/index.js"; import { - ATest1OptionalParams, - ATest2OptionalParams, - ATest3OptionalParams, ATest4OptionalParams, + ATest3OptionalParams, + ATest2OptionalParams, + ATest1OptionalParams, } from "../../api/options.js"; /** Interface representing a A operations. */ export interface AOperations { - test1: ( - a: string, - b: string, - c: string, - options?: ATest1OptionalParams, - ) => Promise; - test2: (prop: string, options?: ATest2OptionalParams) => Promise; - test3: ( + test4: ( body: { prop: string; }, - options?: ATest3OptionalParams, + options?: ATest4OptionalParams, ) => Promise; - test4: ( + test3: ( body: { prop: string; }, - options?: ATest4OptionalParams, + options?: ATest3OptionalParams, + ) => Promise; + test2: (prop: string, options?: ATest2OptionalParams) => Promise; + test1: ( + a: string, + b: string, + c: string, + options?: ATest1OptionalParams, ) => Promise; } export function getA(context: DemoServiceContext) { return { - test1: (a: string, b: string, c: string, options?: ATest1OptionalParams) => - test1(context, a, b, c, options), - test2: (prop: string, options?: ATest2OptionalParams) => - test2(context, prop, options), - test3: ( - body: { - prop: string; - }, - options?: ATest3OptionalParams, - ) => test3(context, body, options), test4: ( body: { prop: string; }, options?: ATest4OptionalParams, ) => test4(context, body, options), + test3: ( + body: { + prop: string; + }, + options?: ATest3OptionalParams, + ) => test3(context, body, options), + test2: (prop: string, options?: ATest2OptionalParams) => + test2(context, prop, options), + test1: (a: string, b: string, c: string, options?: ATest1OptionalParams) => + test1(context, a, b, c, options), }; } diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts index 2465ae3633..b7281c3bb4 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/demoServiceClient.ts @@ -32,6 +32,6 @@ export class DemoServiceClient { this.a = getAOperations(this._client); } - /** The operation groups for A */ + /** The operation groups for a */ public readonly a: AOperations; } diff --git a/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts index c2ef03828c..bd937a353c 100644 --- a/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/spread/generated/typespec-ts/src/index.ts @@ -4,9 +4,9 @@ export { DemoServiceClient } from "./demoServiceClient.js"; export { DemoServiceClientOptionalParams, - ATest1OptionalParams, - ATest2OptionalParams, - ATest3OptionalParams, ATest4OptionalParams, + ATest3OptionalParams, + ATest2OptionalParams, + ATest1OptionalParams, } from "./api/index.js"; export { AOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/package.json b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/package.json index 9f4b34033d..37245a51f3 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/package.json @@ -13,9 +13,9 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/users": "./src/api/users/index.ts", + "./api/todoItems/attachments": "./src/api/todoItems/attachments/index.ts", "./api/todoItems": "./src/api/todoItems/index.ts", - "./api/todoItems/attachments": "./src/api/todoItems/attachments/index.ts" + "./api/users": "./src/api/users/index.ts" }, "dialects": [ "esm", @@ -105,22 +105,22 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/users": { + "./api/todoItems/attachments": { "browser": { - "types": "./dist/browser/api/users/index.d.ts", - "default": "./dist/browser/api/users/index.js" + "types": "./dist/browser/api/todoItems/attachments/index.d.ts", + "default": "./dist/browser/api/todoItems/attachments/index.js" }, "react-native": { - "types": "./dist/react-native/api/users/index.d.ts", - "default": "./dist/react-native/api/users/index.js" + "types": "./dist/react-native/api/todoItems/attachments/index.d.ts", + "default": "./dist/react-native/api/todoItems/attachments/index.js" }, "import": { - "types": "./dist/esm/api/users/index.d.ts", - "default": "./dist/esm/api/users/index.js" + "types": "./dist/esm/api/todoItems/attachments/index.d.ts", + "default": "./dist/esm/api/todoItems/attachments/index.js" }, "require": { - "types": "./dist/commonjs/api/users/index.d.ts", - "default": "./dist/commonjs/api/users/index.js" + "types": "./dist/commonjs/api/todoItems/attachments/index.d.ts", + "default": "./dist/commonjs/api/todoItems/attachments/index.js" } }, "./api/todoItems": { @@ -141,22 +141,22 @@ "default": "./dist/commonjs/api/todoItems/index.js" } }, - "./api/todoItems/attachments": { + "./api/users": { "browser": { - "types": "./dist/browser/api/todoItems/attachments/index.d.ts", - "default": "./dist/browser/api/todoItems/attachments/index.js" + "types": "./dist/browser/api/users/index.d.ts", + "default": "./dist/browser/api/users/index.js" }, "react-native": { - "types": "./dist/react-native/api/todoItems/attachments/index.d.ts", - "default": "./dist/react-native/api/todoItems/attachments/index.js" + "types": "./dist/react-native/api/users/index.d.ts", + "default": "./dist/react-native/api/users/index.js" }, "import": { - "types": "./dist/esm/api/todoItems/attachments/index.d.ts", - "default": "./dist/esm/api/todoItems/attachments/index.js" + "types": "./dist/esm/api/users/index.d.ts", + "default": "./dist/esm/api/users/index.js" }, "require": { - "types": "./dist/commonjs/api/todoItems/attachments/index.d.ts", - "default": "./dist/commonjs/api/todoItems/attachments/index.js" + "types": "./dist/commonjs/api/users/index.d.ts", + "default": "./dist/commonjs/api/users/index.js" } } }, diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md index 06adde345d..8b6dc60f76 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/review/todo-non-branded.api.md @@ -9,6 +9,23 @@ import { KeyCredential } from '@typespec/ts-http-runtime'; import { OperationOptions } from '@typespec/ts-http-runtime'; import { Pipeline } from '@typespec/ts-http-runtime'; +// @public +export type ContinuablePage = TPage & { + continuationToken?: string; +}; + +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; + next(): Promise>; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} + // @public export interface PageTodoAttachment { // (undocumented) @@ -75,15 +92,13 @@ export interface TodoItemsAttachmentsOperations { // (undocumented) createAttachment: (itemId: number, contents: TodoAttachment, options?: TodoItemsAttachmentsCreateAttachmentOptionalParams) => Promise; // (undocumented) - list: (itemId: number, options?: TodoItemsAttachmentsListOptionalParams) => Promise; + list: (itemId: number, options?: TodoItemsAttachmentsListOptionalParams) => PagedAsyncIterableIterator; } // @public export interface TodoItemsCreateOptionalParams extends OperationOptions { // (undocumented) attachments?: TodoAttachment[]; - // (undocumented) - contentType?: string; } // @public @@ -132,7 +147,7 @@ export interface TodoItemsOperations { labels?: TodoLabels; }>; // (undocumented) - list: (options?: TodoItemsListOptionalParams) => Promise; + list: (options?: TodoItemsListOptionalParams) => PagedAsyncIterableIterator; // (undocumented) update: (id: number, patch: TodoItemPatch, options?: TodoItemsUpdateOptionalParams) => Promise<{ id: number; @@ -150,8 +165,6 @@ export interface TodoItemsOperations { // @public export interface TodoItemsUpdateOptionalParams extends OperationOptions { - // (undocumented) - contentType?: string; } // @public diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/index.ts index ffa0471b5b..3054d820a9 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/index.ts @@ -1,14 +1,14 @@ // Licensed under the MIT License. export { - UsersCreateOptionalParams, - TodoItemsListOptionalParams, - TodoItemsCreateOptionalParams, - TodoItemsGetOptionalParams, - TodoItemsUpdateOptionalParams, - TodoItemsDeleteOptionalParams, - TodoItemsAttachmentsListOptionalParams, TodoItemsAttachmentsCreateAttachmentOptionalParams, + TodoItemsAttachmentsListOptionalParams, + TodoItemsDeleteOptionalParams, + TodoItemsUpdateOptionalParams, + TodoItemsGetOptionalParams, + TodoItemsCreateOptionalParams, + TodoItemsListOptionalParams, + UsersCreateOptionalParams, } from "./options.js"; export { createTodo, diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/options.ts index b5f8dc2302..a3c2012467 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/options.ts @@ -1,40 +1,37 @@ // Licensed under the MIT License. -import { OperationOptions } from "@typespec/ts-http-runtime"; import { TodoAttachment } from "../models/models.js"; +import { OperationOptions } from "@typespec/ts-http-runtime"; /** Optional parameters. */ -export interface UsersCreateOptionalParams extends OperationOptions {} +export interface TodoItemsAttachmentsCreateAttachmentOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface TodoItemsListOptionalParams extends OperationOptions { - /** The limit to the number of items */ - limit?: number; - /** The offset to start paginating at */ - offset?: number; -} +export interface TodoItemsAttachmentsListOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface TodoItemsCreateOptionalParams extends OperationOptions { - contentType?: string; - attachments?: TodoAttachment[]; -} +export interface TodoItemsDeleteOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface TodoItemsGetOptionalParams extends OperationOptions {} +export interface TodoItemsUpdateOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface TodoItemsUpdateOptionalParams extends OperationOptions { - contentType?: string; -} +export interface TodoItemsGetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface TodoItemsDeleteOptionalParams extends OperationOptions {} +export interface TodoItemsCreateOptionalParams extends OperationOptions { + attachments?: TodoAttachment[]; +} /** Optional parameters. */ -export interface TodoItemsAttachmentsListOptionalParams - extends OperationOptions {} +export interface TodoItemsListOptionalParams extends OperationOptions { + /** The limit to the number of items */ + limit?: number; + /** The offset to start paginating at */ + offset?: number; +} /** Optional parameters. */ -export interface TodoItemsAttachmentsCreateAttachmentOptionalParams - extends OperationOptions {} +export interface UsersCreateOptionalParams extends OperationOptions {} diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoContext.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoContext.ts index 0b4e0c56d3..068b4d2649 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoContext.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoContext.ts @@ -18,6 +18,7 @@ export function createTodo( credential: KeyCredential, options: TodoClientOptionalParams = {}, ): TodoContext { + const endpointUrl = options.endpoint ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-todo-non-branded/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -27,11 +28,7 @@ export function createTodo( ...options, userAgentOptions: { userAgentPrefix }, }; - const clientContext = getClient( - options.endpoint ?? String(endpointParam), - undefined, - updatedOptions, - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); if (isKeyCredential(credential)) { clientContext.pipeline.addPolicy({ diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/attachments/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/attachments/index.ts index de6f596f99..aaf4b51cb8 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/attachments/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/attachments/index.ts @@ -11,6 +11,10 @@ import { PageTodoAttachment, pageTodoAttachmentDeserializer, } from "../../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../../static-helpers/pagingHelpers.js"; import { StreamableMethod, PathUncheckedResponse, @@ -18,36 +22,6 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _listSend( - context: Client, - itemId: number, - options: TodoItemsAttachmentsListOptionalParams = { requestOptions: {} }, -): StreamableMethod { - return context - .path("/items/{itemId}/attachments", itemId) - .get({ ...operationOptionsToRequestParameters(options) }); -} - -export async function _listDeserialize( - result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; - if (!expectedStatuses.includes(result.status)) { - throw createRestError(result); - } - - return pageTodoAttachmentDeserializer(result.body); -} - -export async function list( - context: Client, - itemId: number, - options: TodoItemsAttachmentsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, itemId, options); - return _listDeserialize(result); -} - export function _createAttachmentSend( context: Client, itemId: number, @@ -60,6 +34,11 @@ export function _createAttachmentSend( .path("/items/{itemId}/attachments", itemId) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: todoAttachmentSerializer(contents), }); } @@ -91,3 +70,44 @@ export async function createAttachment( ); return _createAttachmentDeserialize(result); } + +export function _listSend( + context: Client, + itemId: number, + options: TodoItemsAttachmentsListOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/items/{itemId}/attachments", itemId) + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); +} + +export async function _listDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["200"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return pageTodoAttachmentDeserializer(result.body); +} + +export function list( + context: Client, + itemId: number, + options: TodoItemsAttachmentsListOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listSend(context, itemId, options), + _listDeserialize, + ["200"], + { itemName: "items" }, + ); +} diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/index.ts index 0ec78284b8..45fa0a95df 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/todoItems/index.ts @@ -12,15 +12,19 @@ import { TodoPage, todoPageDeserializer, TodoItem, + todoItemSerializer, TodoLabels, - todoLabelsSerializer, - todoAttachmentSerializer, + todoAttachmentArraySerializer, _createResponseDeserializer, _getResponseDeserializer, TodoItemPatch, todoItemPatchSerializer, _updateResponseDeserializer, } from "../../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../../static-helpers/pagingHelpers.js"; import { StreamableMethod, PathUncheckedResponse, @@ -28,66 +32,67 @@ import { operationOptionsToRequestParameters, } from "@typespec/ts-http-runtime"; -export function _listSend( +export function _$deleteSend( context: Client, - options: TodoItemsListOptionalParams = { requestOptions: {} }, + id: number, + options: TodoItemsDeleteOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/items") - .get({ + .path("/items/{id}", id) + .delete({ ...operationOptionsToRequestParameters(options), - queryParameters: { limit: options?.limit, offset: options?.offset }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _listDeserialize( +export async function _$deleteDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return todoPageDeserializer(result.body); + return; } -export async function list( +/** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ +export async function $delete( context: Client, - options: TodoItemsListOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); + id: number, + options: TodoItemsDeleteOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _$deleteSend(context, id, options); + return _$deleteDeserialize(result); } -export function _createSend( +export function _updateSend( context: Client, - item: TodoItem, - options: TodoItemsCreateOptionalParams = { requestOptions: {} }, + id: number, + patch: TodoItemPatch, + options: TodoItemsUpdateOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/items").post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "application/json", - body: { - item: { - title: item["title"], - assignedTo: item["assignedTo"], - description: item["description"], - status: item["status"], - labels: !item["labels"] - ? item["labels"] - : todoLabelsSerializer(item["labels"]), - _dummy: item["dummy"], + return context + .path("/items/{id}", id) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: "application/merge-patch+json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, }, - attachments: !options?.attachments - ? options?.attachments - : options?.attachments.map((p: any) => { - return todoAttachmentSerializer(p); - }), - }, - }); + body: todoItemPatchSerializer(patch), + }); } -export async function _createDeserialize( +export async function _updateDeserialize( result: PathUncheckedResponse, ): Promise<{ id: number; @@ -106,13 +111,14 @@ export async function _createDeserialize( throw createRestError(result); } - return _createResponseDeserializer(result.body); + return _updateResponseDeserializer(result.body); } -export async function create( +export async function update( context: Client, - item: TodoItem, - options: TodoItemsCreateOptionalParams = { requestOptions: {} }, + id: number, + patch: TodoItemPatch, + options: TodoItemsUpdateOptionalParams = { requestOptions: {} }, ): Promise<{ id: number; title: string; @@ -125,8 +131,8 @@ export async function create( completedAt?: Date; labels?: TodoLabels; }> { - const result = await _createSend(context, item, options); - return _createDeserialize(result); + const result = await _updateSend(context, id, patch, options); + return _updateDeserialize(result); } export function _getSend( @@ -136,7 +142,13 @@ export function _getSend( ): StreamableMethod { return context .path("/items/{id}", id) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _getDeserialize(result: PathUncheckedResponse): Promise<{ @@ -179,23 +191,30 @@ export async function get( return _getDeserialize(result); } -export function _updateSend( +export function _createSend( context: Client, - id: number, - patch: TodoItemPatch, - options: TodoItemsUpdateOptionalParams = { requestOptions: {} }, + item: TodoItem, + options: TodoItemsCreateOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/items/{id}", id) - .patch({ + .path("/items") + .post({ ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: todoItemPatchSerializer(patch), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: { + item: todoItemSerializer(item), + attachments: !options?.attachments + ? options?.attachments + : todoAttachmentArraySerializer(options?.attachments), + }, }); } -export async function _updateDeserialize( +export async function _createDeserialize( result: PathUncheckedResponse, ): Promise<{ id: number; @@ -214,14 +233,13 @@ export async function _updateDeserialize( throw createRestError(result); } - return _updateResponseDeserializer(result.body); + return _createResponseDeserializer(result.body); } -export async function update( +export async function create( context: Client, - id: number, - patch: TodoItemPatch, - options: TodoItemsUpdateOptionalParams = { requestOptions: {} }, + item: TodoItem, + options: TodoItemsCreateOptionalParams = { requestOptions: {} }, ): Promise<{ id: number; title: string; @@ -234,41 +252,46 @@ export async function update( completedAt?: Date; labels?: TodoLabels; }> { - const result = await _updateSend(context, id, patch, options); - return _updateDeserialize(result); + const result = await _createSend(context, item, options); + return _createDeserialize(result); } -export function _$deleteSend( +export function _listSend( context: Client, - id: number, - options: TodoItemsDeleteOptionalParams = { requestOptions: {} }, + options: TodoItemsListOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/items/{id}", id) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/items") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { limit: options?.limit, offset: options?.offset }, + }); } -export async function _$deleteDeserialize( +export async function _listDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return todoPageDeserializer(result.body); } -/** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ -export async function $delete( +export function list( context: Client, - id: number, - options: TodoItemsDeleteOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _$deleteSend(context, id, options); - return _$deleteDeserialize(result); + options: TodoItemsListOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listSend(context, options), + _listDeserialize, + ["200"], + { itemName: "items" }, + ); } diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/users/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/users/index.ts index b2eb13a210..d6ec7d21f1 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/users/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/api/users/index.ts @@ -22,6 +22,11 @@ export function _createSend( .path("/users") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: userSerializer(user), }); } diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/attachments/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/attachments/index.ts index d3a84179ae..3c44fd9152 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/attachments/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/attachments/index.ts @@ -1,38 +1,39 @@ // Licensed under the MIT License. import { - TodoItemsAttachmentsListOptionalParams, TodoItemsAttachmentsCreateAttachmentOptionalParams, + TodoItemsAttachmentsListOptionalParams, } from "../../../api/options.js"; import { TodoContext } from "../../../api/todoContext.js"; import { - list, createAttachment, + list, } from "../../../api/todoItems/attachments/index.js"; -import { TodoAttachment, PageTodoAttachment } from "../../../models/models.js"; +import { TodoAttachment } from "../../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../../static-helpers/pagingHelpers.js"; /** Interface representing a TodoItemsAttachments operations. */ export interface TodoItemsAttachmentsOperations { - list: ( - itemId: number, - options?: TodoItemsAttachmentsListOptionalParams, - ) => Promise; createAttachment: ( itemId: number, contents: TodoAttachment, options?: TodoItemsAttachmentsCreateAttachmentOptionalParams, ) => Promise; + list: ( + itemId: number, + options?: TodoItemsAttachmentsListOptionalParams, + ) => PagedAsyncIterableIterator; } export function getTodoItemsAttachments(context: TodoContext) { return { - list: (itemId: number, options?: TodoItemsAttachmentsListOptionalParams) => - list(context, itemId, options), createAttachment: ( itemId: number, contents: TodoAttachment, options?: TodoItemsAttachmentsCreateAttachmentOptionalParams, ) => createAttachment(context, itemId, contents, options), + list: (itemId: number, options?: TodoItemsAttachmentsListOptionalParams) => + list(context, itemId, options), }; } diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/index.ts index c956c49970..c87b3ff30f 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/classic/todoItems/index.ts @@ -1,26 +1,22 @@ // Licensed under the MIT License. import { - TodoItemsListOptionalParams, - TodoItemsCreateOptionalParams, - TodoItemsGetOptionalParams, - TodoItemsUpdateOptionalParams, TodoItemsDeleteOptionalParams, + TodoItemsUpdateOptionalParams, + TodoItemsGetOptionalParams, + TodoItemsCreateOptionalParams, + TodoItemsListOptionalParams, } from "../../api/options.js"; import { TodoContext } from "../../api/todoContext.js"; import { - list, - create, - get, - update, $delete, + update, + get, + create, + list, } from "../../api/todoItems/index.js"; -import { - TodoPage, - TodoItem, - TodoLabels, - TodoItemPatch, -} from "../../models/models.js"; +import { TodoItem, TodoLabels, TodoItemPatch } from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; import { TodoItemsAttachmentsOperations, getTodoItemsAttachmentsOperations, @@ -28,10 +24,19 @@ import { /** Interface representing a TodoItems operations. */ export interface TodoItemsOperations { - list: (options?: TodoItemsListOptionalParams) => Promise; - create: ( - item: TodoItem, - options?: TodoItemsCreateOptionalParams, + /** + * @fixme delete is a reserved word that cannot be used as an operation name. + * Please add @clientName("clientName") or @clientName("", "javascript") + * to the operation to override the generated name. + */ + delete: ( + id: number, + options?: TodoItemsDeleteOptionalParams, + ) => Promise; + update: ( + id: number, + patch: TodoItemPatch, + options?: TodoItemsUpdateOptionalParams, ) => Promise<{ id: number; title: string; @@ -59,10 +64,9 @@ export interface TodoItemsOperations { completedAt?: Date; labels?: TodoLabels; }>; - update: ( - id: number, - patch: TodoItemPatch, - options?: TodoItemsUpdateOptionalParams, + create: ( + item: TodoItem, + options?: TodoItemsCreateOptionalParams, ) => Promise<{ id: number; title: string; @@ -75,32 +79,26 @@ export interface TodoItemsOperations { completedAt?: Date; labels?: TodoLabels; }>; - /** - * @fixme delete is a reserved word that cannot be used as an operation name. - * Please add @clientName("clientName") or @clientName("", "javascript") - * to the operation to override the generated name. - */ - delete: ( - id: number, - options?: TodoItemsDeleteOptionalParams, - ) => Promise; + list: ( + options?: TodoItemsListOptionalParams, + ) => PagedAsyncIterableIterator; attachments: TodoItemsAttachmentsOperations; } export function getTodoItems(context: TodoContext) { return { - list: (options?: TodoItemsListOptionalParams) => list(context, options), - create: (item: TodoItem, options?: TodoItemsCreateOptionalParams) => - create(context, item, options), - get: (id: number, options?: TodoItemsGetOptionalParams) => - get(context, id, options), + delete: (id: number, options?: TodoItemsDeleteOptionalParams) => + $delete(context, id, options), update: ( id: number, patch: TodoItemPatch, options?: TodoItemsUpdateOptionalParams, ) => update(context, id, patch, options), - delete: (id: number, options?: TodoItemsDeleteOptionalParams) => - $delete(context, id, options), + get: (id: number, options?: TodoItemsGetOptionalParams) => + get(context, id, options), + create: (item: TodoItem, options?: TodoItemsCreateOptionalParams) => + create(context, item, options), + list: (options?: TodoItemsListOptionalParams) => list(context, options), }; } diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/index.ts index 4f53c4a4f4..2819fab8c4 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/index.ts @@ -1,5 +1,11 @@ // Licensed under the MIT License. +import { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./static-helpers/pagingHelpers.js"; + export { TodoClient } from "./todoClient.js"; export { TodoPage, @@ -14,14 +20,14 @@ export { User, } from "./models/index.js"; export { - UsersCreateOptionalParams, - TodoItemsListOptionalParams, - TodoItemsCreateOptionalParams, - TodoItemsGetOptionalParams, - TodoItemsUpdateOptionalParams, - TodoItemsDeleteOptionalParams, - TodoItemsAttachmentsListOptionalParams, TodoItemsAttachmentsCreateAttachmentOptionalParams, + TodoItemsAttachmentsListOptionalParams, + TodoItemsDeleteOptionalParams, + TodoItemsUpdateOptionalParams, + TodoItemsGetOptionalParams, + TodoItemsCreateOptionalParams, + TodoItemsListOptionalParams, + UsersCreateOptionalParams, TodoClientOptionalParams, } from "./api/index.js"; export { @@ -29,3 +35,4 @@ export { UsersOperations, TodoItemsAttachmentsOperations, } from "./classic/index.js"; +export { PageSettings, ContinuablePage, PagedAsyncIterableIterator }; diff --git a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/static-helpers/pagingHelpers.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/static-helpers/pagingHelpers.ts new file mode 100644 index 0000000000..39c2ece980 --- /dev/null +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/static-helpers/pagingHelpers.ts @@ -0,0 +1,273 @@ +// Licensed under the MIT License. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@typespec/ts-http-runtime"; +import { RestError } from "@typespec/ts-http-runtime"; + +/** + * 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< + TElement, + TPage, + TPageSettings + >; + /** + * 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< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + pagedResult: PagedResult, +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + for await (const page of pages) { + yield* page as unknown as TElement[]; + } +} + +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings, +>( + 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/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts index 2f64cccfbf..3ea8460958 100644 --- a/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts +++ b/packages/typespec-test/test/todo_non_branded/generated/typespec-ts/src/todoClient.ts @@ -1,10 +1,10 @@ // Licensed under the MIT License. -import { getUsersOperations, UsersOperations } from "./classic/users/index.js"; import { getTodoItemsOperations, TodoItemsOperations, } from "./classic/todoItems/index.js"; +import { getUsersOperations, UsersOperations } from "./classic/users/index.js"; import { createTodo, TodoContext, @@ -33,12 +33,12 @@ export class TodoClient { userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; - this.users = getUsersOperations(this._client); this.todoItems = getTodoItemsOperations(this._client); + this.users = getUsersOperations(this._client); } - /** The operation groups for Users */ - public readonly users: UsersOperations; - /** The operation groups for TodoItems */ + /** The operation groups for todoItems */ public readonly todoItems: TodoItemsOperations; + /** The operation groups for users */ + public readonly users: UsersOperations; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json index cdb86990a4..489d121b32 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/package.json @@ -13,8 +13,8 @@ ".": "./src/index.ts", "./models": "./src/models/index.ts", "./api": "./src/api/index.ts", - "./api/widgets": "./src/api/widgets/index.ts", - "./api/budgets": "./src/api/budgets/index.ts" + "./api/budgets": "./src/api/budgets/index.ts", + "./api/widgets": "./src/api/widgets/index.ts" }, "dialects": [ "esm", @@ -144,24 +144,6 @@ "default": "./dist/commonjs/api/index.js" } }, - "./api/widgets": { - "browser": { - "types": "./dist/browser/api/widgets/index.d.ts", - "default": "./dist/browser/api/widgets/index.js" - }, - "react-native": { - "types": "./dist/react-native/api/widgets/index.d.ts", - "default": "./dist/react-native/api/widgets/index.js" - }, - "import": { - "types": "./dist/esm/api/widgets/index.d.ts", - "default": "./dist/esm/api/widgets/index.js" - }, - "require": { - "types": "./dist/commonjs/api/widgets/index.d.ts", - "default": "./dist/commonjs/api/widgets/index.js" - } - }, "./api/budgets": { "browser": { "types": "./dist/browser/api/budgets/index.d.ts", @@ -179,6 +161,24 @@ "types": "./dist/commonjs/api/budgets/index.d.ts", "default": "./dist/commonjs/api/budgets/index.js" } + }, + "./api/widgets": { + "browser": { + "types": "./dist/browser/api/widgets/index.d.ts", + "default": "./dist/browser/api/widgets/index.js" + }, + "react-native": { + "types": "./dist/react-native/api/widgets/index.d.ts", + "default": "./dist/react-native/api/widgets/index.js" + }, + "import": { + "types": "./dist/esm/api/widgets/index.d.ts", + "default": "./dist/esm/api/widgets/index.js" + }, + "require": { + "types": "./dist/commonjs/api/widgets/index.d.ts", + "default": "./dist/commonjs/api/widgets/index.js" + } } }, "main": "./dist/commonjs/index.js", diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md index adeb64a0cc..2c61b4933b 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/review/widget_dpg.api.md @@ -21,7 +21,6 @@ export interface AnalyzeResult { // @public export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { - apiVersion?: string; updateIntervalInMs?: number; } @@ -88,7 +87,6 @@ export interface WidgetsAnalyzeWidgetOptionalParams extends OperationOptions { // @public export interface WidgetsCreateOrReplaceOptionalParams extends OperationOptions { - apiVersion?: string; updateIntervalInMs?: number; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts index ea721ea5b0..57cbbfff35 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/budgets/index.ts @@ -25,7 +25,12 @@ export function _createOrReplaceSend( .path("/budgets/widgets/createOrReplace/users/{name}", name) .put({ ...operationOptionsToRequestParameters(options), - queryParameters: { "api-version": options?.apiVersion ?? "1.0.0" }, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, body: userSerializer(resource), }); } @@ -33,7 +38,7 @@ export function _createOrReplaceSend( export async function _createOrReplaceDeserialize( result: PathUncheckedResponse, ): Promise { - const expectedStatuses = ["200", "201"]; + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } @@ -51,7 +56,7 @@ export function createOrReplace( return getLongRunningPoller( context, _createOrReplaceDeserialize, - ["200", "201"], + ["201", "200"], { updateIntervalInMs: options?.updateIntervalInMs, abortSignal: options?.abortSignal, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/index.ts index 7322ab36e0..7dc382b13d 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/index.ts @@ -2,16 +2,16 @@ // Licensed under the MIT License. export { - WidgetsListWidgetsOptionalParams, - WidgetsListWidgetsPagesOptionalParams, - WidgetsQueryWidgetsPagesOptionalParams, - WidgetsGetWidgetOptionalParams, - WidgetsCreateWidgetOptionalParams, - WidgetsCreateOrReplaceOptionalParams, - WidgetsUpdateWidgetOptionalParams, - WidgetsDeleteWidgetOptionalParams, - WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, + WidgetsAnalyzeWidgetOptionalParams, + WidgetsDeleteWidgetOptionalParams, + WidgetsUpdateWidgetOptionalParams, + WidgetsCreateOrReplaceOptionalParams, + WidgetsCreateWidgetOptionalParams, + WidgetsGetWidgetOptionalParams, + WidgetsQueryWidgetsPagesOptionalParams, + WidgetsListWidgetsPagesOptionalParams, + WidgetsListWidgetsOptionalParams, } from "./options.js"; export { createWidgetService, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/options.ts index dd32ad23e3..c97e0cf593 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/options.ts @@ -4,53 +4,49 @@ import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface WidgetsListWidgetsOptionalParams extends OperationOptions { - optionalHeader?: string; - nullableOptionalHeader?: string | null; - optionalDateHeader?: Date; - nullableDateHeader?: Date | null; +export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { + /** Delay to wait until next poll, in milliseconds. */ + updateIntervalInMs?: number; } /** Optional parameters. */ -export interface WidgetsListWidgetsPagesOptionalParams - extends OperationOptions {} - -/** Optional parameters. */ -export interface WidgetsQueryWidgetsPagesOptionalParams - extends OperationOptions {} +export interface WidgetsAnalyzeWidgetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface WidgetsGetWidgetOptionalParams extends OperationOptions {} +export interface WidgetsDeleteWidgetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface WidgetsCreateWidgetOptionalParams extends OperationOptions {} +export interface WidgetsUpdateWidgetOptionalParams extends OperationOptions { + /** The weight of the widget. This is an int32, but must be greater than zero. */ + weight?: number; + /** The color of the widget. */ + color?: "red" | "blue"; +} /** Optional parameters. */ export interface WidgetsCreateOrReplaceOptionalParams extends OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; - /** The API version to use for this operation. */ - apiVersion?: string; } /** Optional parameters. */ -export interface WidgetsUpdateWidgetOptionalParams extends OperationOptions { - /** The weight of the widget. This is an int32, but must be greater than zero. */ - weight?: number; - /** The color of the widget. */ - color?: "red" | "blue"; -} +export interface WidgetsCreateWidgetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface WidgetsDeleteWidgetOptionalParams extends OperationOptions {} +export interface WidgetsGetWidgetOptionalParams extends OperationOptions {} /** Optional parameters. */ -export interface WidgetsAnalyzeWidgetOptionalParams extends OperationOptions {} +export interface WidgetsQueryWidgetsPagesOptionalParams + extends OperationOptions {} /** Optional parameters. */ -export interface BudgetsCreateOrReplaceOptionalParams extends OperationOptions { - /** Delay to wait until next poll, in milliseconds. */ - updateIntervalInMs?: number; - /** The API version to use for this operation. */ - apiVersion?: string; +export interface WidgetsListWidgetsPagesOptionalParams + extends OperationOptions {} + +/** Optional parameters. */ +export interface WidgetsListWidgetsOptionalParams extends OperationOptions { + optionalHeader?: string; + nullableOptionalHeader?: string | null; + optionalDateHeader?: Date; + nullableDateHeader?: Date | null; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts index 612a105381..2843b360f6 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgetServiceContext.ts @@ -6,7 +6,11 @@ import { KnownVersions } from "../models/models.js"; import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; import { KeyCredential, isKeyCredential } from "@azure/core-auth"; -export interface WidgetServiceContext extends Client {} +export interface WidgetServiceContext extends Client { + /** The API version to use for this operation. */ + /** Known values of {@link KnownVersions} that the service accepts. */ + apiVersion: string; +} /** Optional parameters for the client. */ export interface WidgetServiceClientOptionalParams extends ClientOptions { @@ -20,6 +24,8 @@ export function createWidgetService( credential: KeyCredential, options: WidgetServiceClientOptionalParams = {}, ): WidgetServiceContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentInfo = `azsdk-js-widget_dpg/1.0.0-beta.1`; const userAgentPrefix = prefixFromOptions @@ -30,11 +36,7 @@ export function createWidgetService( userAgentOptions: { userAgentPrefix }, loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; - const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? String(endpointParam), - undefined, - updatedOptions, - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); if (isKeyCredential(credential)) { clientContext.pipeline.addPolicy({ @@ -46,10 +48,21 @@ export function createWidgetService( }); } clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - if (options.apiVersion) { - logger.warning( - "This client does not support client api-version, please change it at the operation level", - ); - } - return clientContext; + const apiVersion = options.apiVersion ?? "1.0.0"; + 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, apiVersion } as WidgetServiceContext; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts index 6d91eb21c7..768d13c245 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/widgets/index.ts @@ -40,199 +40,175 @@ import { import { uint8ArrayToString } from "@azure/core-util"; import { PollerLike, OperationState } from "@azure/core-lro"; -export function _listWidgetsSend( +export function _analyzeWidgetSend( context: Client, - requiredHeader: string, - bytesHeader: Uint8Array, - value: Uint8Array, - csvArrayHeader: Uint8Array[], - utcDateHeader: Date, - options: WidgetsListWidgetsOptionalParams = { requestOptions: {} }, + id: string, + options: WidgetsAnalyzeWidgetOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/widgets").get({ - ...operationOptionsToRequestParameters(options), - headers: { - "required-header": requiredHeader, - ...(options?.optionalHeader !== undefined - ? { "optional-header": options?.optionalHeader } - : {}), - ...(options?.nullableOptionalHeader !== undefined && - options?.nullableOptionalHeader !== null - ? { "nullable-optional-header": options?.nullableOptionalHeader } - : {}), - "bytes-header": uint8ArrayToString(bytesHeader, "base64"), - value: uint8ArrayToString(value, "base64"), - "csv-array-header": buildCsvCollection( - csvArrayHeader.map((p: any) => { - return uint8ArrayToString(p, "base64url"); - }), - ), - "utc-date-header": utcDateHeader.toUTCString(), - ...(options?.optionalDateHeader !== undefined - ? { - "optional-date-header": !options?.optionalDateHeader - ? options?.optionalDateHeader - : options?.optionalDateHeader.toUTCString(), - } - : {}), - ...(options?.nullableDateHeader !== undefined && - options?.nullableDateHeader !== null - ? { - "nullable-date-header": !options?.nullableDateHeader - ? options?.nullableDateHeader - : options?.nullableDateHeader.toUTCString(), - } - : {}), - }, - }); + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); + return context + .path("/widgets/{id}/analyze", id) + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _listWidgetsDeserialize( +export async function _analyzeWidgetDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return widgetArrayDeserializer(result.body); + return analyzeResultDeserializer(result.body); } -/** - * List all widgets in the system. This operation is not paginated, and returns a simple array of widgets. - * - * It does not accept any options or parameters. - */ -export async function listWidgets( +/** Analyze a widget. The only guarantee is that this method will return a string containing the results of the analysis. */ +export async function analyzeWidget( context: Client, - requiredHeader: string, - bytesHeader: Uint8Array, - value: Uint8Array, - csvArrayHeader: Uint8Array[], - utcDateHeader: Date, - options: WidgetsListWidgetsOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _listWidgetsSend( - context, - requiredHeader, - bytesHeader, - value, - csvArrayHeader, - utcDateHeader, - options, - ); - return _listWidgetsDeserialize(result); + id: string, + options: WidgetsAnalyzeWidgetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _analyzeWidgetSend(context, id, options); + return _analyzeWidgetDeserialize(result); } -export function _listWidgetsPagesSend( +export function _deleteWidgetSend( context: Client, - page: number, - pageSize: number, - options: WidgetsListWidgetsPagesOptionalParams = { requestOptions: {} }, + id: string, + options: WidgetsDeleteWidgetOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/widgets/widgets/pages") - .get({ + .path("/widgets/{id}", id) + .delete({ ...operationOptionsToRequestParameters(options), - queryParameters: { page: page, pageSize: pageSize }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _listWidgetsPagesDeserialize( +export async function _deleteWidgetDeserialize( result: PathUncheckedResponse, -): Promise<_ListWidgetsPagesResults> { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _listWidgetsPagesResultsDeserializer(result.body); + return; } -export function listWidgetsPages( +/** Delete a widget by ID. */ +export async function deleteWidget( context: Client, - page: number, - pageSize: number, - options: WidgetsListWidgetsPagesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _listWidgetsPagesSend(context, page, pageSize, options), - _listWidgetsPagesDeserialize, - ["200"], - { itemName: "results", nextLinkName: "odata.nextLink" }, - ); + id: string, + options: WidgetsDeleteWidgetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _deleteWidgetSend(context, id, options); + return _deleteWidgetDeserialize(result); } -export function _queryWidgetsPagesSend( +export function _updateWidgetSend( context: Client, - page: number, - pageSize: number, - options: WidgetsQueryWidgetsPagesOptionalParams = { requestOptions: {} }, + id: string, + options: WidgetsUpdateWidgetOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/widgets/widgets/pages") - .post({ + .path("/widgets/{id}", id) + .patch({ ...operationOptionsToRequestParameters(options), - queryParameters: { page: page, pageSize: pageSize }, + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: { weight: options?.weight, color: options?.color }, }); } -export async function _queryWidgetsPagesDeserialize( +export async function _updateWidgetDeserialize( result: PathUncheckedResponse, -): Promise<_ListWidgetsPagesResults> { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return _listWidgetsPagesResultsDeserializer(result.body); + return widgetDeserializer(result.body); } -export function queryWidgetsPages( +/** + * Update the contents of the widget. The widget ID is required in the input, but cannot be changed. All other fields + * are optional and will be updated within the widget if provided. + */ +export async function updateWidget( context: Client, - page: number, - pageSize: number, - options: WidgetsQueryWidgetsPagesOptionalParams = { requestOptions: {} }, -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - () => _queryWidgetsPagesSend(context, page, pageSize, options), - _queryWidgetsPagesDeserialize, - ["200"], - { itemName: "results", nextLinkName: "odata.nextLink" }, - ); + id: string, + options: WidgetsUpdateWidgetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _updateWidgetSend(context, id, options); + return _updateWidgetDeserialize(result); } -export function _getWidgetSend( +export function _createOrReplaceSend( context: Client, - id: string, - options: WidgetsGetWidgetOptionalParams = { requestOptions: {} }, + name: string, + resource: User, + options: WidgetsCreateOrReplaceOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/widgets/{id}", id) - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/widgets/widgets/createOrReplace/users/{name}", name) + .put({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": context.apiVersion }, + body: userSerializer(resource), + }); } -export async function _getWidgetDeserialize( +export async function _createOrReplaceDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200"]; +): Promise { + const expectedStatuses = ["201", "200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return widgetDeserializer(result.body); + return userDeserializer(result.body); } -/** Get a widget by ID. */ -export async function getWidget( +/** Long-running resource create or replace operation template. */ +export function createOrReplace( context: Client, - id: string, - options: WidgetsGetWidgetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _getWidgetSend(context, id, options); - return _getWidgetDeserialize(result); + name: string, + resource: User, + options: WidgetsCreateOrReplaceOptionalParams = { requestOptions: {} }, +): PollerLike, User> { + return getLongRunningPoller( + context, + _createOrReplaceDeserialize, + ["201", "200"], + { + updateIntervalInMs: options?.updateIntervalInMs, + abortSignal: options?.abortSignal, + getInitialResponse: () => + _createOrReplaceSend(context, name, resource, options), + resourceLocationConfig: "original-uri", + }, + ) as PollerLike, User>; } export function _createWidgetSend( @@ -241,10 +217,16 @@ export function _createWidgetSend( color: "red" | "blue", options: WidgetsCreateWidgetOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context .path("/widgets") .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, body: { weight: weight, color: color }, }); } @@ -276,148 +258,217 @@ export async function createWidget( return _createWidgetDeserialize(result); } -export function _createOrReplaceSend( +export function _getWidgetSend( context: Client, - name: string, - resource: User, - options: WidgetsCreateOrReplaceOptionalParams = { requestOptions: {} }, + id: string, + options: WidgetsGetWidgetOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/widgets/widgets/createOrReplace/users/{name}", name) - .put({ + .path("/widgets/{id}", id) + .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { "api-version": options?.apiVersion ?? "1.0.0" }, - body: userSerializer(resource), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, }); } -export async function _createOrReplaceDeserialize( +export async function _getWidgetDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["200", "201"]; +): Promise { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return userDeserializer(result.body); + return widgetDeserializer(result.body); } -/** Long-running resource create or replace operation template. */ -export function createOrReplace( +/** Get a widget by ID. */ +export async function getWidget( context: Client, - name: string, - resource: User, - options: WidgetsCreateOrReplaceOptionalParams = { requestOptions: {} }, -): PollerLike, User> { - return getLongRunningPoller( - context, - _createOrReplaceDeserialize, - ["200", "201"], - { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, - getInitialResponse: () => - _createOrReplaceSend(context, name, resource, options), - resourceLocationConfig: "original-uri", - }, - ) as PollerLike, User>; + id: string, + options: WidgetsGetWidgetOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _getWidgetSend(context, id, options); + return _getWidgetDeserialize(result); } -export function _updateWidgetSend( +export function _queryWidgetsPagesSend( context: Client, - id: string, - options: WidgetsUpdateWidgetOptionalParams = { requestOptions: {} }, + page: number, + pageSize: number, + options: WidgetsQueryWidgetsPagesOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/widgets/{id}", id) - .patch({ + .path("/widgets/widgets/pages") + .post({ ...operationOptionsToRequestParameters(options), - body: { weight: options?.weight, color: options?.color }, + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { page: page, pageSize: pageSize }, }); } -export async function _updateWidgetDeserialize( +export async function _queryWidgetsPagesDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise<_ListWidgetsPagesResults> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return widgetDeserializer(result.body); + return _listWidgetsPagesResultsDeserializer(result.body); } -/** - * Update the contents of the widget. The widget ID is required in the input, but cannot be changed. All other fields - * are optional and will be updated within the widget if provided. - */ -export async function updateWidget( +export function queryWidgetsPages( context: Client, - id: string, - options: WidgetsUpdateWidgetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _updateWidgetSend(context, id, options); - return _updateWidgetDeserialize(result); + page: number, + pageSize: number, + options: WidgetsQueryWidgetsPagesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _queryWidgetsPagesSend(context, page, pageSize, options), + _queryWidgetsPagesDeserialize, + ["200"], + { itemName: "results", nextLinkName: "odata.nextLink" }, + ); } -export function _deleteWidgetSend( +export function _listWidgetsPagesSend( context: Client, - id: string, - options: WidgetsDeleteWidgetOptionalParams = { requestOptions: {} }, + page: number, + pageSize: number, + options: WidgetsListWidgetsPagesOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context - .path("/widgets/{id}", id) - .delete({ ...operationOptionsToRequestParameters(options) }); + .path("/widgets/widgets/pages") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { page: page, pageSize: pageSize }, + }); } -export async function _deleteWidgetDeserialize( +export async function _listWidgetsPagesDeserialize( result: PathUncheckedResponse, -): Promise { - const expectedStatuses = ["204"]; +): Promise<_ListWidgetsPagesResults> { + const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return; + return _listWidgetsPagesResultsDeserializer(result.body); } -/** Delete a widget by ID. */ -export async function deleteWidget( +export function listWidgetsPages( context: Client, - id: string, - options: WidgetsDeleteWidgetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _deleteWidgetSend(context, id, options); - return _deleteWidgetDeserialize(result); + page: number, + pageSize: number, + options: WidgetsListWidgetsPagesOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listWidgetsPagesSend(context, page, pageSize, options), + _listWidgetsPagesDeserialize, + ["200"], + { itemName: "results", nextLinkName: "odata.nextLink" }, + ); } -export function _analyzeWidgetSend( +export function _listWidgetsSend( context: Client, - id: string, - options: WidgetsAnalyzeWidgetOptionalParams = { requestOptions: {} }, + requiredHeader: string, + bytesHeader: Uint8Array, + value: Uint8Array, + csvArrayHeader: Uint8Array[], + utcDateHeader: Date, + options: WidgetsListWidgetsOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context - .path("/widgets/{id}/analyze", id) - .post({ ...operationOptionsToRequestParameters(options) }); + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); + return context.path("/widgets").get({ + ...operationOptionsToRequestParameters(options), + headers: { + "required-header": requiredHeader, + ...(options?.optionalHeader !== undefined + ? { "optional-header": options?.optionalHeader } + : {}), + ...(options?.nullableOptionalHeader !== undefined && + options?.nullableOptionalHeader !== null + ? { "nullable-optional-header": options?.nullableOptionalHeader } + : {}), + "bytes-header": uint8ArrayToString(bytesHeader, "base64"), + value: uint8ArrayToString(value, "base64"), + "csv-array-header": buildCsvCollection( + csvArrayHeader.map((p: any) => { + return uint8ArrayToString(p, "base64url"); + }), + ), + "utc-date-header": utcDateHeader.toUTCString(), + ...(options?.optionalDateHeader !== undefined + ? { + "optional-date-header": !options?.optionalDateHeader + ? options?.optionalDateHeader + : options?.optionalDateHeader.toUTCString(), + } + : {}), + ...(options?.nullableDateHeader !== undefined && + options?.nullableDateHeader !== null + ? { + "nullable-date-header": !options?.nullableDateHeader + ? options?.nullableDateHeader + : options?.nullableDateHeader.toUTCString(), + } + : {}), + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _analyzeWidgetDeserialize( +export async function _listWidgetsDeserialize( result: PathUncheckedResponse, -): Promise { +): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { throw createRestError(result); } - return analyzeResultDeserializer(result.body); + return widgetArrayDeserializer(result.body); } -/** Analyze a widget. The only guarantee is that this method will return a string containing the results of the analysis. */ -export async function analyzeWidget( +/** + * List all widgets in the system. This operation is not paginated, and returns a simple array of widgets. + * + * It does not accept any options or parameters. + */ +export async function listWidgets( context: Client, - id: string, - options: WidgetsAnalyzeWidgetOptionalParams = { requestOptions: {} }, -): Promise { - const result = await _analyzeWidgetSend(context, id, options); - return _analyzeWidgetDeserialize(result); + requiredHeader: string, + bytesHeader: Uint8Array, + value: Uint8Array, + csvArrayHeader: Uint8Array[], + utcDateHeader: Date, + options: WidgetsListWidgetsOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _listWidgetsSend( + context, + requiredHeader, + bytesHeader, + value, + csvArrayHeader, + utcDateHeader, + options, + ); + return _listWidgetsDeserialize(result); } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts index 2279c56f25..fcdcddc78a 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/classic/widgets/index.ts @@ -2,27 +2,27 @@ // Licensed under the MIT License. import { - WidgetsListWidgetsOptionalParams, - WidgetsListWidgetsPagesOptionalParams, - WidgetsQueryWidgetsPagesOptionalParams, - WidgetsGetWidgetOptionalParams, - WidgetsCreateWidgetOptionalParams, - WidgetsCreateOrReplaceOptionalParams, - WidgetsUpdateWidgetOptionalParams, - WidgetsDeleteWidgetOptionalParams, WidgetsAnalyzeWidgetOptionalParams, + WidgetsDeleteWidgetOptionalParams, + WidgetsUpdateWidgetOptionalParams, + WidgetsCreateOrReplaceOptionalParams, + WidgetsCreateWidgetOptionalParams, + WidgetsGetWidgetOptionalParams, + WidgetsQueryWidgetsPagesOptionalParams, + WidgetsListWidgetsPagesOptionalParams, + WidgetsListWidgetsOptionalParams, } from "../../api/options.js"; import { WidgetServiceContext } from "../../api/widgetServiceContext.js"; import { - listWidgets, - listWidgetsPages, - queryWidgetsPages, - getWidget, - createWidget, - createOrReplace, - updateWidget, - deleteWidget, analyzeWidget, + deleteWidget, + updateWidget, + createOrReplace, + createWidget, + getWidget, + queryWidgetsPages, + listWidgetsPages, + listWidgets, } from "../../api/widgets/index.js"; import { User, Widget, AnalyzeResult } from "../../models/models.js"; import { PagedAsyncIterableIterator } from "../../static-helpers/pagingHelpers.js"; @@ -30,34 +30,30 @@ import { PollerLike, OperationState } from "@azure/core-lro"; /** Interface representing a Widgets operations. */ export interface WidgetsOperations { + /** Analyze a widget. The only guarantee is that this method will return a string containing the results of the analysis. */ + analyzeWidget: ( + id: string, + options?: WidgetsAnalyzeWidgetOptionalParams, + ) => Promise; + /** Delete a widget by ID. */ + deleteWidget: ( + id: string, + options?: WidgetsDeleteWidgetOptionalParams, + ) => Promise; /** - * List all widgets in the system. This operation is not paginated, and returns a simple array of widgets. - * - * It does not accept any options or parameters. + * Update the contents of the widget. The widget ID is required in the input, but cannot be changed. All other fields + * are optional and will be updated within the widget if provided. */ - listWidgets: ( - requiredHeader: string, - bytesHeader: Uint8Array, - value: Uint8Array, - csvArrayHeader: Uint8Array[], - utcDateHeader: Date, - options?: WidgetsListWidgetsOptionalParams, - ) => Promise; - listWidgetsPages: ( - page: number, - pageSize: number, - options?: WidgetsListWidgetsPagesOptionalParams, - ) => PagedAsyncIterableIterator; - queryWidgetsPages: ( - page: number, - pageSize: number, - options?: WidgetsQueryWidgetsPagesOptionalParams, - ) => PagedAsyncIterableIterator; - /** Get a widget by ID. */ - getWidget: ( + updateWidget: ( id: string, - options?: WidgetsGetWidgetOptionalParams, + options?: WidgetsUpdateWidgetOptionalParams, ) => Promise; + /** Long-running resource create or replace operation template. */ + createOrReplace: ( + name: string, + resource: User, + options?: WidgetsCreateOrReplaceOptionalParams, + ) => PollerLike, User>; /** * Create a new widget. * @@ -69,34 +65,66 @@ export interface WidgetsOperations { color: "red" | "blue", options?: WidgetsCreateWidgetOptionalParams, ) => Promise; - /** Long-running resource create or replace operation template. */ - createOrReplace: ( - name: string, - resource: User, - options?: WidgetsCreateOrReplaceOptionalParams, - ) => PollerLike, User>; - /** - * Update the contents of the widget. The widget ID is required in the input, but cannot be changed. All other fields - * are optional and will be updated within the widget if provided. - */ - updateWidget: ( + /** Get a widget by ID. */ + getWidget: ( id: string, - options?: WidgetsUpdateWidgetOptionalParams, + options?: WidgetsGetWidgetOptionalParams, ) => Promise; - /** Delete a widget by ID. */ - deleteWidget: ( - id: string, - options?: WidgetsDeleteWidgetOptionalParams, - ) => Promise; - /** Analyze a widget. The only guarantee is that this method will return a string containing the results of the analysis. */ - analyzeWidget: ( - id: string, - options?: WidgetsAnalyzeWidgetOptionalParams, - ) => Promise; + queryWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsQueryWidgetsPagesOptionalParams, + ) => PagedAsyncIterableIterator; + listWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsListWidgetsPagesOptionalParams, + ) => PagedAsyncIterableIterator; + /** + * List all widgets in the system. This operation is not paginated, and returns a simple array of widgets. + * + * It does not accept any options or parameters. + */ + listWidgets: ( + requiredHeader: string, + bytesHeader: Uint8Array, + value: Uint8Array, + csvArrayHeader: Uint8Array[], + utcDateHeader: Date, + options?: WidgetsListWidgetsOptionalParams, + ) => Promise; } export function getWidgets(context: WidgetServiceContext) { return { + analyzeWidget: (id: string, options?: WidgetsAnalyzeWidgetOptionalParams) => + analyzeWidget(context, id, options), + deleteWidget: (id: string, options?: WidgetsDeleteWidgetOptionalParams) => + deleteWidget(context, id, options), + updateWidget: (id: string, options?: WidgetsUpdateWidgetOptionalParams) => + updateWidget(context, id, options), + createOrReplace: ( + name: string, + resource: User, + options?: WidgetsCreateOrReplaceOptionalParams, + ) => createOrReplace(context, name, resource, options), + createWidget: ( + weight: number, + color: "red" | "blue", + options?: WidgetsCreateWidgetOptionalParams, + ) => createWidget(context, weight, color, options), + getWidget: (id: string, options?: WidgetsGetWidgetOptionalParams) => + getWidget(context, id, options), + queryWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsQueryWidgetsPagesOptionalParams, + ) => queryWidgetsPages(context, page, pageSize, options), + listWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsListWidgetsPagesOptionalParams, + ) => listWidgetsPages(context, page, pageSize, options), listWidgets: ( requiredHeader: string, bytesHeader: Uint8Array, @@ -114,34 +142,6 @@ export function getWidgets(context: WidgetServiceContext) { utcDateHeader, options, ), - listWidgetsPages: ( - page: number, - pageSize: number, - options?: WidgetsListWidgetsPagesOptionalParams, - ) => listWidgetsPages(context, page, pageSize, options), - queryWidgetsPages: ( - page: number, - pageSize: number, - options?: WidgetsQueryWidgetsPagesOptionalParams, - ) => queryWidgetsPages(context, page, pageSize, options), - getWidget: (id: string, options?: WidgetsGetWidgetOptionalParams) => - getWidget(context, id, options), - createWidget: ( - weight: number, - color: "red" | "blue", - options?: WidgetsCreateWidgetOptionalParams, - ) => createWidget(context, weight, color, options), - createOrReplace: ( - name: string, - resource: User, - options?: WidgetsCreateOrReplaceOptionalParams, - ) => createOrReplace(context, name, resource, options), - updateWidget: (id: string, options?: WidgetsUpdateWidgetOptionalParams) => - updateWidget(context, id, options), - deleteWidget: (id: string, options?: WidgetsDeleteWidgetOptionalParams) => - deleteWidget(context, id, options), - analyzeWidget: (id: string, options?: WidgetsAnalyzeWidgetOptionalParams) => - analyzeWidget(context, id, options), }; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts index aea9c394f9..8a937aec7e 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/index.ts @@ -17,16 +17,16 @@ export { KnownVersions, } from "./models/index.js"; export { - WidgetsListWidgetsOptionalParams, - WidgetsListWidgetsPagesOptionalParams, - WidgetsQueryWidgetsPagesOptionalParams, - WidgetsGetWidgetOptionalParams, - WidgetsCreateWidgetOptionalParams, - WidgetsCreateOrReplaceOptionalParams, - WidgetsUpdateWidgetOptionalParams, - WidgetsDeleteWidgetOptionalParams, - WidgetsAnalyzeWidgetOptionalParams, BudgetsCreateOrReplaceOptionalParams, + WidgetsAnalyzeWidgetOptionalParams, + WidgetsDeleteWidgetOptionalParams, + WidgetsUpdateWidgetOptionalParams, + WidgetsCreateOrReplaceOptionalParams, + WidgetsCreateWidgetOptionalParams, + WidgetsGetWidgetOptionalParams, + WidgetsQueryWidgetsPagesOptionalParams, + WidgetsListWidgetsPagesOptionalParams, + WidgetsListWidgetsOptionalParams, WidgetServiceClientOptionalParams, } from "./api/index.js"; export { BudgetsOperations, WidgetsOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts index c2c96cb208..b2173b8a55 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/restorePollerHelpers.ts @@ -2,8 +2,8 @@ // Licensed under the MIT License. import { WidgetServiceClient } from "./widgetServiceClient.js"; -import { _createOrReplaceDeserialize } from "./api/widgets/index.js"; -import { _createOrReplaceDeserialize as _createOrReplaceDeserializeBudgets } from "./api/budgets/index.js"; +import { _createOrReplaceDeserialize } from "./api/budgets/index.js"; +import { _createOrReplaceDeserialize as _createOrReplaceDeserializeWidgets } from "./api/widgets/index.js"; import { getLongRunningPoller } from "./static-helpers/pollingHelpers.js"; import { OperationOptions, @@ -82,13 +82,13 @@ interface DeserializationHelper { } const deserializeMap: Record = { - "PUT /widgets/widgets/createOrReplace/users/{name}": { + "PUT /budgets/widgets/createOrReplace/users/{name}": { deserializer: _createOrReplaceDeserialize, - expectedStatuses: ["200", "201"], + expectedStatuses: ["201", "200"], }, - "PUT /budgets/widgets/createOrReplace/users/{name}": { - deserializer: _createOrReplaceDeserializeBudgets, - expectedStatuses: ["200", "201"], + "PUT /widgets/widgets/createOrReplace/users/{name}": { + deserializer: _createOrReplaceDeserializeWidgets, + expectedStatuses: ["201", "200"], }, }; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts index db2aa3f371..d50863d698 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/widgetServiceClient.ts @@ -1,14 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { - getWidgetsOperations, - WidgetsOperations, -} from "./classic/widgets/index.js"; import { getBudgetsOperations, BudgetsOperations, } from "./classic/budgets/index.js"; +import { + getWidgetsOperations, + WidgetsOperations, +} from "./classic/widgets/index.js"; import { createWidgetService, WidgetServiceContext, @@ -38,12 +38,12 @@ export class WidgetServiceClient { userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; - this.widgets = getWidgetsOperations(this._client); this.budgets = getBudgetsOperations(this._client); + this.widgets = getWidgetsOperations(this._client); } - /** The operation groups for Widgets */ - public readonly widgets: WidgetsOperations; - /** The operation groups for Budgets */ + /** The operation groups for budgets */ public readonly budgets: BudgetsOperations; + /** The operation groups for widgets */ + public readonly widgets: WidgetsOperations; } diff --git a/packages/typespec-ts/src/contextManager.ts b/packages/typespec-ts/src/contextManager.ts index 3113d37d20..f6f53d762f 100644 --- a/packages/typespec-ts/src/contextManager.ts +++ b/packages/typespec-ts/src/contextManager.ts @@ -1,5 +1,5 @@ import { Project, SourceFile } from "ts-morph"; -import { ModularMetaTree, RlcMetaTree } from "./metaTree.js"; +import { RlcMetaTree } from "./metaTree.js"; import { EmitContext } from "@typespec/compiler"; import { SdkContext } from "@azure-tools/typespec-client-generator-core"; import { SdkTypeContext } from "./framework/hooks/sdkTypes.js"; @@ -21,7 +21,6 @@ import { ExternalDependencies } from "./framework/dependency.js"; */ type Contexts = { rlcMetaTree: RlcMetaTree; // Context for RLC types metadata. - modularMetaTree: ModularMetaTree; // Context for modular types metadata. outputProject: Project; // The TS-Morph root project context for code generation. symbolMap: Map; // Mapping of symbols to their corresponding source files. sdkTypes: SdkTypeContext; diff --git a/packages/typespec-ts/src/framework/load-static-helpers.ts b/packages/typespec-ts/src/framework/load-static-helpers.ts index 6558f19c5d..d3921dfe28 100644 --- a/packages/typespec-ts/src/framework/load-static-helpers.ts +++ b/packages/typespec-ts/src/framework/load-static-helpers.ts @@ -10,6 +10,8 @@ import { } from "ts-morph"; import { refkey } from "./refkey.js"; import { resolveProjectRoot } from "../utils/resolve-project-root.js"; +import { isAzurePackage } from "@azure-tools/rlc-common"; +import { ModularEmitterOptions } from "../modular/interfaces.js"; export const SourceFileSymbol = Symbol("SourceFile"); export interface StaticHelperMetadata { name: string; @@ -34,7 +36,8 @@ export type StaticHelpers = Record; const DEFAULT_STATIC_HELPERS_PATH = "static/static-helpers"; -export interface LoadStaticHelpersOptions { +export interface LoadStaticHelpersOptions + extends Partial { helpersAssetDirectory?: string; sourcesDir?: string; } @@ -60,6 +63,26 @@ export async function loadStaticHelpers( const addedFile = project.createSourceFile(targetPath, contents, { overwrite: true }); + addedFile.getImportDeclarations().map((i) => { + if (!isAzurePackage({ options: options.options })) { + if ( + i + .getModuleSpecifier() + .getFullText() + .includes("@azure/core-rest-pipeline") + ) { + i.setModuleSpecifier("@typespec/ts-http-runtime"); + } + if ( + i + .getModuleSpecifier() + .getFullText() + .includes("@azure-rest/core-client") + ) { + i.setModuleSpecifier("@typespec/ts-http-runtime"); + } + } + }); for (const entry of Object.values(helpers)) { if (!addedFile.getFilePath().endsWith(entry.location)) { diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 197e12920e..403ea319e4 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -55,7 +55,7 @@ import { emitContentByBuilder, emitModels } from "./utils/emitUtil.js"; import { provideContext, useContext } from "./contextManager.js"; import { EmitterOptions } from "./lib.js"; -import { ModularCodeModel } from "./modular/modularCodeModel.js"; +import { ModularEmitterOptions } from "./modular/interfaces.js"; import { Project, SourceFile } from "ts-morph"; import { buildClassicOperationFiles } from "./modular/buildClassicalOperationGroups.js"; import { buildClassicalClient } from "./modular/buildClassicalClient.js"; @@ -68,7 +68,7 @@ import { buildOperationFiles } from "./modular/buildOperations.js"; import { buildRestorePoller } from "./modular/buildRestorePoller.js"; import { buildSubpathIndexFile } from "./modular/buildSubpathIndex.js"; import { createSdkContext } from "@azure-tools/typespec-client-generator-core"; -import { emitCodeModel } from "./modular/buildCodeModel.js"; +import { transformModularEmitterOptions } from "./modular/buildModularOptions.js"; import { emitLoggerFile } from "./modular/emitLoggerFile.js"; import { emitSerializerHelpersFile } from "./modular/buildHelperSerializers.js"; import { emitTypes } from "./modular/emitModels.js"; @@ -105,7 +105,6 @@ export async function $onEmit(context: EmitContext) { >(); provideContext("rlcMetaTree", new Map()); provideContext("symbolMap", new Map()); - provideContext("modularMetaTree", new Map()); provideContext("outputProject", outputProject); provideContext("emitContext", { compilerContext: context, @@ -118,7 +117,10 @@ export async function $onEmit(context: EmitContext) { ...PagingHelpers, ...PollingHelpers }, - { sourcesDir: dpgContext.generationPathDetail?.modularSourcesDir } + { + sourcesDir: dpgContext.generationPathDetail?.modularSourcesDir, + options: rlcOptions + } ); const extraDependencies = isAzurePackage({ options: rlcOptions }) ? { @@ -136,8 +138,7 @@ export async function $onEmit(context: EmitContext) { provideSdkTypes(dpgContext); const rlcCodeModels: RLCModel[] = []; - let modularCodeModel: ModularCodeModel; - + let modularEmitterOptions: ModularEmitterOptions; // 1. Clear sources folder await clearSrcFolder(); // 2. Generate RLC code model @@ -152,7 +153,7 @@ export async function $onEmit(context: EmitContext) { } // 5. Generate metadata and test files - await generateMetadataAndTest(); + await generateMetadataAndTest(dpgContext); async function enrichDpgContext() { const generationPathDetail: GenerationDirDetail = @@ -243,9 +244,8 @@ export async function $onEmit(context: EmitContext) { dpgContext.generationPathDetail?.modularSourcesDir ?? "src"; const project = useContext("outputProject"); emitSerializerHelpersFile(project, modularSourcesRoot); - modularCodeModel = emitCodeModel( + modularEmitterOptions = transformModularEmitterOptions( dpgContext, - serviceNameToRlcModelsMap, modularSourcesRoot, project, { @@ -253,7 +253,7 @@ export async function $onEmit(context: EmitContext) { } ); - emitLoggerFile(modularCodeModel, project, modularSourcesRoot); + emitLoggerFile(modularEmitterOptions, modularSourcesRoot); const rootIndexFile = project.createSourceFile( `${modularSourcesRoot}/index.ts`, @@ -263,10 +263,10 @@ export async function $onEmit(context: EmitContext) { } ); - const isMultiClients = modularCodeModel.clients.length > 1; + const isMultiClients = dpgContext.sdkPackage.clients.length > 1; emitTypes(dpgContext, { sourceRoot: modularSourcesRoot }); - buildSubpathIndexFile(modularCodeModel, "models"); + buildSubpathIndexFile(dpgContext, modularEmitterOptions, "models"); // Enable modular sample generation when explicitly set to true or MPG if (emitterOptions?.generateSample === true) { const samples = emitSamples(dpgContext); @@ -276,29 +276,51 @@ export async function $onEmit(context: EmitContext) { dpgContext.rlcOptions!.generateSample = true; } } - for (const subClient of modularCodeModel.clients) { - buildApiOptions(dpgContext, subClient, modularCodeModel); - buildOperationFiles(subClient, dpgContext, modularCodeModel); - buildClientContext(subClient, dpgContext, modularCodeModel); - buildRestorePoller(modularCodeModel, subClient); + for (const subClient of dpgContext.sdkPackage.clients) { + buildApiOptions(dpgContext, subClient, modularEmitterOptions); + buildOperationFiles(dpgContext, subClient, modularEmitterOptions); + buildClientContext(dpgContext, subClient, modularEmitterOptions); + buildRestorePoller(dpgContext, subClient, modularEmitterOptions); if (dpgContext.rlcOptions?.hierarchyClient) { - buildSubpathIndexFile(modularCodeModel, "api", subClient); + buildSubpathIndexFile( + dpgContext, + modularEmitterOptions, + "api", + subClient + ); } else { - buildSubpathIndexFile(modularCodeModel, "api", subClient, { - exportIndex: true - }); + buildSubpathIndexFile( + dpgContext, + modularEmitterOptions, + "api", + subClient, + { + exportIndex: true + } + ); } - buildClassicalClient(subClient, dpgContext, modularCodeModel); - buildClassicOperationFiles(dpgContext, modularCodeModel, subClient); - buildSubpathIndexFile(modularCodeModel, "classic", subClient, { - exportIndex: true, - interfaceOnly: true - }); + buildClassicalClient(dpgContext, subClient, modularEmitterOptions); + buildClassicOperationFiles(dpgContext, subClient, modularEmitterOptions); + buildSubpathIndexFile( + dpgContext, + modularEmitterOptions, + "classic", + subClient, + { + exportIndex: true, + interfaceOnly: true + } + ); if (isMultiClients) { - buildSubClientIndexFile(subClient, modularCodeModel); + buildSubClientIndexFile(dpgContext, subClient, modularEmitterOptions); } - buildRootIndex(subClient, modularCodeModel, rootIndexFile); + buildRootIndex( + dpgContext, + subClient, + modularEmitterOptions, + rootIndexFile + ); } binder.resolveAllReferences(modularSourcesRoot); @@ -318,12 +340,12 @@ export async function $onEmit(context: EmitContext) { await emitContentByBuilder( program, () => ({ content: file.getFullText(), path: file.getFilePath() }), - modularCodeModel as any + modularEmitterOptions as any ); } } - async function generateMetadataAndTest() { + async function generateMetadataAndTest(context: SdkContext) { const project = useContext("outputProject"); if (rlcCodeModels.length === 0 || !rlcCodeModels[0]) { return; @@ -359,7 +381,7 @@ export async function $onEmit(context: EmitContext) { let modularPackageInfo = {}; if (option.isModularLibrary) { modularPackageInfo = { - exports: getModuleExports(modularCodeModel) + exports: getModuleExports(context, modularEmitterOptions) }; if (isAzureFlavor) { modularPackageInfo = { @@ -367,7 +389,10 @@ export async function $onEmit(context: EmitContext) { dependencies: { "@azure/core-util": "^1.9.2" }, - clientContextPaths: getRelativeContextPaths(modularCodeModel) + clientContextPaths: getRelativeContextPaths( + context, + modularEmitterOptions + ) }; } } @@ -388,7 +413,7 @@ export async function $onEmit(context: EmitContext) { await emitContentByBuilder( program, () => ({ content: file.getFullText(), path: file.getFilePath() }), - modularCodeModel as any + modularEmitterOptions as any ); } } @@ -413,9 +438,12 @@ export async function $onEmit(context: EmitContext) { } } - function getRelativeContextPaths(codeModel: ModularCodeModel) { - return codeModel.clients - .map((subClient) => getClientContextPath(subClient, codeModel)) + function getRelativeContextPaths( + context: SdkContext, + options: ModularEmitterOptions + ) { + return context.sdkPackage.clients + .map((subClient) => getClientContextPath(context, subClient, options)) .map((path) => path.substring(path.indexOf("src"))); } } diff --git a/packages/typespec-ts/src/metaTree.ts b/packages/typespec-ts/src/metaTree.ts index b6d42045a8..3a14e99c26 100644 --- a/packages/typespec-ts/src/metaTree.ts +++ b/packages/typespec-ts/src/metaTree.ts @@ -1,14 +1,8 @@ import { Schema as RlcType } from "@azure-tools/rlc-common"; -import { Type as ModularType } from "./modular/modularCodeModel.js"; import { Type } from "@typespec/compiler"; export interface RlcTypeMetadata { rlcType: RlcType; } -export interface ModularTypeMetadata { - modularType: ModularType; -} - export type RlcMetaTree = Map; -export type ModularMetaTree = Map; diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index cf625dcf29..af58e0bbf2 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -5,7 +5,7 @@ import { SourceFile, StructureKind } from "ts-morph"; -import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; import { NameType, normalizeName } from "@azure-tools/rlc-common"; import { buildUserAgentOptions, @@ -13,39 +13,48 @@ import { } from "./helpers/clientHelpers.js"; import { getClassicalClientName, - getClassicalLayerPrefix, getClientName } from "./helpers/namingHelpers.js"; import { SdkContext } from "../utils/interfaces.js"; import { getDocsFromDescription } from "./helpers/docsHelpers.js"; import { getOperationFunction } from "./helpers/operationHelpers.js"; -import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; +import { + getModularClientOptions, + isRLCMultiEndpoint +} from "../utils/clientUtils.js"; import { resolveReference } from "../framework/reference.js"; -import { shouldPromoteSubscriptionId } from "./helpers/classicalOperationHelpers.js"; import { useDependencies } from "../framework/hooks/useDependencies.js"; +import { + SdkClientType, + SdkServiceMethod, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { getMethodHierarchiesMap } from "../utils/operationUtil.js"; export function buildClassicalClient( - _client: Client, dpgContext: SdkContext, - codeModel: ModularCodeModel + client: SdkClientType, + emitterOptions: ModularEmitterOptions ) { - const { description, tcgcClient: client } = _client; const dependencies = useDependencies(); const modularClientName = getClientName(client); const classicalClientName = `${getClassicalClientName(client)}`; - const classicalParams = getClientParametersDeclaration(_client, dpgContext, { + const classicalParams = getClientParametersDeclaration(client, dpgContext, { requiredOnly: true }); - const contextParams = getClientParametersDeclaration(_client, dpgContext, { - onClientOnly: true, + const contextParams = getClientParametersDeclaration(client, dpgContext, { + onClientOnly: false, requiredOnly: true }); - const srcPath = codeModel.modularOptions.sourceRoot; - const subfolder = _client.subfolder ?? ""; + const srcPath = emitterOptions.modularOptions.sourceRoot; + const { subfolder, rlcClientName } = getModularClientOptions( + dpgContext, + client + ); - const clientFile = codeModel.project.createSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}${normalizeName( + const clientFile = emitterOptions.project.createSourceFile( + `${srcPath}/${subfolder && subfolder !== "" ? subfolder + "/" : ""}${normalizeName( classicalClientName, NameType.File )}.ts` @@ -68,13 +77,13 @@ export function buildClassicalClient( if (isRLCMultiEndpoint(dpgContext)) { clientClass.addProperty({ name: "_client", - type: `Client.${_client.rlcClientName}`, + type: `Client.${rlcClientName}`, scope: Scope.Private }); } else { clientClass.addProperty({ name: "_client", - type: `${_client.rlcClientName}`, + type: `${rlcClientName}`, scope: Scope.Private }); } @@ -89,7 +98,7 @@ export function buildClassicalClient( // TODO: We may need to generate constructor overloads at some point. Here we'd do that. const constructor = clientClass.addConstructor({ - docs: getDocsFromDescription(description), + docs: getDocsFromDescription(client.doc), parameters: classicalParams }); @@ -99,7 +108,7 @@ export function buildClassicalClient( if (x === "options") { return `{...options, userAgentOptions: ${buildUserAgentOptions( constructor, - codeModel, + emitterOptions, "azsdk-js-client" )}}`; } else { @@ -112,8 +121,8 @@ export function buildClassicalClient( ]); constructor.addStatements(`this.pipeline = this._client.pipeline;`); - buildClientOperationGroups(clientFile, _client, dpgContext, clientClass); - importAllApis(clientFile, srcPath, subfolder); + buildClientOperationGroups(clientFile, client, dpgContext, clientClass); + importAllApis(clientFile, srcPath, subfolder ?? ""); clientFile.fixUnusedIdentifiers(); return clientFile; } @@ -125,7 +134,7 @@ function importAllApis( ) { const project = clientFile.getProject(); const apiModels = project.getSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}api/index.ts` + `${srcPath}/${subfolder && subfolder !== "" ? subfolder + "/" : ""}api/index.ts` ); if (!apiModels) { @@ -140,96 +149,85 @@ function importAllApis( }); } +function generateMethod( + context: SdkContext, + clientType: string, + method: [string[], SdkServiceMethod] +) { + const declarations = getOperationFunction(context, method, clientType); + const result: MethodDeclarationStructure = { + docs: declarations.docs, + name: declarations.propertyName ?? declarations.name ?? "FIXME", + kind: StructureKind.Method, + returnType: declarations.returnType, + parameters: declarations.parameters?.filter((p) => p.name !== "context"), + statements: `return ${declarations.name}(${[ + "this._client", + ...[ + declarations.parameters + ?.map((p) => p.name) + .filter((p) => p !== "context") + ] + ].join(",")})` + }; + return result; +} function buildClientOperationGroups( clientFile: SourceFile, - client: Client, + client: SdkClientType, dpgContext: SdkContext, clientClass: ClassDeclaration ) { let clientType = "Client"; - const subfolder = client.subfolder ?? ""; + const { subfolder } = getModularClientOptions(dpgContext, client); if (subfolder && subfolder !== "") { clientType = `Client.${clientClass.getName()}`; } - for (const operationGroup of client.operationGroups) { - const groupName = normalizeName( - operationGroup.namespaceHierarchies[0] ?? operationGroup.propertyName, - NameType.Property - ); - // TODO: remove this logic once client-level parameter design is finalized - // https://github.com/Azure/autorest.typescript/issues/2618 - const hasSubscriptionIdPromoted = shouldPromoteSubscriptionId( - dpgContext, - operationGroup - ); - if (groupName === "") { - operationGroup.operations.forEach((op) => { - const declarations = getOperationFunction(dpgContext, op, clientType); - const method: MethodDeclarationStructure = { - docs: declarations.docs, - name: declarations.propertyName ?? declarations.name ?? "FIXME", - kind: StructureKind.Method, - returnType: declarations.returnType, - parameters: declarations.parameters?.filter( - (p) => p.name !== "context" - ), - statements: `return ${declarations.name}(${[ - "this._client", - ...[ - declarations.parameters - ?.map((p) => p.name) - .filter((p) => p !== "context") - ] - ].join(",")})` - }; + const methodMap = getMethodHierarchiesMap(dpgContext, client); + for (const [prefixKey, operations] of methodMap) { + const prefixes = prefixKey.split("/"); + if (prefixKey === "") { + operations.forEach((op) => { + const method = generateMethod(dpgContext, clientType, [prefixes, op]); clientClass.addMethod(method); }); - continue; - } - const operationName = `get${getClassicalLayerPrefix( - operationGroup, - NameType.Interface, - "", - 0 - )}Operations`; - const propertyType = `${getClassicalLayerPrefix( - operationGroup, - NameType.Interface, - "", - 0 - )}Operations`; - const existProperty = clientClass.getProperties().filter((p) => { - return p.getName() === groupName; - }); - if (!existProperty || existProperty.length === 0) { - clientFile.addImportDeclaration({ - namedImports: [operationName, propertyType], - moduleSpecifier: `./classic/${getClassicalLayerPrefix( - operationGroup, - NameType.File, - "/", - 0 - )}/index.js` + } else { + const groupName = normalizeName(prefixes[0] ?? "", NameType.Property); + const operationName = `get${normalizeName( + groupName, + NameType.OperationGroup + )}Operations`; + const propertyType = `${normalizeName( + groupName, + NameType.OperationGroup + )}Operations`; + const existProperty = clientClass.getProperties().filter((p) => { + return p.getName() === groupName; }); - clientClass.addProperty({ - name: groupName, - type: propertyType, - scope: Scope.Public, - isReadonly: true, - docs: ["The operation groups for " + operationGroup.propertyName] - }); - clientClass - .getConstructors()[0] - ?.addStatements( - `this.${groupName} = get${getClassicalLayerPrefix( - operationGroup, - NameType.Interface, - "", - 0 - )}Operations(this._client${ - hasSubscriptionIdPromoted ? ", subscriptionId" : "" - })` - ); + if (!existProperty || existProperty.length === 0) { + clientFile.addImportDeclaration({ + namedImports: [operationName, propertyType], + moduleSpecifier: `./classic/${normalizeName( + groupName, + NameType.File + )}/index.js` + }); + clientClass.addProperty({ + name: groupName, + type: propertyType, + scope: Scope.Public, + isReadonly: true, + docs: ["The operation groups for " + groupName] + }); + clientClass + .getConstructors()[0] + ?.addStatements( + `this.${groupName} = get${normalizeName( + groupName, + NameType.OperationGroup + )}Operations(this._client)` + ); + } } } } diff --git a/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts b/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts index 921fc68f9d..9f9759b508 100644 --- a/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts +++ b/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts @@ -2,63 +2,68 @@ import { NameType } from "@azure-tools/rlc-common"; import { SourceFile } from "ts-morph"; import { getClassicalOperation } from "./helpers/classicalOperationHelpers.js"; import { getClassicalLayerPrefix } from "./helpers/namingHelpers.js"; -import { - Client, - ModularCodeModel, - OperationGroup -} from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; import { SdkContext } from "../utils/interfaces.js"; +import { getMethodHierarchiesMap } from "../utils/operationUtil.js"; +import { + SdkClientType, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { getModularClientOptions } from "../utils/clientUtils.js"; export function buildClassicOperationFiles( dpgContext: SdkContext, - codeModel: ModularCodeModel, - client: Client + client: SdkClientType, + emitterOptions: ModularEmitterOptions ) { + // const sdkPackage = dpgContext.sdkPackage; + const { subfolder } = getModularClientOptions(dpgContext, client); const classicOperationFiles: Map = new Map< string, SourceFile >(); - for (const operationGroup of client.operationGroups) { - if (operationGroup.namespaceHierarchies.length > 0) { + const methodMap = getMethodHierarchiesMap(dpgContext, client); + for (const [prefixKey, operations] of methodMap) { + const prefixes = prefixKey.split("/"); + if (prefixes.length > 0 && prefixKey !== "") { const classicOperationFileName = - operationGroup.namespaceHierarchies.length > 0 + prefixes.length > 0 ? `${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.File, "/", - operationGroup.namespaceHierarchies.length - 1 + prefixes.length - 1 )}/index` : // When the program has no operation groups defined all operations are put // into a nameless operation group. We'll call this operations. "index"; - const subfolder = client.subfolder; - const srcPath = codeModel.modularOptions.sourceRoot; + const srcPath = emitterOptions.modularOptions.sourceRoot; const classicFile = classicOperationFiles.get(classicOperationFileName) ?? - codeModel.project.createSourceFile( + emitterOptions.project.createSourceFile( `${srcPath}/${ subfolder && subfolder !== "" ? subfolder + "/" : "" }classic/${classicOperationFileName}.ts` ); - getClassicalOperation(dpgContext, client, classicFile, operationGroup); + getClassicalOperation(dpgContext, client, classicFile, [ + prefixes, + operations + ]); - importApis(classicFile, client, codeModel, operationGroup); + importApis(dpgContext, classicFile, client, emitterOptions, prefixes); // We need to import the paging helpers and types explicitly because ts-morph may not be able to find them. classicOperationFiles.set(classicOperationFileName, classicFile); } } - for (const operationGroup of client.operationGroups) { - if (operationGroup.namespaceHierarchies.length > 0) { - for ( - let layer = 0; - layer < operationGroup.namespaceHierarchies.length - 1; - layer++ - ) { + for (const [prefixKey, operations] of methodMap) { + const prefixes = prefixKey.split("/"); + if (prefixes.length > 0 && prefixKey !== "") { + for (let layer = 0; layer < prefixes.length - 1; layer++) { const classicOperationFileName = - operationGroup.namespaceHierarchies.length > 0 + prefixes.length > 0 ? `${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.File, "/", layer @@ -66,12 +71,10 @@ export function buildClassicOperationFiles( : // When the program has no operation groups defined all operations are put // into a nameless operation group. We'll call this operations. "index"; - - const subfolder = client.subfolder; - const srcPath = codeModel.modularOptions.sourceRoot; + const srcPath = emitterOptions.modularOptions.sourceRoot; const classicFile = classicOperationFiles.get(classicOperationFileName) ?? - codeModel.project.createSourceFile( + emitterOptions.project.createSourceFile( `${srcPath}/${ subfolder && subfolder !== "" ? subfolder + "/" : "" }classic/${classicOperationFileName}.ts` @@ -80,10 +83,17 @@ export function buildClassicOperationFiles( dpgContext, client, classicFile, - operationGroup, + [prefixes, operations], + layer + ); + importApis( + dpgContext, + classicFile, + client, + emitterOptions, + prefixes, layer ); - importApis(classicFile, client, codeModel, operationGroup, layer); classicOperationFiles.set(classicOperationFileName, classicFile); } } @@ -92,27 +102,23 @@ export function buildClassicOperationFiles( } function importApis( + context: SdkContext, classicFile: SourceFile, - client: Client, - modularCodeModel: ModularCodeModel, - operationGroup: OperationGroup, - layer: number = operationGroup.namespaceHierarchies.length - 1 + client: SdkClientType, + emitterOptions: ModularEmitterOptions, + prefixes: string[], + layer: number = prefixes.length - 1 ) { + const { subfolder } = getModularClientOptions(context, client); const classicOperationFileName = - operationGroup.namespaceHierarchies.length > 0 - ? `${getClassicalLayerPrefix( - operationGroup, - NameType.File, - "/", - layer - )}/index` + prefixes.length > 0 && prefixes[0] !== "" + ? `${getClassicalLayerPrefix(prefixes, NameType.File, "/", layer)}/index` : // When the program has no operation groups defined all operations are put // into a nameless operation group. We'll call this operations. "index"; - const subfolder = client.subfolder; - const srcPath = modularCodeModel.modularOptions.sourceRoot; - const apiFile = modularCodeModel.project.getSourceFile( + const srcPath = emitterOptions.modularOptions.sourceRoot; + const apiFile = emitterOptions.project.getSourceFile( `${srcPath}/${ subfolder && subfolder !== "" ? subfolder + "/" : "" }api/${classicOperationFileName}.ts` @@ -134,7 +140,7 @@ function importApis( if (exported.length > 0 && !existApiImport) { classicFile.addImportDeclaration({ moduleSpecifier: `${"../".repeat( - operationGroup.namespaceHierarchies.length + 1 + prefixes.length + 1 )}api/${classicOperationFileName}.js`, namedImports: exported }); diff --git a/packages/typespec-ts/src/modular/buildClientContext.ts b/packages/typespec-ts/src/modular/buildClientContext.ts index 41415b531d..4bfc2ca605 100644 --- a/packages/typespec-ts/src/modular/buildClientContext.ts +++ b/packages/typespec-ts/src/modular/buildClientContext.ts @@ -1,4 +1,4 @@ -import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; import { NameType, isAzurePackage, @@ -22,20 +22,24 @@ import { resolveReference } from "../framework/reference.js"; import { useDependencies } from "../framework/hooks/useDependencies.js"; import { buildEnumTypes, getApiVersionEnum } from "./emitModels.js"; import { + SdkClientType, SdkHttpParameter, - SdkParameter + SdkParameter, + SdkServiceOperation } from "@azure-tools/typespec-client-generator-core"; +import { getModularClientOptions } from "../utils/clientUtils.js"; /** * This function gets the path of the file containing the modular client context */ export function getClientContextPath( - _client: Client, - codeModel: ModularCodeModel + context: SdkContext, + client: SdkClientType, + emitterOptions: ModularEmitterOptions ): string { - const { subfolder, tcgcClient: client } = _client; + const { subfolder } = getModularClientOptions(context, client); const name = getClientName(client); - const srcPath = codeModel.modularOptions.sourceRoot; + const srcPath = emitterOptions.modularOptions.sourceRoot; const contentPath = `${srcPath}/${ subfolder && subfolder !== "" ? subfolder + "/" : "" }api/${normalizeName(name, NameType.File)}Context.ts`; @@ -46,39 +50,60 @@ export function getClientContextPath( * This function creates the file containing the modular client context */ export function buildClientContext( - _client: Client, dpgContext: SdkContext, - codeModel: ModularCodeModel + client: SdkClientType, + emitterOptions: ModularEmitterOptions ): SourceFile { - const { description, tcgcClient: client } = _client; const dependencies = useDependencies(); const name = getClientName(client); - const requiredParams = getClientParametersDeclaration(_client, dpgContext, { + const { rlcClientName } = getModularClientOptions(dpgContext, client); + const requiredParams = getClientParametersDeclaration(client, dpgContext, { onClientOnly: false, - requiredOnly: true + requiredOnly: true, + apiVersionAsRequired: true }); - const clientContextFile = codeModel.project.createSourceFile( - getClientContextPath(_client, codeModel) + const clientContextFile = emitterOptions.project.createSourceFile( + getClientContextPath(dpgContext, client, emitterOptions) ); clientContextFile.addInterface({ isExported: true, - name: `${_client.rlcClientName}`, + name: `${rlcClientName}`, extends: [resolveReference(dependencies.Client)], - docs: getDocsFromDescription(description) + docs: getDocsFromDescription(client.doc), + properties: getClientParameters(client, dpgContext, { + onClientOnly: false, + requiredOnly: true, + apiVersionAsRequired: true + }) + .filter((p) => { + const clientParamName = getClientParameterName(p); + return ( + clientParamName !== "endpointParam" && + clientParamName !== "credential" + ); + }) + .map((p) => { + return { + name: getClientParameterName(p), + type: getTypeExpression(dpgContext, p.type), + hasQuestionToken: false, + docs: getDocsWithKnownVersion(dpgContext, p) + }; + }) }); clientContextFile.addInterface({ name: `${name}ClientOptionalParams`, isExported: true, extends: [resolveReference(dependencies.ClientOptions)], - properties: getClientParameters(_client, dpgContext, { + properties: getClientParameters(client, dpgContext, { optionalOnly: true }) .filter((p) => p.name !== "endpoint") .map((p) => { return { - name: normalizeName(p.name, NameType.Parameter), + name: getClientParameterName(p), type: p.name.toLowerCase() === "apiversion" ? "string" @@ -92,31 +117,36 @@ export function buildClientContext( // TODO use binder here // (for now) now logger for unbranded pkgs - if (isAzurePackage(codeModel)) { + if (isAzurePackage(emitterOptions)) { clientContextFile.addImportDeclaration({ moduleSpecifier: - codeModel.clients.length > 1 ? "../../logger.js" : "../logger.js", + dpgContext.sdkPackage.clients.length > 1 + ? "../../logger.js" + : "../logger.js", namedImports: ["logger"] }); } const factoryFunction = clientContextFile.addFunction({ - docs: getDocsFromDescription(description), + docs: getDocsFromDescription(client.doc), name: `create${name}`, - returnType: `${_client.rlcClientName}`, - parameters: requiredParams, + returnType: `${rlcClientName}`, + parameters: getClientParametersDeclaration(client, dpgContext, { + onClientOnly: false, + requiredOnly: true + }), isExported: true }); const endpointParam = buildGetClientEndpointParam( factoryFunction, dpgContext, - _client + client ); - const credentialParam = buildGetClientCredentialParam(_client, codeModel); + const credentialParam = buildGetClientCredentialParam(client, emitterOptions); const optionsParam = buildGetClientOptionsParam( factoryFunction, - codeModel, + emitterOptions, endpointParam ); @@ -127,7 +157,7 @@ export function buildClientContext( ); const { customHttpAuthHeaderName, customHttpAuthSharedKeyPrefix } = - codeModel.options; + emitterOptions.options; if (customHttpAuthHeaderName && customHttpAuthSharedKeyPrefix) { factoryFunction.addStatements(` @@ -144,17 +174,28 @@ export function buildClientContext( } let apiVersionPolicyStatement = `clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" });`; + const apiVersionParam = getClientParameters(client, dpgContext).find( + (x) => x.isApiVersionParam + ); + const endpointParameter = getClientParameters(client, dpgContext, { + onClientOnly: false, + requiredOnly: true, + skipEndpointTemplate: true + }).find((x) => x.kind === "endpoint"); + if (apiVersionParam) { + const templateArguments = + endpointParameter && endpointParameter.type.kind === "endpoint" + ? endpointParameter.type.templateArguments + : endpointParameter && endpointParameter.type.kind === "union" + ? endpointParameter.type.variantTypes[0]?.templateArguments + : []; + const apiVersionInEndpoint = + templateArguments && templateArguments.find((p) => p.isApiVersionParam); + if (!apiVersionInEndpoint && apiVersionParam.clientDefaultValue) { + apiVersionPolicyStatement += `const apiVersion = options.apiVersion ?? "${apiVersionParam.clientDefaultValue}";`; + } - if (dpgContext.hasApiVersionInClient) { - const apiVersionParam = getClientParameters(_client, dpgContext).find( - (x) => x.isApiVersionParam && x.kind === "method" - ); - - if (apiVersionParam) { - if (apiVersionParam.clientDefaultValue) { - apiVersionPolicyStatement += `const apiVersion = options.apiVersion ?? "${apiVersionParam.clientDefaultValue}";`; - } - + if (apiVersionParam.kind === "method") { apiVersionPolicyStatement += ` clientContext.pipeline.addPolicy({ name: 'ClientApiVersionPolicy', @@ -172,20 +213,36 @@ export function buildClientContext( }, });`; } - } else if (isAzurePackage(codeModel)) { + } else if (isAzurePackage(emitterOptions)) { apiVersionPolicyStatement += ` - if (options.apiVersion) { - logger.warning("This client does not support client api-version, please change it at the operation level"); - }`; + if (options.apiVersion) { + logger.warning("This client does not support client api-version, please change it at the operation level"); + }`; } else { apiVersionPolicyStatement += ` - if (options.apiVersion) { - console.warn("This client does not support client api-version, please change it at the operation level"); - }`; + if (options.apiVersion) { + console.warn("This client does not support client api-version, please change it at the operation level"); + }`; } factoryFunction.addStatements(apiVersionPolicyStatement); - factoryFunction.addStatements("return clientContext;"); + const contextRequiredParam = requiredParams.filter( + (p) => + p.name !== "endpointParam" && + p.name !== "credential" && + p.name !== "options" + ); + if (contextRequiredParam.length) { + factoryFunction.addStatements( + `return { ...clientContext, ${contextRequiredParam + .map((p) => { + return p.name; + }) + .join(", ")}} as ${rlcClientName};` + ); + } else { + factoryFunction.addStatements(`return clientContext;`); + } clientContextFile.fixMissingImports( {}, diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts deleted file mode 100644 index 9f0c8e24c6..0000000000 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ /dev/null @@ -1,1965 +0,0 @@ -import { - Enum, - EnumMember, - IntrinsicScalarName, - Model, - ModelProperty, - Namespace, - NoTarget, - Operation, - Program, - Scalar, - Type, - Union, - UsageFlags, - getDiscriminator, - getDoc, - getEncode, - getFriendlyName, - getMaxItems, - getMaxLength, - getMaxValue, - getMinItems, - getMinLength, - getMinValue, - getPattern, - getPropertyType, - getSummary, - getVisibility, - isErrorModel, - isNeverType, - isNullType, - isNumericType, - isStringType, - isTemplateDeclarationOrInstance, - isType, - isVoidType, - listServices -} from "@typespec/compiler"; -import { - Header, - Client as HrlcClient, - Operation as HrlcOperation, - Type as HrlcType, - ModularCodeModel, - OperationGroup, - Parameter, - Property, - Response -} from "./modularCodeModel.js"; -import { - HttpAuth, - HttpOperation, - HttpOperationParameter, - HttpOperationResponse, - HttpOperationResponseContent, - HttpServer, - getAuthentication, - getServers, - isSharedRoute -} from "@typespec/http"; -import { - NameType, - RLCModel, - buildRuntimeImports, - isAzurePackage, - normalizeName -} from "@azure-tools/rlc-common"; -import { - SdkBuiltInType, - SdkClient, - SdkType, - getAllModels, - getClientNamespaceString, - getClientType, - getDefaultApiVersion, - getHttpOperationWithCache, - getLibraryName, - getSdkUnion, - getWireName, - isApiVersion, - listClients, - listOperationGroups, - listOperationsInOperationGroup -} from "@azure-tools/typespec-client-generator-core"; -import { - buildCoreTypeInfo, - getBodyType, - getDefaultApiVersionString, - getEffectiveSchemaType, - isAzureCoreErrorType, - isBodyRequired, - isSchemaProperty -} from "../utils/modelUtils.js"; -import { camelToSnakeCase, toCamelCase } from "../utils/casingUtils.js"; -import { - extractPagedMetadataNested, - getOperationGroupName, - getOperationName, - isBinaryPayload, - isIgnoredHeaderParam, - isLongRunningOperation, - parseItemName, - parseNextLinkName -} from "../utils/operationUtil.js"; -import { - getLroMetadata, - getPagedResult, - LroMetadata -} from "@azure-tools/typespec-azure-core"; - -import { Project } from "ts-morph"; -import { SdkContext } from "../utils/interfaces.js"; -import { getAddedOnVersions } from "@typespec/versioning"; -import { getModelNamespaceName } from "../utils/namespaceUtils.js"; -import { getSupportedHttpAuth } from "../utils/credentialUtils.js"; -import { getType as getTypeName } from "./helpers/typeHelpers.js"; -import { reportDiagnostic } from "../lib.js"; -import { useContext } from "../contextManager.js"; -import { normalizeModelName } from "./emitModels.js"; - -interface HttpServerParameter { - type: "endpointPath"; - name: string; - param: ModelProperty; -} - -interface CredentialType { - kind: "Credential"; - scheme: HttpAuth; -} - -interface CredentialTypeUnion { - kind: "CredentialTypeUnion"; - types: CredentialType[]; -} - -type EmitterType = Type | CredentialType | CredentialTypeUnion; - -let CASING: "camel" | "snake" = "snake"; - -export interface EmitterOptions { - "basic-setup-py"?: boolean; - "package-version"?: string; - "package-name"?: string; - "output-dir"?: string; - "package-mode"?: string; - debug?: boolean; -} - -function applyCasing( - name: string, - options: { casing: "snake" | "camel" } = { casing: "snake" } -): string { - if (options.casing === "camel") { - return toCamelCase(name); - } - - return camelToSnakeCase(name); -} - -const typesMap = new Map(); -const simpleTypesMap = new Map(); -const endpointPathParameters: Record[] = []; -let methodApiVersionParam: Parameter | undefined = undefined; -let serverApiVersionParam: Parameter | undefined = undefined; - -function isSimpleType( - program: Program, - type: EmitterType | undefined -): boolean { - // these decorators can only work for simple type(int/string/float, etc) - if (type && (type.kind === "Scalar" || type.kind === "ModelProperty")) { - const funcs = [ - getMinValue, - getMaxValue, - getMinLength, - getMaxLength, - getPattern, - getEncode - ]; - for (const func of funcs) { - if (func(program, type)) { - return true; - } - } - } - return false; -} - -function getDocStr(program: Program, target: Type): string { - return getDoc(program, target) ?? ""; -} - -function isDiscriminator( - context: SdkContext, - type: Model, - propertyName: string -): boolean { - const discriminator = getDiscriminator(context.program, type); - if (discriminator && discriminator.propertyName === propertyName) { - return true; - } - return false; -} - -function handleDiscriminator( - context: SdkContext, - type: Model, - usage: UsageFlags -) { - const discriminator = getDiscriminator(context.program, type); - if (discriminator) { - const discriminatorValues: string[] = []; - const aliases: string[] = []; - const discriminatedSubtypes: Type[] = []; - let discriminatorTcgcType = undefined; - for (const childModel of type.derivedModels) { - const modelType = getType(context, childModel, { usage }); - aliases.push(modelType.name); - for (const property of modelType.properties) { - if (property.restApiName === discriminator.propertyName) { - modelType.discriminatorValue = property.type.value; - discriminatorValues.push(modelType.discriminatorValue); - discriminatorTcgcType = getClientType(context, property.type); - } - } - discriminatedSubtypes.push(modelType); - } - const discriminatorInfo = { - description: - discriminatorValues.length > 0 - ? `the discriminator possible values: ${discriminatorValues.join( - ", " - )}` - : "discriminator property", - type: { type: "string", tcgcType: discriminatorTcgcType }, - restApiName: discriminator.propertyName, - clientName: discriminator.propertyName, - name: discriminator.propertyName, - isPolymorphic: true, - isDiscriminator: true, - aliases, - discriminatedSubtypes - }; - return discriminatorInfo; - } - return undefined; -} - -function processModelProperties( - context: SdkContext, - newValue: any, - model: Model, - usage: UsageFlags -) { - // need to do properties after insertion to avoid infinite recursion - const discriminatorInfo = handleDiscriminator(context, model, usage); - let hasDiscriminator = false; - for (const property of model.properties.values()) { - if (!isSchemaProperty(context.program, property)) { - continue; - } - if (isNeverType(property.type)) { - continue; - } - if (newValue.properties === undefined || newValue.properties === null) { - newValue.properties = []; - } - let newProperty = emitProperty(context, property, usage); - if (isDiscriminator(context, model, property.name)) { - hasDiscriminator = true; - newProperty = { - ...newProperty, - ...discriminatorInfo, - type: newProperty["type"], - tcgcType: getClientType(context, property) - }; - } - newValue.properties.push(newProperty); - } - if (discriminatorInfo) { - if (!hasDiscriminator) { - newValue.properties.push({ ...discriminatorInfo }); - } - // we don't need to add the discriminator info if it's an anonymous model - // because it's impossible to have a anonymous model as the polymorphic base in typespec - // the only possibility is the anonymous model is an alias for an union type which has already been taken care of in the combined types. - if (newValue.name) { - newValue.name = normalizeName(newValue.name, NameType.Interface); - discriminatorInfo?.aliases.push(`${newValue.name}`); - newValue.alias = `${newValue.name.replace(/Union$/g, "")}`; - newValue.name = `${newValue.name}`; - newValue.aliasType = discriminatorInfo?.aliases.join(" | "); - newValue.types = discriminatorInfo?.discriminatedSubtypes; - newValue.isPolymorphicBaseModel = true; - newValue.discriminator = discriminatorInfo.restApiName; - } - } -} - -function isEmptyAnonymousModel(type: EmitterType): boolean { - // object, {}, all will be treated as empty model - return ( - type.kind === "Model" && - type.name === "" && - type.properties.size === 0 && - !type.baseModel && - type.derivedModels.length === 0 && - !type.indexer - ); -} - -interface EmitTypeOptions { - disableEffectiveModel?: boolean; - usage?: UsageFlags; -} - -export function getType( - context: SdkContext, - type: EmitterType, - options: EmitTypeOptions = {} -): any { - const modularMetatree = useContext("modularMetaTree"); - - // don't cache simple type(string, int, etc) since decorators may change the result - const enableCache = !isSimpleType(context.program, type); - const effectiveModel = - !options.disableEffectiveModel && - (type.kind === "Model" || type.kind === "Union") - ? getEffectiveSchemaType(context.program, type) - : type; - if (enableCache) { - const cached = typesMap.get(effectiveModel); - if (cached) { - return cached; - } - } - let newValue: any = { __raw: type }; - - if (isEmptyAnonymousModel(type)) { - // do not generate model for empty model, treat it as any - newValue = { type: "any" }; - } else { - newValue = emitType(context, type, options); - } - if (type.kind === "ModelProperty" || type.kind === "Scalar") { - newValue = applyEncoding(context.program, type, newValue); - } - - if (isTypespecType(type)) { - newValue.tcgcType = getClientType(context, effectiveModel as any); - newValue.name = !newValue.tcgcType.isGeneratedName - ? normalizeModelName(context, newValue.tcgcType) - : newValue.name; - newValue.__raw = type; - modularMetatree.set(type, newValue); - } - - if (enableCache) { - if (!options.disableEffectiveModel) { - if (newValue.__raw === undefined) { - newValue.__raw = type; - } - typesMap.set(effectiveModel, newValue); - } - if (type.kind === "Union") { - for (const t of type.variants.values()) { - if (t.type.kind === "Model") { - processModelProperties(context, newValue, t.type, options.usage!); - } - } - } - if (type.kind === "Model") { - // need to do properties after insertion to avoid infinite recursion - processModelProperties(context, newValue, type, options.usage!); - if (newValue.type === "dict") { - newValue = { ...emitModel(context, type, options), ...newValue }; - typesMap.set(effectiveModel, newValue); - } - } - } else { - const { __raw, tcgcType, ...keyableValue } = newValue; - const key = JSON.stringify(keyableValue); - const value = simpleTypesMap.get(key); - if (value) { - newValue = value; - } else { - simpleTypesMap.set(key, newValue); - } - } - if ( - type.kind === "Model" && - newValue.tcgcType.additionalProperties && - !context.rlcOptions?.compatibilityMode - ) { - reportDiagnostic(context.program, { - code: "compatible-additional-properties", - format: { - modelName: type?.name ?? "" - }, - target: type - }); - } - - typesMap.set(effectiveModel, newValue); - return newValue; -} - -function isTypespecType(type: EmitterType): type is Type { - return type.kind !== "Credential" && type.kind !== "CredentialTypeUnion"; -} - -// To pass the yaml dump -function getAddedOnVersion(p: Program, t: Type): string | undefined { - return getAddedOnVersions(p, t)?.[0]?.value; -} - -type ParamBase = { - optional: boolean; - description: string; - addedOn: string | undefined; - clientName: string; - restApiName: string; - inOverload: boolean; - format?: string; - tcgcType: SdkType; -}; -function emitParamBase( - context: SdkContext, - parameter: ModelProperty | Type -): ParamBase { - let optional: boolean; - let name: string; - let restApiName: string; - let description: string = ""; - let addedOn: string | undefined; - let format: string | undefined; - - const program = context.program; - - if (parameter.kind === "ModelProperty") { - optional = parameter.optional; - name = normalizeName( - getLibraryName(context, parameter), - NameType.Parameter, - true - ); - restApiName = getWireName(context, parameter); - description = getDocStr(program, parameter); - addedOn = getAddedOnVersion(program, parameter); - const newParameter = applyEncoding(program, parameter, parameter); - format = newParameter.format; - } else { - optional = false; - name = "body"; - restApiName = "body"; - } - - return { - optional, - description, - addedOn, - clientName: applyCasing(name, { casing: CASING }), - restApiName, - inOverload: false, - format, - tcgcType: getClientType(context, parameter) - }; -} - -type BodyParameter = ParamBase & { - contentTypes: string[]; - type: Type; - location: "body"; - // defaultContentType: string; - isBinaryPayload: boolean; -}; - -function emitBodyParameter( - context: SdkContext, - httpOperation: HttpOperation -): BodyParameter | undefined { - const params = httpOperation.parameters; - const body = params.body!; - if (body.bodyKind === "single") { - const base = emitParamBase(context, body.parameter ?? body.type); - let contentTypes = body.contentTypes; - if (contentTypes.length === 0) { - contentTypes = ["application/json"]; - } - const type = getType(context, getBodyType(httpOperation)!, { - disableEffectiveModel: true, - usage: UsageFlags.Input - }); - - return { - contentTypes, - type, - location: "body", - ...base, - isBinaryPayload: isBinaryPayload(context, body.type, contentTypes), - optional: !isBodyRequired(httpOperation.parameters) - }; - } - return undefined; -} - -function emitParameter( - context: SdkContext, - parameter: HttpOperationParameter | HttpServerParameter, - implementation: string -): Parameter | undefined { - if (parameter.type === "cookie") { - // TODO: support cookie parameters, https://github.com/Azure/autorest.typescript/issues/2898 - reportDiagnostic(context.program, { - code: "parameter-type-not-supported", - format: { - paramType: parameter.type, - paramName: parameter.name - }, - target: NoTarget - }); - return undefined; - } - const base = emitParamBase(context, parameter.param); - let type = getType(context, parameter.param.type, { - usage: UsageFlags.Input - }); - let clientDefaultValue = undefined; - if ( - parameter.name.toLowerCase() === "content-type" && - type["type"] === "constant" - ) { - /// We don't want constant types for content types, so we make sure if it's - /// a constant, we make it not constant - clientDefaultValue = type["value"]; - type = { - ...type["valueType"], - tcgcType: - base.tcgcType.kind === "constant" - ? base.tcgcType.valueType - : base.tcgcType - }; - } - const paramMap = { - restApiName: parameter.name, - location: parameter.type, - type: base.format ? { ...type, format: base.format } : type, - implementation: implementation, - skipUrlEncoding: - parameter.type === "endpointPath" || - (parameter.type === "path" && parameter.allowReserved), - format: (parameter as any).format ?? base.format, - tcgcType: base.tcgcType - }; - - if (paramMap.type.type === "constant") { - clientDefaultValue = paramMap.type.value; - } - - if ( - isApiVersion(context, parameter as HttpOperationParameter) && - (paramMap.location === "query" || paramMap.location === "endpointPath") - ) { - const defaultApiVersion = getDefaultApiVersion( - context, - getServiceNamespace(context.program) - ); - paramMap.implementation = implementation; - (paramMap as any).in_docstring = false; - if (defaultApiVersion) { - clientDefaultValue = defaultApiVersion.value; - } - if (!clientDefaultValue) { - clientDefaultValue = getDefaultApiVersionString(context); - } - if (clientDefaultValue !== undefined) { - (paramMap as any).optional = true; - } - } - - if ( - clientDefaultValue === undefined && - paramMap.location === "endpointPath" && - parameter.param.defaultValue?.valueKind === "StringValue" - ) { - // For endpoint path params, treat the default value as a client default. - clientDefaultValue = parameter.param.defaultValue.value; - } - - return { clientDefaultValue, ...base, ...paramMap }; -} - -function emitFlattenedParameter( - bodyParameter: Record, - property: any -): Record { - return { - checkClientInput: false, - clientDefaultValue: null, - clientName: property.clientName, - delimiter: null, - description: property.description, - implementation: "Method", - inDocstring: true, - inFlattenedBody: true, - inOverload: false, - inOverriden: false, - isApiVersion: bodyParameter["isApiVersion"], - location: "other", - optional: property["optional"], - restApiName: null, - skipUrlEncoding: false, - type: property["type"], - defaultToUnsetSentinel: true - }; -} - -function emitResponseHeaders( - context: SdkContext, - headers?: Record -): Header[] { - const retval: Header[] = []; - if (!headers) { - return retval; - } - for (const [key, value] of Object.entries(headers)) { - retval.push({ - type: getType(context, value.type, { usage: UsageFlags.Output }), - restApiName: key - }); - } - return retval; -} - -function emitResponse( - context: SdkContext, - operation: Operation, - response: HttpOperationResponse, - innerResponse: HttpOperationResponseContent -): Response { - let type = undefined; - if ( - innerResponse.body?.type && - !isAzureCoreErrorType(context.program, innerResponse.body?.type) - ) { - // temporary logic. It can be removed after compiler optimize the response - const candidate = [ - "ResourceOkResponse", - "ResourceCreatedResponse", - "AcceptedResponse" - ]; - const originType = innerResponse.body.type as Model; - if ( - innerResponse.body.type.kind === "Model" && - candidate.find((e) => e === originType.name) - ) { - const modelType = getEffectiveSchemaType(context.program, originType); - type = getType(context, modelType, { usage: UsageFlags.Output }); - } else if (isLroResponse()) { - const metadata = getLroMetadata(context.program, operation); - type = - metadata?.finalResult === "void" || metadata?.finalResult === undefined - ? undefined - : getType(context, metadata.finalResult); - } else { - type = isVoidType(innerResponse.body.type) - ? undefined - : getType(context, innerResponse.body.type, { - usage: UsageFlags.Output - }); - } - } - const statusCodes: (number | "default")[] = []; - if (response.statusCode === "*") { - statusCodes.push("default"); - } else { - statusCodes.push(parseInt(response.statusCode)); - } - return { - headers: emitResponseHeaders(context, innerResponse.headers), - statusCodes: statusCodes ?? [], - addedOn: getAddedOnVersion(context.program, response.type), - discriminator: "basic", - type: type, - isBinaryPayload: innerResponse.body?.type - ? isBinaryPayload( - context, - innerResponse.body?.type, - innerResponse.body?.contentTypes![0] ?? "application/json" - ) - : false - }; - - function isLroResponse() { - return ( - typeof response.statusCodes === "number" && - ["200", "201", "202"]?.includes(`${response.statusCodes}`) && - !!getLroMetadata(context.program, operation) - ); - } -} - -function emitOperation( - context: SdkContext, - operation: Operation, - operationGroupName: string, - rlcModels: RLCModel, - hierarchies: string[] -): HrlcOperation { - const isAzureFlavor = isAzurePackage(rlcModels); - const emittedOperation = emitBasicOperation( - context, - operation, - operationGroupName, - rlcModels, - hierarchies - ); - // Skip to extract paging and lro information for non-branded clients. - if (!isAzureFlavor) { - return emittedOperation; - } - const lro = isLongRunningOperation( - context.program, - getHttpOperationWithCache(context, operation) - ); - const pagingMetadata = getPagedResult(context.program, operation); - // Disable the paging feature if no itemsSegments is found. - const paging = - pagingMetadata && - pagingMetadata.itemsSegments && - pagingMetadata.itemsSegments.length > 0; - if ( - pagingMetadata && - (!pagingMetadata.itemsSegments || pagingMetadata.itemsSegments.length === 0) - ) { - reportDiagnostic(context.program, { - code: "no-paging-items-defined", - format: { - operationName: operation.name - }, - target: operation - }); - } - - emitExtraInfoForOperation(emittedOperation); - return emittedOperation; - - function emitExtraInfoForOperation(emittedOperation: HrlcOperation) { - if (lro) { - addLroInformation(context, operation, emittedOperation); - } - if (paging) { - addPagingInformation(context, operation, emittedOperation); - } - if (lro && paging) { - emittedOperation["discriminator"] = "lropaging"; - } - } -} - -function addLroInformation( - context: SdkContext, - operation: Operation, - emittedOperation: HrlcOperation -) { - emittedOperation["discriminator"] = "lro"; - const metadata = getLroMetadata(context.program, operation); - emittedOperation["lroMetadata"] = { - finalResult: - metadata?.finalResult === "void" || metadata?.finalResult === undefined - ? undefined - : getType(context, metadata.finalResult), - finalStateVia: getFinalStateVia(context, operation, metadata), - finalResultPath: metadata?.finalResultPath - }; -} - -function getFinalStateVia( - context: SdkContext, - operation: Operation, - metadata?: LroMetadata -) { - if (!metadata) { - return undefined; - } - switch (metadata.finalStateVia) { - case "azure-async-operation": - case "location": - case "operation-location": - case "original-uri": - return metadata.finalStateVia; - default: - reportDiagnostic(context.program, { - code: "un-supported-finalStateVia", - format: { - finalStateVia: metadata.finalStateVia! - }, - target: operation - }); - return undefined; - } -} - -function addPagingInformation( - context: SdkContext, - operation: Operation, - emittedOperation: Record -) { - emittedOperation["discriminator"] = "paging"; - const pagedResult = getPagedResult(context.program, operation); - if (pagedResult === undefined) { - throw Error( - "Trying to add paging information, but not paging metadata for this operation" - ); - } - emittedOperation["itemName"] = parseItemName(pagedResult); - emittedOperation["continuationTokenName"] = parseNextLinkName(pagedResult); -} - -function emitBasicOperation( - context: SdkContext, - operation: Operation, - operationGroupName: string, - rlcModels: RLCModel, - hierarchies: string[] -): HrlcOperation { - // Set up parameters for operation - const parameters: any[] = []; - if (endpointPathParameters) { - for (const param of endpointPathParameters) { - parameters.push(param); - } - } - const httpOperation = getHttpOperationWithCache(context, operation); - const sourceOperation = - operation.sourceOperation && - !isTemplateDeclarationOrInstance(operation.sourceOperation) - ? operation.sourceOperation - : operation; - const sourceOperationGroupName = getOperationGroupName( - context, - sourceOperation - ); - const sourceOperationName = getOperationName(context, sourceOperation); - const sourceRoutePath = getHttpOperationWithCache(context, operation).path; - const rlcResponses = rlcModels.responses?.filter((op) => { - return ( - (sourceOperationGroupName === "" || - op.operationGroup === sourceOperationGroupName) && - op.operationName === sourceOperationName && - op.path === sourceRoutePath - ); - }); - - const namespaceHierarchies = - context.rlcOptions?.hierarchyClient === true ? hierarchies : []; - - if ( - namespaceHierarchies.length === 0 && - context.rlcOptions?.hierarchyClient === false && - operationGroupName !== "" - ) { - namespaceHierarchies.push(operationGroupName); - } - - for (const param of httpOperation.parameters.parameters) { - if (isIgnoredHeaderParam(param)) { - continue; - } - const emittedParam = emitParameter(context, param, "Method"); - if (emittedParam === undefined) { - continue; - } - if (isApiVersion(context, param)) { - emittedParam.isApiVersion = true; - methodApiVersionParam = emittedParam; - } - parameters.push(emittedParam); - } - - // Set up responses for operation - const responses: Response[] = []; - const exceptions: Response[] = []; - const isOverload = isSharedRoute(context.program, operation); - for (const response of httpOperation.responses) { - for (const innerResponse of response.responses) { - const emittedResponse: Response = emitResponse( - context, - operation, - response, - innerResponse - ); - if (isErrorModel(context.program, response.type)) { - // * is valid status code in typespec but invalid for autorest.python - if (response.statusCode === "*") { - exceptions.push(emittedResponse); - } - } else { - responses.push(emittedResponse); - } - } - } - - let bodyParameter: any | undefined; - if ( - httpOperation.parameters.body === undefined || - isVoidType(httpOperation.parameters.body.type) - ) { - bodyParameter = undefined; - } else { - bodyParameter = emitBodyParameter(context, httpOperation); - // Flatten the body parameter if it is an anonymous model - const originalBodyType = httpOperation.parameters.body.type; - - if ( - bodyParameter.type.type === "model" && - originalBodyType.kind === "Model" && - originalBodyType.name === "" && - [...originalBodyType.properties.keys()].every( - (k) => - operation.parameters.properties.has(k) && - (operation.parameters.properties.get(k) === - (originalBodyType as Model).properties.get(k) || - operation.parameters.properties.get(k) === - (originalBodyType as Model).properties.get(k)?.sourceProperty) - ) - ) { - for (const param of bodyParameter.type.properties) { - param.implementation = "Method"; - param.location = param.location ?? "body"; - parameters.push(param); - } - bodyParameter = undefined; - } else if ( - bodyParameter.type.type === "model" && - bodyParameter.type.base === "json" - ) { - bodyParameter["propertyToParameterName"] = {}; - if (!isOverload) { - bodyParameter.defaultToUnsetSentinel = true; - } - for (const property of bodyParameter.type.properties) { - bodyParameter["propertyToParameterName"][property["restApiName"]] = - property["clientName"]; - parameters.push(emitFlattenedParameter(bodyParameter, property)); - } - } - } - - const name = applyCasing(getLibraryName(context, operation), { - casing: CASING - }); - - /** handle name collision between operation name and parameter signature */ - if (bodyParameter) { - bodyParameter.clientName = - bodyParameter.clientName === name - ? bodyParameter.clientName + "Parameter" - : bodyParameter.clientName; - } - parameters - .filter((param) => { - return param.clientName === name && !param.isReadOnly && param.required; - }) - .forEach((param) => { - param.clientName = param.clientName + "Parameter"; - }); - return { - name, - description: getDocStr(context.program, operation), - summary: getSummary(context.program, operation) ?? "", - url: httpOperation.path, - method: httpOperation.verb.toUpperCase(), - parameters: parameters, - bodyParameter: bodyParameter, - responses: responses ?? [], - exceptions: exceptions ?? [], - groupName: operationGroupName, - addedOn: getAddedOnVersion(context.program, operation), - discriminator: "basic", - isOverload, - overloads: [], - apiVersions: [getAddedOnVersion(context.program, operation)], - rlcResponse: rlcResponses?.[0], - namespaceHierarchies - }; -} - -function isReadOnly(program: Program, type: ModelProperty): boolean { - // https://microsoft.github.io/typespec/standard-library/http/operations#automatic-visibility - // Only "read" should be readOnly - const visibility = getVisibility(program, type); - if (visibility) { - return visibility.includes("read") && visibility.length === 1; - } else { - return false; - } -} - -function emitProperty( - context: SdkContext, - property: ModelProperty, - usage: UsageFlags -): Record { - const newProperty = applyEncoding(context.program, property, property); - let clientDefaultValue = undefined; - const propertyDefaultKind = property.default?.kind; - if ( - property.default && - (propertyDefaultKind === "Number" || - propertyDefaultKind === "String" || - propertyDefaultKind === "Boolean") - ) { - clientDefaultValue = property.default.value; - } - - if (propertyDefaultKind === "EnumMember") { - clientDefaultValue = property.default.value ?? property.default.name; - } - - // const [clientName, jsonName] = getPropertyNames(context, property); - const clientName = getLibraryName(context, property); - const jsonName = getWireName(context, property); - - if (property.model) { - getType(context, property.model, { usage }); - } - const type = getType(context, property.type, { usage }); - return { - clientName: context.rlcOptions?.ignorePropertyNameNormalize - ? clientName - : normalizeName(clientName, NameType.Property), - restApiName: jsonName, - type: newProperty.format ? { ...type, format: newProperty.format } : type, - optional: property.optional, - description: getDocStr(context.program, property), - addedOn: getAddedOnVersion(context.program, property), - readonly: isReadOnly(context.program, property), - clientDefaultValue: clientDefaultValue, - format: newProperty.format - }; -} - -function getName(program: Program, type: Model): string { - const friendlyName = getFriendlyName(program, type); - if (friendlyName) { - return friendlyName; - } else { - if ( - type.templateMapper && - type.templateMapper.args && - type.name !== "" && - type.templateMapper.args.length > 0 - ) { - return ( - type.name + - (type.templateMapper.args.filter((it) => isType(it)) as Type[]) - .map((it) => (it.kind === "Model" ? it.name : "")) - .join("") - ); - } else { - return type.name; - } - } -} - -export function emitModel( - context: SdkContext, - type: Model, - options: EmitTypeOptions = {} -): Record { - // Now we know it's a defined model - const properties: Record[] = []; - let baseModel = undefined; - if (type.baseModel) { - baseModel = getType(context, type.baseModel, options); - } - const effectiveName = !options.disableEffectiveModel - ? getEffectiveSchemaType(context.program, type).name - : undefined; - const overridedModelName = normalizeName( - getLibraryName(context, type) ?? getFriendlyName(context.program, type), - NameType.Interface, - true - ); - const fullNamespaceName = - getModelNamespaceName(context, type.namespace!) - .map((nsName) => { - return normalizeName(nsName, NameType.Interface); - }) - .join("") + - (effectiveName ? effectiveName : getName(context.program, type)); - let modelName = - overridedModelName !== type.name - ? overridedModelName - : context.rlcOptions?.enableModelNamespace - ? fullNamespaceName - : effectiveName - ? effectiveName - : getName(context.program, type); - if ( - !overridedModelName && - type.templateMapper && - type.templateMapper.args && - type.templateMapper.args.length > 0 && - getPagedResult(context.program, type) - ) { - modelName = - (type.templateMapper.args.filter((it) => isType(it)) as Type[]) - .map((it) => { - switch (it.kind) { - case "Model": - return it.name; - case "String": - return it.value; - default: - return ""; - } - }) - .join("") + "List"; - } - - const page = extractPagedMetadataNested(context.program, type); - const isPaging = page && page.itemsSegments && page.itemsSegments.length > 0; - return { - type: "model", - name: `${isPaging ? "_" : ""}${modelName}`, - description: getDocStr(context.program, type), - parents: baseModel ? [baseModel] : [], - discriminatedSubtypes: [], - properties: properties, - addedOn: getAddedOnVersion(context.program, type), - snakeCaseName: modelName - ? applyCasing(modelName, { casing: CASING }) - : modelName, - base: modelName === "" ? "json" : "dpg", - coreTypeInfo: buildCoreTypeInfo(context.program, type), - usage: options.usage - }; -} - -function intOrFloat(value: number): string { - return value.toString().indexOf(".") === -1 ? "integer" : "float"; -} - -function enumName(name: string): string { - return name; -} - -function emitEnum(context: SdkContext, type: Enum): Record { - const program = context.program; - const enumValues = []; - for (const m of type.members.values()) { - enumValues.push({ - name: enumName(m.name), - value: m.value ?? m.name, - description: getDocStr(program, m) - }); - } - - if (enumValues.length === 0) { - throw new Error(`Expecting enum values but got none`); - } - const name = normalizeName( - getLibraryName(context, type) ? getLibraryName(context, type) : type.name, - NameType.Interface - ); - return { - type: "enum", - name, - description: - getDocStr(program, type) === "" - ? `Type of ${name}` - : getDocStr(program, type), - valueType: { type: enumMemberType(type.members.values().next().value!) }, - values: enumValues, - isFixed: true, - coreTypeInfo: buildCoreTypeInfo(program, type) - }; -} - -function enumMemberType(member: EnumMember) { - if (typeof member.value === "number") { - return "number"; - } - return "string"; -} - -function constantType(value: any, valueType: string): Record { - return { type: "constant", value: value, valueType: { type: valueType } }; -} - -function emitCredential(auth: HttpAuth): Record { - let credential_type: any = {}; - if (auth.type === "oauth2") { - credential_type = { - type: "OAuth2", - policy: { - type: "BearerTokenCredentialPolicy", - credentialScopes: [] - } - }; - for (const flow of auth.flows) { - for (const scope of flow.scopes) { - credential_type.policy.credentialScopes.push(scope.value); - } - credential_type.policy.credentialScopes.push(); - } - } else if (auth.type === "apiKey") { - credential_type = { - type: "Key", - policy: { - type: "AzureKeyCredentialPolicy", - key: auth.name - } - }; - } else if (auth.type === "http") { - credential_type = { - type: "Key", - policy: { - type: "AzureKeyCredentialPolicy", - key: "Authorization" - } - }; - } - return credential_type; -} - -function emitCredentialUnion(cred_types: CredentialTypeUnion) { - const result: any = {}; - // Export as CombinedType, which is already a Union Type in autorest codegen - result.type = "combined"; - result.types = []; - for (const cred_type of cred_types.types) { - result.types.push(emitCredential(cred_type.scheme)); - } - - return result; -} - -function emitStdScalar( - program: Program, - scalar: Scalar & { name: IntrinsicScalarName } -): Record { - const newScalar = applyEncoding(program, scalar, scalar); - switch (scalar.name) { - case "bytes": - return { type: "byte-array", format: newScalar.format }; - case "int8": - case "int16": - case "int32": - case "int64": - case "safeint": - case "uint8": - case "uint16": - case "uint32": - case "uint64": - case "integer": - return { type: "integer" }; - case "float32": - case "float64": - case "float": - return { type: "float" }; - case "url": - case "string": - return { type: "string" }; - case "boolean": - return { type: "boolean" }; - case "plainDate": - return { type: "string", format: newScalar.format ?? "date" }; - case "utcDateTime": - return { type: "datetime", format: newScalar.format }; - case "plainTime": - return { type: "string", format: newScalar.format ?? "time" }; - case "offsetDateTime": - return { type: "string" }; - case "duration": - return { type: "duration", format: newScalar.format }; - case "numeric": - return {}; // Waiting on design for more precise type https://github.com/microsoft/cadl/issues/1260 - case "decimal": - case "decimal128": - reportDiagnostic(program, { - code: "decimal-to-number", - format: { - propertyName: newScalar?.name ?? "" - }, - target: NoTarget - }); - return { type: "integer", format: newScalar.format }; - default: - return {}; - } -} - -function applyEncoding( - program: Program, - typespecType: Scalar | ModelProperty, - target: any = {} -) { - const encodeData = getEncode(program, typespecType); - if (encodeData) { - const newTarget = { ...target }; - const newType = emitScalar(program, encodeData.type); - // newTarget["type"] = newType["type"]; - // If the target already has a format it takes priority. (e.g. int32) - newTarget["format"] = mergeFormatAndEncoding( - newTarget.format, - encodeData.encoding, - newType["format"] - ); - return newTarget; - } - return target; -} - -function mergeFormatAndEncoding( - format: string | undefined, - encoding: string | undefined, - encodeAsFormat: string | undefined -): string | undefined { - switch (format) { - case undefined: - return encodeAsFormat ?? encoding ?? format; - case "date-time": - return encoding; - case "duration": - default: - return encodeAsFormat ?? encoding ?? format; - } -} - -function applyIntrinsicDecorators( - program: Program, - type: Scalar | ModelProperty, - result: any -): Record { - let newResult = { ...result }; - const docStr = getDoc(program, type); - const isString = isStringType(program, getPropertyType(type)); - const isNumeric = isNumericType(program, getPropertyType(type)); - - if (!result.description && docStr) { - newResult.description = docStr; - } - - newResult = applyEncoding(program, type, newResult); - - const pattern = getPattern(program, type); - if (isString && !result.pattern && pattern) { - newResult.pattern = pattern; - } - - const minLength = getMinLength(program, type); - if (isString && !result.minLength && minLength !== undefined) { - newResult.minLength = minLength; - } - - const maxLength = getMaxLength(program, type); - if (isString && !result.maxLength && maxLength !== undefined) { - newResult.maxLength = maxLength; - } - - const minValue = getMinValue(program, type); - if (isNumeric && !result.minimum && minValue !== undefined) { - newResult.minimum = minValue; - } - - const maxValue = getMaxValue(program, type); - if (isNumeric && !result.maximum && maxValue !== undefined) { - newResult.maximum = maxValue; - } - - const minItems = getMinItems(program, type); - if (!result.minItems && minItems !== undefined) { - newResult.minItems = minItems; - } - - const maxItems = getMaxItems(program, type); - if (!result.maxItems && maxItems !== undefined) { - newResult.maxItems = maxItems; - } - return newResult; -} - -function emitScalar(program: Program, scalar: Scalar): Record { - let result: Record = {}; - const isStd = program.checker.isStdType(scalar); - if (isStd) { - result = emitStdScalar(program, scalar); - } else if (scalar.baseScalar) { - result = emitScalar(program, scalar.baseScalar); - } - return applyIntrinsicDecorators(program, scalar, result); -} - -function emitListOrDict( - context: SdkContext, - type: Model, - usage: UsageFlags -): Record | undefined { - if (type.indexer !== undefined) { - if (!isNeverType(type.indexer.key)) { - const name = type.indexer.key.name; - if (name === "string") { - return { - type: "dict", - name: type.name, - elementType: getType(context, type.indexer.value!, { usage }) - }; - } else if (name === "integer") { - return { - type: "list", - elementType: getType(context, type.indexer.value!, { usage }) - }; - } - } - } - return undefined; -} - -function mapTypeSpecType( - context: SdkContext, - type: Type, - usage: UsageFlags -): any { - switch (type.kind) { - case "Number": - return constantType(type.value, intOrFloat(type.value)); - case "String": - return constantType(type.value, "string"); - case "Boolean": - return constantType(type.value, "boolean"); - case "Model": - return emitListOrDict(context, type, usage); - } -} - -function emitUnion( - context: SdkContext, - type: Union, - usage: UsageFlags -): Record { - let sdkType = getSdkUnion(context, type); - const isNull = sdkType.kind === "nullable"; - if (sdkType.kind === "nullable") { - sdkType = sdkType.type; - } - const nonNullOptions = getNonNullOptions(type); - if (sdkType === undefined) { - throw Error("Should not have an empty union"); - } - if (sdkType.kind === "union") { - const unionName = getLibraryName(context, type) - ? getLibraryName(context, type) - : type.name; - const discriminatorPropertyName = getDiscriminator( - context.program, - type - )?.propertyName; - const variantTypes = sdkType.variantTypes.map((x) => { - const valueType = getType(context, x.__raw!, { usage }); - if (valueType.properties && discriminatorPropertyName) { - valueType.discriminatorValue = valueType.properties.filter( - (p: Property) => p.clientName === discriminatorPropertyName - )[0].type.value; - } - return valueType; - }); - const unionTypeName = unionName - ? normalizeName(unionName, NameType.Interface) - : undefined; - return { - nullable: isNull, - name: unionTypeName, - description: `Type of ${unionTypeName}`, - internal: true, - type: "combined", - types: variantTypes, - xmlMetadata: {}, - usage, - discriminator: discriminatorPropertyName, - alias: - unionName === "" || unionName === undefined ? undefined : unionName, - aliasType: - unionName === "" || unionName === undefined - ? undefined - : variantTypes.map((x) => getTypeName(x).name).join(" | "), - tcgcType: sdkType - }; - } else if (sdkType.kind === "enum") { - let typeName = getLibraryName(context, type) - ? getLibraryName(context, type) - : sdkType.isGeneratedName - ? type.name - : sdkType.name; - typeName = typeName - ? normalizeName(typeName, NameType.Interface) - : undefined; - return { - name: typeName, - nullable: isNull, - description: sdkType.doc || `Type of ${typeName}`, - internal: true, - type: sdkType.kind, - valueType: emitSimpleType(sdkType.valueType), - values: sdkType.values.map((x) => emitEnumMember(context, x)), - isFixed: sdkType.isFixed, - isNonExhaustive: context.rlcOptions?.experimentalExtensibleEnums ?? false, - xmlMetadata: {}, - usage - }; - } else if (nonNullOptions.length === 1 && nonNullOptions[0]) { - return { - ...emitType(context, nonNullOptions[0], { usage }), - nullable: isNull - }; - } else { - return { - ...emitType(context, sdkType.__raw!, { usage }), - nullable: isNull - }; - } -} - -function getNonNullOptions(type: Union) { - return [...type.variants.values()] - .map((x) => x.type) - .filter((t) => !isNullType(t)); -} - -function emitEnumMember(context: SdkContext, member: any): Record { - const value = member.value ?? member.name; - return { - type: "constant", - valueType: { - type: enumMemberType(member) - }, - value, - name: member.name ? enumName(member.name) : undefined, - description: getDoc(context.program, member), - isConstant: true - }; -} - -function emitSimpleType(type: SdkBuiltInType): Record { - return { - nullable: isNullType(type.__raw!), - type: type.kind === "string" ? "string" : "number", // TODO: handle other types - doc: "", - apiVersions: [], - sdkDefaultValue: undefined, - format: undefined - }; -} - -function emitType( - context: SdkContext, - type: EmitterType, - options: EmitTypeOptions = {} -): Record { - if (type.kind === "Credential") { - return emitCredential(type.scheme); - } - if (type.kind === "CredentialTypeUnion") { - return emitCredentialUnion(type); - } - const builtinType = mapTypeSpecType(context, type, options.usage!); - if (builtinType !== undefined) { - // add in description elements for types derived from primitive types (SecureString, etc.) - const doc = getDoc(context.program, type); - if (doc) { - builtinType.description = doc; - } - return builtinType; - } - - switch (type.kind) { - case "Intrinsic": - return { type: type.name }; - case "Model": - return emitModel(context, type, options); - case "Scalar": - return emitScalar(context.program, type); - case "Union": - return emitUnion(context, type, options.usage!); - case "UnionVariant": - return emitType(context, type.type, options); - case "Enum": - return emitEnum(context, type); - case "EnumMember": - return emitEnumMember(context, type); - case "ModelProperty": - return emitType(context, type.type, options); - default: - throw Error(`Not supported ${type.kind}`); - } -} - -function emitOperationGroups( - context: SdkContext, - client: SdkClient, - rlcModels: RLCModel -): OperationGroup[] { - const operationGroups: OperationGroup[] = []; - const groupMapping: Map = new Map< - string, - OperationGroup - >(); - const clientOperations: HrlcOperation[] = []; - for (const operation of listOperationsInOperationGroup(context, client)) { - clientOperations.push(emitOperation(context, operation, "", rlcModels, [])); - } - if (clientOperations.length > 0) { - addHierarchyOperationGroup(clientOperations, groupMapping); - } - for (const operationGroup of listOperationGroups(context, client, true)) { - const operations: HrlcOperation[] = []; - const overrideName = getLibraryName(context, operationGroup.type); - const name = - context.rlcOptions?.hierarchyClient || - context.rlcOptions?.enableOperationGroup - ? (overrideName ?? operationGroup.type.name) - : ""; - const hierarchies = - context.rlcOptions?.hierarchyClient || - context.rlcOptions?.enableOperationGroup - ? operationGroup.groupPath.split(".") - : []; - if (hierarchies[0]?.endsWith("Client")) { - hierarchies.shift(); - } - for (const operation of listOperationsInOperationGroup( - context, - operationGroup - )) { - operations.push( - emitOperation(context, operation, name, rlcModels, hierarchies) - ); - } - if (operations.length > 0) { - addHierarchyOperationGroup(operations, groupMapping); - } - } - - groupMapping.forEach((value) => { - operationGroups.push(value); - }); - if ( - context.rlcOptions?.hierarchyClient === false && - context.rlcOptions?.enableOperationGroup - ) { - appendOperationGroupPrefix(operationGroups); - } - return operationGroups; -} - -function addHierarchyOperationGroup( - operations: HrlcOperation[], - groupMapping: Map -): OperationGroup[] { - if (operations.length > 0) { - operations.forEach((op) => { - const groupName = op.namespaceHierarchies.join("") ?? ""; - if (!groupMapping.has(groupName)) { - groupMapping.set(groupName, { - className: groupName, - propertyName: groupName, - operations: [op], - namespaceHierarchies: op.namespaceHierarchies - }); - } else { - groupMapping.get(groupName)!.operations.push(op); - } - }); - return [...groupMapping.values()]; - } - return []; -} - -function appendOperationGroupPrefix(operationGroups: OperationGroup[]) { - if (operationGroups.length < 2) { - return; - } - // Append operation group prefix - operationGroups.forEach((g) => - g.operations.forEach((op) => { - op.oriName = op.name; - op.name = `${g.propertyName}_${op.name}`; - }) - ); -} - -function getServerHelper( - program: Program, - namespace: Namespace -): HttpServer | undefined { - const servers = getServers(program, namespace); - if (servers === undefined) { - return undefined; - } - return servers[0]; -} - -function emitServerParams( - context: SdkContext, - namespace: Namespace -): Parameter[] { - const server = getServerHelper(context.program, namespace); - if (server === undefined || server.parameters.size === 0) { - return [ - { - optional: false, - description: "Service host", - clientName: "endpointParam", - clientDefaultValue: null, - restApiName: "endpoint", - location: "endpointPath", - type: { type: "string" }, - implementation: "Client", - inOverload: false - } - ]; - } - if (server.parameters) { - const params: Parameter[] = []; - for (const param of server.parameters.values()) { - const serverParameter: HttpServerParameter = { - type: "endpointPath", - name: param.name, - param: param - }; - const emittedParameter = emitParameter( - context, - serverParameter, - "Client" - ); - if (emittedParameter === undefined) { - continue; - } - endpointPathParameters.push(emittedParameter); - if (isApiVersion(context, serverParameter as any)) { - emittedParameter.isApiVersion = true; - serverApiVersionParam = emittedParameter; - emittedParameter.isApiVersion = true; - } - params.push(emittedParameter); - } - return params; - } else { - return [ - { - optional: false, - description: "Service host", - clientName: "endpointParam", - clientDefaultValue: server.url, - restApiName: "endpoint", - location: "path", - type: { type: "string" }, - implementation: "Client", - inOverload: false - } - ]; - } -} - -function emitCredentialParam( - context: SdkContext, - namespace: Namespace -): Parameter | undefined { - const auth = getAuthentication(context.program, namespace); - if (auth) { - const credential_types: CredentialType[] = []; - for (const scheme of getSupportedHttpAuth(context.program, auth)) { - const type: CredentialType = { - kind: "Credential", - scheme: scheme - }; - credential_types.push(type); - } - - if ( - credential_types.length > 0 && - context.rlcOptions?.addCredentials !== false - ) { - let type: EmitterType; - if (credential_types.length === 1 && credential_types[0]) { - type = credential_types[0]; - } else { - type = { - kind: "CredentialTypeUnion", - types: credential_types - }; - } - return { - type: getType(context, type, { usage: UsageFlags.Input }), - optional: false, - description: "Credential needed for the client to connect to Azure.", - clientName: "credential", - location: "other", - restApiName: "credential", - implementation: "Client", - skipUrlEncoding: true, - inOverload: false - }; - } - } - return undefined; -} - -function emitGlobalParameters( - context: SdkContext, - namespace: Namespace -): Parameter[] { - const clientParameters = emitServerParams(context, namespace); - const credentialParam = emitCredentialParam(context, namespace); - if (credentialParam) { - clientParameters.push(credentialParam); - } - return clientParameters; -} - -function getMethodApiVersionParameter(): Parameter | void { - if (methodApiVersionParam) { - return { - ...methodApiVersionParam, - isApiVersion: true - }; - } -} - -function emitClients( - context: SdkContext, - rlcModelsMap: Map -): HrlcClient[] { - const program = context.program; - const clients = listClients(context); - const retval: HrlcClient[] = []; - methodApiVersionParam = undefined; - for (const client of clients) { - const sdkPackageClient = context.sdkPackage.clients.find((p) => { - return p.name === client.name; - }); - - if (!sdkPackageClient) { - throw new Error(`Client ${client.name} not found in the SDK package`); - } - - const clientName = client.name.replace("Client", ""); - const server = getServerHelper(program, client.service); - const rlcModels = rlcModelsMap.get(client.service.name); - if (!rlcModels) { - continue; - } - const emittedClient: HrlcClient = { - name: clientName.split(".").at(-1) ?? "", - description: getDocStr(program, client.type), - parameters: emitGlobalParameters(context, client.service), - operationGroups: emitOperationGroups(context, client, rlcModels), - tcgcClient: sdkPackageClient, - url: server ? server.url : "", - apiVersions: [], - rlcClientName: `${client.name.replace("Client", "")}Context`, - subfolder: "", - rlcHelperDetails: - rlcModels && rlcModels.helperDetails ? rlcModels.helperDetails : {} - }; - const methodApiVersionParam = getMethodApiVersionParameter(); - if ( - methodApiVersionParam && - !serverApiVersionParam && - context.hasApiVersionInClient - ) { - // prompt method-level api version to client level only when there is no client one defined - emittedClient.parameters.push(methodApiVersionParam); - // if we have client level api version, we need to remove it from all operations - emittedClient.operationGroups.map((opGroup) => { - opGroup.operations.map((op) => { - op.parameters = op.parameters.filter((param) => { - return !param.isApiVersion; - }); - return op; - }); - return opGroup; - }); - } - retval.push(emittedClient); - } - return retval; -} - -function getServiceNamespace(program: Program): Namespace { - return listServices(program)[0]!.type; -} - -function getNamespace(context: SdkContext, clientName: string): string { - // We get client namespaces from the client name. If there's a dot, we add that to the namespace - const submodule = clientName.split(".").slice(0, -1).join(".").toLowerCase(); - if (!submodule) { - return getClientNamespaceString(context)!.toLowerCase(); - } - return submodule; -} - -function getNamespaces(context: SdkContext): Set { - const namespaces = new Set(); - for (const client of listClients(context)) { - namespaces.add(getNamespace(context, client.name)); - } - return namespaces; -} - -export function emitCodeModel( - dpgContext: SdkContext, - rlcModelsMap: Map, - modularSourcesRoot: string, - project: Project, - options: { casing: "snake" | "camel" } = { casing: "snake" } -): ModularCodeModel { - CASING = options.casing ?? CASING; - const clientNamespaceString = - getClientNamespaceString(dpgContext)?.toLowerCase(); - // Get types - const codeModel: ModularCodeModel = { - options: dpgContext.rlcOptions ?? {}, - modularOptions: { - sourceRoot: modularSourcesRoot, - compatibilityMode: !!dpgContext.rlcOptions?.compatibilityMode, - experimentalExtensibleEnums: - !!dpgContext.rlcOptions?.experimentalExtensibleEnums - }, - namespace: clientNamespaceString, - clients: [], - types: [], - project, - runtimeImports: buildRuntimeImports(dpgContext.rlcOptions?.flavor) - }; - - typesMap.clear(); - simpleTypesMap.clear(); - const allModels = getAllModels(dpgContext); - for (const model of allModels) { - getType(dpgContext, model.__raw!, { usage: model.usage as UsageFlags }); - } - for (const namespace of getNamespaces(dpgContext)) { - if (namespace === clientNamespaceString) { - codeModel.clients = emitClients(dpgContext, rlcModelsMap); - codeModel.clients.length > 1 && - codeModel.clients.map((client) => { - client["subfolder"] = normalizeName( - client.name.replace("Client", ""), - NameType.File - ); - }); - } - } - - codeModel["types"] = [ - { type: "string" }, - ...typesMap.values(), - ...simpleTypesMap.values() - ]; - return codeModel; -} diff --git a/packages/typespec-ts/src/modular/buildModularOptions.ts b/packages/typespec-ts/src/modular/buildModularOptions.ts new file mode 100644 index 0000000000..ea2714bd40 --- /dev/null +++ b/packages/typespec-ts/src/modular/buildModularOptions.ts @@ -0,0 +1,27 @@ +import { ModularEmitterOptions } from "./interfaces.js"; + +import { Project } from "ts-morph"; +import { SdkContext } from "../utils/interfaces.js"; + +let CASING: "camel" | "snake" = "snake"; + +export function transformModularEmitterOptions( + dpgContext: SdkContext, + modularSourcesRoot: string, + project: Project, + options: { casing: "snake" | "camel" } = { casing: "snake" } +): ModularEmitterOptions { + CASING = options.casing ?? CASING; + const emitterOptions: ModularEmitterOptions = { + options: dpgContext.rlcOptions ?? {}, + modularOptions: { + sourceRoot: modularSourcesRoot, + compatibilityMode: !!dpgContext.rlcOptions?.compatibilityMode, + experimentalExtensibleEnums: + !!dpgContext.rlcOptions?.experimentalExtensibleEnums + }, + project + }; + + return emitterOptions; +} diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index cc2c58a6ec..1b6a8b5fe9 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -1,15 +1,5 @@ -import { - BodyParameter, - Client, - ModularCodeModel, - Operation, - Parameter -} from "./modularCodeModel.js"; -import { - NameType, - clearImportSets, - normalizeName -} from "@azure-tools/rlc-common"; +import { ModularEmitterOptions } from "./interfaces.js"; +import { NameType, normalizeName } from "@azure-tools/rlc-common"; import { Project, SourceFile } from "ts-morph"; import { getDeserializePrivateFunction, @@ -25,9 +15,22 @@ import { SdkContext } from "../utils/interfaces.js"; import { addImportBySymbol } from "../utils/importHelper.js"; import { getDocsFromDescription } from "./helpers/docsHelpers.js"; import { getOperationName } from "./helpers/namingHelpers.js"; -import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; +import { + getModularClientOptions, + isRLCMultiEndpoint +} from "../utils/clientUtils.js"; import { getTypeExpression } from "./type-expressions/get-type-expression.js"; -import { buildType } from "./helpers/typeHelpers.js"; +import { + SdkClientType, + SdkMethodParameter, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { + getMethodHierarchiesMap, + ServiceOperation +} from "../utils/operationUtil.js"; +import { resolveReference } from "../framework/reference.js"; +import { useDependencies } from "../framework/hooks/useDependencies.js"; /** * This function creates a file under /api for each operation group. @@ -35,20 +38,23 @@ import { buildType } from "./helpers/typeHelpers.js"; * file called operations.ts where all operations are generated. */ export function buildOperationFiles( - client: Client, dpgContext: SdkContext, - codeModel: ModularCodeModel + client: SdkClientType, + emitterOptions: ModularEmitterOptions ) { - const operationFiles = []; + const operationFiles: Set = new Set(); + const { subfolder, rlcClientName } = getModularClientOptions( + dpgContext, + client + ); const isMultiEndpoint = isRLCMultiEndpoint(dpgContext); - const clientType = isMultiEndpoint - ? `Client.${client.rlcClientName}` - : "Client"; - for (const operationGroup of client.operationGroups) { - clearImportSets(codeModel.runtimeImports); + const clientType = isMultiEndpoint ? `Client.${rlcClientName}` : "Client"; + const methodMap = getMethodHierarchiesMap(dpgContext, client); + for (const [prefixKey, operations] of methodMap) { + const prefixes = prefixKey.split("/"); const operationFileName = - operationGroup.className && operationGroup.namespaceHierarchies.length > 0 - ? `${operationGroup.namespaceHierarchies + prefixes.length > 0 && prefixKey !== "" + ? `${prefixes .map((hierarchy) => { return normalizeName(hierarchy, NameType.File); }) @@ -57,55 +63,48 @@ export function buildOperationFiles( // into a nameless operation group. We'll call this operations. "operations"; - const subfolder = client.subfolder; - const srcPath = codeModel.modularOptions.sourceRoot; - const operationGroupFile = codeModel.project.createSourceFile( - `${srcPath}/${ - subfolder && subfolder !== "" ? subfolder + "/" : "" - }api/${operationFileName}.ts` - ); + const srcPath = emitterOptions.modularOptions.sourceRoot; + const filepath = `${srcPath}/${ + subfolder && subfolder !== "" ? subfolder + "/" : "" + }api/${operationFileName}.ts`; + const operationGroupFile = + emitterOptions.project.createSourceFile(filepath); // Import the deserializeUtils importDeserializeUtils( srcPath, operationGroupFile, - codeModel.project, + emitterOptions.project, "deserialize", subfolder, - operationGroup.namespaceHierarchies.length + prefixes.length ); // Import the serializeUtils importDeserializeUtils( srcPath, operationGroupFile, - codeModel.project, + emitterOptions.project, "serialize", subfolder, - operationGroup.namespaceHierarchies.length + prefixes.length ); - const indexPathPrefix = - "../".repeat(operationGroup.namespaceHierarchies.length) || "./"; - operationGroupFile.addImportDeclaration({ - namedImports: [`${client.rlcClientName} as Client`], - moduleSpecifier: `${indexPathPrefix}index.js` - }); - - operationGroup.operations.forEach((o) => { + operations.forEach((op) => { const operationDeclaration = getOperationFunction( dpgContext, - o, + [prefixes, op], clientType ); const sendOperationDeclaration = getSendPrivateFunction( dpgContext, - o, + client, + [prefixes, op], clientType ); const deserializeOperationDeclaration = getDeserializePrivateFunction( dpgContext, - o + op ); operationGroupFile.addFunctions([ sendOperationDeclaration, @@ -114,13 +113,18 @@ export function buildOperationFiles( ]); }); - // addImportsToFiles(codeModel.runtimeImports, operationGroupFile); - operationGroupFile.fixUnusedIdentifiers(); + const indexPathPrefix = + "../".repeat(prefixKey === "" ? 0 : prefixes.length) || "./"; + operationGroupFile.addImportDeclaration({ + namedImports: [`${rlcClientName} as Client`], + moduleSpecifier: `${indexPathPrefix}index.js` + }); addImportBySymbol("serializeRecord", operationGroupFile); + operationGroupFile.fixUnusedIdentifiers(); - operationFiles.push(operationGroupFile); + operationFiles.add(operationGroupFile); } - return operationFiles; + return Array.from(operationFiles); } export function importDeserializeUtils( @@ -160,15 +164,24 @@ export function importDeserializeUtils( */ export function buildOperationOptions( context: SdkContext, - operation: Operation, + method: [string[], ServiceOperation], sourceFile: SourceFile ) { + const dependencies = useDependencies(); + const operation = method[1]; const optionalParameters = operation.parameters - .filter((p) => p.implementation === "Method") + .filter( + (p) => + p.onClient === false && + !( + p.isGeneratedName && + (p.name === "contentType" || p.name !== "accept") + ) + ) .filter((p) => p.optional || p.clientDefaultValue); - const options: (BodyParameter | Parameter)[] = [...optionalParameters]; + const options: SdkMethodParameter[] = [...optionalParameters]; - const name = getOperationOptionsName(operation, true); + const name = getOperationOptionsName(method, true); const lroOptions = { name: "updateIntervalInMs", type: "number", @@ -177,27 +190,24 @@ export function buildOperationOptions( }; // handle optional body parameter - if (operation.bodyParameter?.optional === true) { - options.push(operation.bodyParameter); - } - + // if (operation.operation.bodyParam?.optional === true) { + // options.push(operation.operation.bodyParam); + // } + const operationOptionsReference = resolveReference( + dependencies.OperationOptions + ); sourceFile.addInterface({ name, isExported: true, - extends: ["OperationOptions"], + extends: [operationOptionsReference], properties: (isLroOnlyOperation(operation) ? [lroOptions] : []).concat( options.map((p) => { return { - docs: getDocsFromDescription(p.description), + docs: getDocsFromDescription(p.doc), hasQuestionToken: true, - ...(p.type.tcgcType - ? { - type: getTypeExpression(context, p.type.tcgcType), - name: p.clientName - } - : { - ...buildType(p.clientName, p.type, p.format) - }) + + type: getTypeExpression(context, p.type), + name: normalizeName(p.name, NameType.Parameter) }; }) ), @@ -208,21 +218,24 @@ export function buildOperationOptions( /** * This function creates a map of operation file path to operation names. */ -export function buildLroDeserDetailMap(client: Client) { +export function buildLroDeserDetailMap( + context: SdkContext, + client: SdkClientType +) { const map = new Map(); const existingNames = new Set(); - for (const operationGroup of client.operationGroups) { - const operations = operationGroup.operations.filter((o) => - isLroOnlyOperation(o) - ); + const methodMap = getMethodHierarchiesMap(context, client); + for (const [prefixKey, operations] of methodMap) { + const prefixes = prefixKey.split("/"); + const lroOperations = operations.filter((o) => isLroOnlyOperation(o)); // skip this operation group if it has no LRO operations - if (operations.length === 0) { + if (lroOperations.length === 0) { continue; } const operationFileName = - operationGroup.className && operationGroup.namespaceHierarchies.length > 0 - ? `${operationGroup.namespaceHierarchies + prefixes.length > 0 && prefixKey !== "" + ? `${prefixes .map((hierarchy) => { return normalizeName(hierarchy, NameType.File); }) @@ -232,7 +245,7 @@ export function buildLroDeserDetailMap(client: Client) { "operations"; map.set( `./api/${operationFileName}.js`, - operations.map((o) => { + lroOperations.map((o) => { const { name } = getOperationName(o); const deserName = `_${name}Deserialize`; let renamedDeserName = undefined; @@ -245,7 +258,7 @@ export function buildLroDeserDetailMap(client: Client) { } existingNames.add(deserName); return { - path: `${o.method.toUpperCase()} ${o.url}`, + path: `${o.operation.verb.toUpperCase()} ${o.operation.path}`, expectedStatusesExpression: getExpectedStatuses(o), deserName, renamedDeserName diff --git a/packages/typespec-ts/src/modular/buildProjectFiles.ts b/packages/typespec-ts/src/modular/buildProjectFiles.ts index 1aae366571..55f4331748 100644 --- a/packages/typespec-ts/src/modular/buildProjectFiles.ts +++ b/packages/typespec-ts/src/modular/buildProjectFiles.ts @@ -1,20 +1,21 @@ -import { NameType, normalizeName } from "@azure-tools/rlc-common"; +import { NameType } from "@azure-tools/rlc-common"; -import { ModularCodeModel } from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; import { getClassicalLayerPrefix } from "./helpers/namingHelpers.js"; +import { SdkContext } from "@azure-tools/typespec-client-generator-core"; +import { getModularClientOptions } from "../utils/clientUtils.js"; +import { getMethodHierarchiesMap } from "../utils/operationUtil.js"; function buildExportsForMultiClient( - codeModel: ModularCodeModel, + context: SdkContext, + emitterOptions: ModularEmitterOptions, packageInfo: any ) { - if (codeModel.clients.length > 1) { + if (context.sdkPackage.clients.length > 1) { delete packageInfo.exports["./api"]; delete packageInfo.exports["./models"]; - for (const client of codeModel.clients) { - const subfolder = normalizeName( - client.name.replace("Client", ""), - NameType.File - ); + for (const client of context.sdkPackage.clients) { + const { subfolder } = getModularClientOptions(context, client); packageInfo.exports[`./${subfolder}`] = `./src/${subfolder}/index.ts`; packageInfo.exports[`./${subfolder}/api`] = @@ -23,18 +24,17 @@ function buildExportsForMultiClient( `./src/${subfolder}/models/index.ts`; } } - if (codeModel.options.hierarchyClient) { - for (const client of codeModel.clients) { - for (const operationGroup of client.operationGroups) { - if (operationGroup.namespaceHierarchies.length === 0) { + if (emitterOptions.options.hierarchyClient) { + for (const client of context.sdkPackage.clients) { + const { subfolder } = getModularClientOptions(context, client); + const methodMap = getMethodHierarchiesMap(context, client); + for (const [prefixKey, _] of methodMap) { + const prefixes = prefixKey.split("/"); + if (prefixKey === "") { continue; } - const subfolder = - codeModel.clients.length > 1 - ? normalizeName(client.name.replace("Client", ""), NameType.File) - : undefined; const subApiPath = `api/${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.File, "/" )}`; @@ -48,16 +48,19 @@ function buildExportsForMultiClient( return packageInfo.exports; } -export function getModuleExports(codeModel: ModularCodeModel) { +export function getModuleExports( + context: SdkContext, + emitterOptions: ModularEmitterOptions +) { const exports: Record = { exports: { ".": "./src/index.ts", "./models": "./src/models/index.ts" } }; - if (!codeModel.options.azureArm) { + if (!emitterOptions.options.azureArm) { exports["exports"]["./api"] = "./src/api/index.ts"; } - return buildExportsForMultiClient(codeModel, exports); + return buildExportsForMultiClient(context, emitterOptions, exports); } diff --git a/packages/typespec-ts/src/modular/buildRestorePoller.ts b/packages/typespec-ts/src/modular/buildRestorePoller.ts index 431719371a..4cb3abe56c 100644 --- a/packages/typespec-ts/src/modular/buildRestorePoller.ts +++ b/packages/typespec-ts/src/modular/buildRestorePoller.ts @@ -1,35 +1,43 @@ import { SourceFile } from "ts-morph"; import { isLroOnlyOperation } from "./helpers/operationHelpers.js"; -import { ModularCodeModel, Client } from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; import path from "path"; import { buildLroDeserDetailMap } from "./buildOperations.js"; import { getClientName } from "./helpers/namingHelpers.js"; import { NameType, normalizeName } from "@azure-tools/rlc-common"; import { resolveReference } from "../framework/reference.js"; -import { - AzureCoreDependencies, - AzurePollingDependencies -} from "./external-dependencies.js"; +import { AzurePollingDependencies } from "./external-dependencies.js"; import { PollingHelpers } from "./static-helpers-metadata.js"; +import { + SdkClientType, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { getMethodHierarchiesMap } from "../utils/operationUtil.js"; +import { getModularClientOptions } from "../utils/clientUtils.js"; +import { SdkContext } from "../utils/interfaces.js"; +import { useDependencies } from "../framework/hooks/useDependencies.js"; export function buildRestorePoller( - codeModel: ModularCodeModel, - client: Client + context: SdkContext, + client: SdkClientType, + emitterOptions: ModularEmitterOptions ) { - const lros = client.operationGroups - .flatMap((op) => op.operations) - .filter(isLroOnlyOperation); - if (lros.length === 0) { + const dependencies = useDependencies(); + const { subfolder } = getModularClientOptions(context, client); + const methodMap = getMethodHierarchiesMap(context, client); + const hasLro = Array.from(methodMap.values()).some((operations) => { + return operations.some(isLroOnlyOperation); + }); + if (!hasLro) { return; } - const srcPath = codeModel.modularOptions.sourceRoot; - const subfolder = client.subfolder ?? ""; + const srcPath = emitterOptions.modularOptions.sourceRoot; const filePath = path.join( `${srcPath}/${ - subfolder !== "" ? subfolder + "/" : "" + subfolder && subfolder !== "" ? subfolder + "/" : "" }restorePollerHelpers.ts` ); - const restorePollerFile = codeModel.project.createSourceFile( + const restorePollerFile = emitterOptions.project.createSourceFile( filePath, undefined, { @@ -38,9 +46,13 @@ export function buildRestorePoller( ); const clientNames = importClassicalClient(client, restorePollerFile); - const deserializeMap = importDeserializeHelpers(client, restorePollerFile); + const deserializeMap = importDeserializeHelpers( + context, + client, + restorePollerFile + ); const pathUncheckedReference = resolveReference( - AzureCoreDependencies.PathUncheckedResponse + dependencies.PathUncheckedResponse ); const pollerLikeReference = resolveReference( AzurePollingDependencies.PollerLike @@ -49,7 +61,7 @@ export function buildRestorePoller( AzurePollingDependencies.OperationState ); const operationOptionsReference = resolveReference( - AzureCoreDependencies.OperationOptions + dependencies.OperationOptions ); const deserializeStateReference = resolveReference( AzurePollingDependencies.DeserializeState @@ -64,7 +76,7 @@ export function buildRestorePoller( /** * The signal which can be used to abort requests. */ - abortSignal?: ${resolveReference(AzureCoreDependencies.AbortSignalLike)}; + abortSignal?: ${resolveReference(dependencies.AbortSignalLike)}; /** Deserialization function for raw response body */ processResponseBody?: (result: TResponse) => Promise; } @@ -203,8 +215,12 @@ export function buildRestorePoller( restorePollerFile.addStatements(restorePollerHelperContent); } -function importDeserializeHelpers(client: Client, sourceFile: SourceFile) { - const deserializeDetails = buildLroDeserDetailMap(client); +function importDeserializeHelpers( + context: SdkContext, + client: SdkClientType, + sourceFile: SourceFile +) { + const deserializeDetails = buildLroDeserDetailMap(context, client); const deserializeMap: string[] = []; for (const [key, value] of deserializeDetails.entries()) { sourceFile.addImportDeclaration({ @@ -227,10 +243,10 @@ function importDeserializeHelpers(client: Client, sourceFile: SourceFile) { } function importClassicalClient( - client: Client, + client: SdkClientType, sourceFile: SourceFile ): string[] { - const classicalClientName = `${getClientName(client.tcgcClient)}Client`; + const classicalClientName = `${getClientName(client)}Client`; sourceFile.addImportDeclaration({ namedImports: [`${classicalClientName}`], moduleSpecifier: `./${normalizeName(classicalClientName, NameType.File)}.js` diff --git a/packages/typespec-ts/src/modular/buildRootIndex.ts b/packages/typespec-ts/src/modular/buildRootIndex.ts index fcc3944914..d69aceb15b 100644 --- a/packages/typespec-ts/src/modular/buildRootIndex.ts +++ b/packages/typespec-ts/src/modular/buildRootIndex.ts @@ -4,21 +4,29 @@ import { getClassicalClientName, getClientName } from "./helpers/namingHelpers.js"; -import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; import { resolveReference } from "../framework/reference.js"; import { PagingHelpers } from "./static-helpers-metadata.js"; +import { + SdkClientType, + SdkContext, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { getModularClientOptions } from "../utils/clientUtils.js"; +import { getMethodHierarchiesMap } from "../utils/operationUtil.js"; export function buildRootIndex( - client: Client, - codeModel: ModularCodeModel, + context: SdkContext, + client: SdkClientType, + emitterOptions: ModularEmitterOptions, rootIndexFile: SourceFile ) { - const { project } = codeModel; - const srcPath = codeModel.modularOptions.sourceRoot; - const subfolder = client.subfolder ?? ""; - const clientName = `${getClassicalClientName(client.tcgcClient)}`; + const { project } = emitterOptions; + const srcPath = emitterOptions.modularOptions.sourceRoot; + const { subfolder } = getModularClientOptions(context, client); + const clientName = `${getClassicalClientName(client)}`; const clientFile = project.getSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}${normalizeName( + `${srcPath}/${subfolder && subfolder !== "" ? subfolder + "/" : ""}${normalizeName( clientName, NameType.File )}.ts` @@ -33,7 +41,7 @@ export function buildRootIndex( ); } - exportClassicalClient(client, rootIndexFile, subfolder); + exportClassicalClient(client, rootIndexFile, subfolder ?? ""); exportRestoreHelpers( rootIndexFile, project, @@ -62,17 +70,14 @@ export function buildRootIndex( isTopLevel: true }); - exportPagingTypes(codeModel, rootIndexFile); + exportPagingTypes(context, rootIndexFile); } /** * This is a temporary solution for adding paging exports. Eventually we will have the binder generate the exports automatically. */ -function exportPagingTypes( - codeModel: ModularCodeModel, - rootIndexFile: SourceFile -) { - if (!hasPaging(codeModel)) { +function exportPagingTypes(context: SdkContext, rootIndexFile: SourceFile) { + if (!hasPaging(context)) { return; } @@ -90,15 +95,18 @@ function exportPagingTypes( } } -function hasPaging(codeModel: ModularCodeModel): boolean { - return codeModel.clients.some((c) => - c.operationGroups.some((og) => - og.operations.some( - (op) => - op.discriminator === "paging" || op.discriminator === "lropaging" - ) - ) - ); +function hasPaging(context: SdkContext): boolean { + return context.sdkPackage.clients.some((client) => { + const methodMap = getMethodHierarchiesMap(context, client); + for (const [_, operations] of methodMap) { + if ( + operations.some((op) => op.kind === "paging" || op.kind === "lropaging") + ) { + return true; + } + } + return false; + }); } function getExistingExports(rootIndexFile: SourceFile): Set { @@ -139,7 +147,7 @@ function exportRestoreHelpers( ) { const helperFile = project.getSourceFile( `${srcPath}/${ - subfolder !== "" ? subfolder + "/" : "" + subfolder && subfolder !== "" ? subfolder + "/" : "" }restorePollerHelpers.ts` ); if (!helperFile) { @@ -155,7 +163,7 @@ function exportRestoreHelpers( } ); const moduleSpecifier = `./${ - isTopLevel && subfolder !== "" ? subfolder + "/" : "" + isTopLevel && subfolder && subfolder !== "" ? subfolder + "/" : "" }restorePollerHelpers.js`; indexFile.addExportDeclaration({ moduleSpecifier, @@ -164,16 +172,16 @@ function exportRestoreHelpers( } function exportClassicalClient( - client: Client, + client: SdkClientType, indexFile: SourceFile, subfolder: string, isSubClient: boolean = false ) { - const clientName = `${getClientName(client.tcgcClient)}Client`; + const clientName = `${getClientName(client)}Client`; indexFile.addExportDeclaration({ namedExports: [clientName], moduleSpecifier: `./${ - subfolder !== "" && !isSubClient ? subfolder + "/" : "" + subfolder && subfolder !== "" && !isSubClient ? subfolder + "/" : "" }${normalizeName(clientName, NameType.File)}.js` }); } @@ -248,37 +256,38 @@ function exportModules( } export function buildSubClientIndexFile( - client: Client, - codeModel: ModularCodeModel + context: SdkContext, + client: SdkClientType, + emitterOptions: ModularEmitterOptions ) { - const subfolder = client.subfolder ?? ""; - const srcPath = codeModel.modularOptions.sourceRoot; - const subClientIndexFile = codeModel.project.createSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}index.ts`, + const { subfolder } = getModularClientOptions(context, client); + const srcPath = emitterOptions.modularOptions.sourceRoot; + const subClientIndexFile = emitterOptions.project.createSourceFile( + `${srcPath}/${subfolder && subfolder !== "" ? subfolder + "/" : ""}index.ts`, undefined, { overwrite: true } ); - const clientName = `${getClientName(client.tcgcClient)}Client`; + const clientName = `${getClientName(client)}Client`; const clientFilePath = `${srcPath}/${ - subfolder !== "" ? subfolder + "/" : "" + subfolder && subfolder !== "" ? subfolder + "/" : "" }${normalizeName(clientName, NameType.File)}.ts`; - const clientFile = codeModel.project.getSourceFile(clientFilePath); + const clientFile = emitterOptions.project.getSourceFile(clientFilePath); if (!clientFile) { throw new Error(`Couldn't find client file: ${clientFilePath}`); } - exportClassicalClient(client, subClientIndexFile, subfolder, true); + exportClassicalClient(client, subClientIndexFile, subfolder ?? "", true); exportRestoreHelpers( subClientIndexFile, - codeModel.project, + emitterOptions.project, srcPath, clientName, subfolder ); exportModules( subClientIndexFile, - codeModel.project, + emitterOptions.project, srcPath, clientName, "api", @@ -289,7 +298,7 @@ export function buildSubClientIndexFile( ); exportModules( subClientIndexFile, - codeModel.project, + emitterOptions.project, srcPath, clientName, "classic", diff --git a/packages/typespec-ts/src/modular/buildSubpathIndex.ts b/packages/typespec-ts/src/modular/buildSubpathIndex.ts index ecefb353dc..ed5e904e1d 100644 --- a/packages/typespec-ts/src/modular/buildSubpathIndex.ts +++ b/packages/typespec-ts/src/modular/buildSubpathIndex.ts @@ -1,6 +1,12 @@ -import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { + SdkClientType, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { ModularEmitterOptions } from "./interfaces.js"; import { join } from "path"; +import { SdkContext } from "../utils/interfaces.js"; +import { getModularClientOptions } from "../utils/clientUtils.js"; export interface buildSubpathIndexFileOptions { exportIndex?: boolean; @@ -8,17 +14,20 @@ export interface buildSubpathIndexFileOptions { } export function buildSubpathIndexFile( - codeModel: ModularCodeModel, + context: SdkContext, + emitterOptions: ModularEmitterOptions, subpath: string, - client?: Client, + client?: SdkClientType, options: buildSubpathIndexFileOptions = {} ) { - const subfolder = client?.subfolder ?? ""; - const srcPath = codeModel.modularOptions.sourceRoot; + const subfolder = client + ? (getModularClientOptions(context, client).subfolder ?? "") + : ""; + const srcPath = emitterOptions.modularOptions.sourceRoot; // Skip to export these files because they are used internally. const skipFiles = ["pagingHelpers.ts", "pollingHelpers.ts"]; const apiFilePattern = join(srcPath, subfolder, subpath); - const apiFiles = codeModel.project.getSourceFiles().filter((file) => { + const apiFiles = emitterOptions.project.getSourceFiles().filter((file) => { return file .getFilePath() .replace(/\\/g, "/") @@ -27,7 +36,7 @@ export function buildSubpathIndexFile( if (apiFiles.length === 0) { return; } - const indexFile = codeModel.project.createSourceFile( + const indexFile = emitterOptions.project.createSourceFile( `${srcPath}/${subfolder}/${subpath}/index.ts` ); for (const file of apiFiles) { diff --git a/packages/typespec-ts/src/modular/emitLoggerFile.ts b/packages/typespec-ts/src/modular/emitLoggerFile.ts index 20d2d0b585..ac9fd1d754 100644 --- a/packages/typespec-ts/src/modular/emitLoggerFile.ts +++ b/packages/typespec-ts/src/modular/emitLoggerFile.ts @@ -1,18 +1,20 @@ -import { Project } from "ts-morph"; -import { ModularCodeModel } from "./modularCodeModel.js"; +import { ModularEmitterOptions } from "./interfaces.js"; export function emitLoggerFile( - codeModel: ModularCodeModel, - project: Project, + emitterOptions: ModularEmitterOptions, srcPath: string = "src" ) { - if (codeModel.options.flavor !== "azure") { + if (emitterOptions.options.flavor !== "azure") { return; } - const sourceFile = project.createSourceFile(`${srcPath}/logger.ts`, "", { - overwrite: true - }); + const sourceFile = emitterOptions.project.createSourceFile( + `${srcPath}/logger.ts`, + "", + { + overwrite: true + } + ); sourceFile.addImportDeclaration({ namedImports: ["createClientLogger"], @@ -20,8 +22,8 @@ export function emitLoggerFile( }); const name = - codeModel.options.packageDetails?.nameWithoutScope ?? - codeModel.options.packageDetails?.name; + emitterOptions.options.packageDetails?.nameWithoutScope ?? + emitterOptions.options.packageDetails?.name; sourceFile.addStatements( `export const logger = createClientLogger("${name}");` ); diff --git a/packages/typespec-ts/src/modular/emitModels.ts b/packages/typespec-ts/src/modular/emitModels.ts index 9d61584de9..325b4efc94 100644 --- a/packages/typespec-ts/src/modular/emitModels.ts +++ b/packages/typespec-ts/src/modular/emitModels.ts @@ -22,6 +22,7 @@ import { SdkModelType, SdkNullableType, SdkServiceMethod, + SdkServiceOperation, SdkType, SdkUnionType, UsageFlags, @@ -346,7 +347,7 @@ function emitEnumMember(member: SdkEnumValueType): EnumMemberStructure { return memberStructure; } -export function buildModelInterface( +function buildModelInterface( context: SdkContext, type: SdkModelType ): InterfaceDeclarationStructure { @@ -408,6 +409,13 @@ function addExtendedDictInfo( } modelInterface.extends.push(`Record`); } else { + reportDiagnostic(context.program, { + code: "compatible-additional-properties", + format: { + modelName: modelInterface?.name ?? "" + }, + target: NoTarget + }); modelInterface.properties?.push({ name: "additionalProperties", docs: ["Additional properties"], @@ -557,7 +565,7 @@ export function visitPackageTypes(context: SdkContext) { function visitClient( context: SdkContext, - client: SdkClientType + client: SdkClientType ) { // Comment this out for now, as client initialization is not used in the generated code // visitType(client.initialization, emitQueue); @@ -634,32 +642,32 @@ function visitType(context: SdkContext, type: SdkType | undefined) { visitType(context, type.additionalProperties); } for (const property of type.properties) { - if (!emitQueue.has(property.type as any)) { + if (!emitQueue.has(property.type)) { visitType(context, property.type); } } if (type.discriminatedSubtypes) { for (const subType of Object.values(type.discriminatedSubtypes)) { - if (!emitQueue.has(subType as any)) { + if (!emitQueue.has(subType)) { visitType(context, subType); } } } } if (type.kind === "array") { - if (!emitQueue.has(type.valueType as any)) { + if (!emitQueue.has(type.valueType)) { visitType(context, type.valueType); } } if (type.kind === "dict") { - if (!emitQueue.has(type.valueType as any)) { + if (!emitQueue.has(type.valueType)) { visitType(context, type.valueType); } } if (type.kind === "union") { emitQueue.add(type); for (const value of type.variantTypes) { - if (!emitQueue.has(value as any)) { + if (!emitQueue.has(value)) { visitType(context, value); } } diff --git a/packages/typespec-ts/src/modular/emitModelsOptions.ts b/packages/typespec-ts/src/modular/emitModelsOptions.ts index 4c86bd6649..1c6eb9826c 100644 --- a/packages/typespec-ts/src/modular/emitModelsOptions.ts +++ b/packages/typespec-ts/src/modular/emitModelsOptions.ts @@ -1,128 +1,28 @@ import * as path from "path"; -import { - Client, - ModularCodeModel, - Type as ModularType -} from "./modularCodeModel.js"; -import { InterfaceDeclarationStructure, OptionalKind } from "ts-morph"; +import { ModularEmitterOptions } from "./interfaces.js"; import { buildOperationOptions } from "./buildOperations.js"; -import { getDocsFromDescription } from "./helpers/docsHelpers.js"; -import { getImportSpecifier } from "@azure-tools/rlc-common"; -import { getType } from "./helpers/typeHelpers.js"; import { SdkContext } from "../utils/interfaces.js"; +import { + SdkClientType, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { getMethodHierarchiesMap } from "../utils/operationUtil.js"; +import { getModularClientOptions } from "../utils/clientUtils.js"; // ====== UTILITIES ====== -function isAzureCoreErrorSdkType(t: ModularType) { - return ( - t.name && - ["error", "errormodel", "innererror", "errorresponse"].includes( - t.name.toLowerCase() - ) && - t.coreTypeInfo === "ErrorType" - ); -} - -function isAzureCoreLroSdkType(t: ModularType) { - return ( - t.name && - ["operationstate"].includes(t.name.toLowerCase()) && - t.coreTypeInfo === "LroType" - ); -} - -export function isModelWithAdditionalProperties(t: ModularType) { - return t.type === "dict" && t.name !== "Record"; -} - -function getCoreClientErrorType(name: string, coreClientTypes: Set) { - const coreClientType: string = name === "Error" ? "ErrorModel" : name; - coreClientTypes.add(coreClientType); - return coreClientType; -} - -function getCoreLroType(name: string, coreLroTypes: Set) { - const coreLroType = name === "OperationState" ? "CoreOperationStatus" : name; - coreLroTypes.add(coreLroType); - return coreLroType; -} - -/** - * Extracts all the aliases from the code model - * 1. alias from polymorphic base model, where we need to use typescript union to combine all the sub models - * 2. alias from unions, where we also need to use typescript union to combine all the union variants - */ -export function extractAliases(codeModel: ModularCodeModel): ModularType[] { - const models = codeModel.types.filter( - (t) => - ((t.type === "model" || t.type === "combined") && - t.alias && - t.aliasType) || - (isModelWithAdditionalProperties(t) && t.alias && t.aliasType) - ); - return models; -} - -type InterfaceStructure = OptionalKind & { - extends: string[]; -}; - -export function buildModelInterface( - model: ModularType, - cache: { coreClientTypes: Set; coreLroTypes: Set } -): InterfaceStructure { - const modelProperties = model.properties ?? []; - const modelInterface = { - name: model.alias ?? model.name ?? "FIXMYNAME", - isExported: true, - docs: getDocsFromDescription(model.description), - extends: [] as string[], - properties: (modelProperties ?? []).map((p) => { - const propertyMetadata = getType(p.type, p.format); - let propertyTypeName = propertyMetadata.name; - if (isAzureCoreErrorSdkType(p.type)) { - propertyTypeName = getCoreClientErrorType( - propertyTypeName, - cache.coreClientTypes - ); - } - if (isAzureCoreLroSdkType(p.type)) { - propertyTypeName = getCoreLroType(propertyTypeName, cache.coreLroTypes); - } - - return { - name: `"${p.clientName}"`, - docs: getDocsFromDescription(p.description), - hasQuestionToken: p.optional, - isReadonly: p.readonly, - type: propertyTypeName - }; - }) - }; - - return modelInterface; -} - -export function buildModelTypeAlias(model: ModularType) { - return { - name: model.name!, - isExported: true, - docs: ["Alias for " + model.name], - type: model.aliasType! - }; -} - export function buildApiOptions( context: SdkContext, - client: Client, - codeModel: ModularCodeModel + client: SdkClientType, + emitterOptions: ModularEmitterOptions ) { - const modelOptionsFile = codeModel.project.createSourceFile( + const { subfolder } = getModularClientOptions(context, client); + const modelOptionsFile = emitterOptions.project.createSourceFile( path.join( - codeModel.modularOptions.sourceRoot, - client.subfolder ?? "", + emitterOptions.modularOptions.sourceRoot, + subfolder ?? "", `api/options.ts` ), undefined, @@ -130,20 +30,13 @@ export function buildApiOptions( overwrite: true } ); - for (const operationGroup of client.operationGroups) { - operationGroup.operations.forEach((o) => { - buildOperationOptions(context, o, modelOptionsFile); + const methodMap = getMethodHierarchiesMap(context, client); + for (const [prefixKey, operations] of methodMap) { + const prefixes = prefixKey.split("/"); + operations.forEach((o) => { + buildOperationOptions(context, [prefixes, o], modelOptionsFile); }); } - modelOptionsFile.addImportDeclarations([ - { - moduleSpecifier: getImportSpecifier( - "restClient", - codeModel.runtimeImports - ), - namedImports: ["OperationOptions"] - } - ]); modelOptionsFile .getImportDeclarations() diff --git a/packages/typespec-ts/src/modular/emitSamples.ts b/packages/typespec-ts/src/modular/emitSamples.ts index 9353979bd0..82df4e61a7 100644 --- a/packages/typespec-ts/src/modular/emitSamples.ts +++ b/packages/typespec-ts/src/modular/emitSamples.ts @@ -243,9 +243,8 @@ function buildParameterValueMap(example: SdkHttpOperationExample) { const parameterMap: Record = {}; example.parameters.forEach( (param) => - (parameterMap[ - (param.parameter as any).serializedName ?? param.parameter.name - ] = param) + (parameterMap[param.parameter.serializedName ?? param.parameter.name] = + param) ); return parameterMap; } diff --git a/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts b/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts index facf2313b1..c8618a6fd6 100644 --- a/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/classicalOperationHelpers.ts @@ -6,50 +6,42 @@ import { SourceFile, StructureKind } from "ts-morph"; -import { Client, OperationGroup } from "../modularCodeModel.js"; -import { getClassicalLayerPrefix, getClientName } from "./namingHelpers.js"; +import { getClassicalLayerPrefix } from "./namingHelpers.js"; import { getOperationFunction } from "./operationHelpers.js"; import { SdkContext } from "../../utils/interfaces.js"; +import { + SdkClientType, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; +import { getModularClientOptions } from "../../utils/clientUtils.js"; +import { ServiceOperation } from "../../utils/operationUtil.js"; -export function shouldPromoteSubscriptionId( - dpgContext: SdkContext, - operationGroup: OperationGroup -) { - const hasSubscriptionIdParameter = operationGroup.operations.some((op) => - op.parameters.some((p) => p.clientName === "subscriptionId") - ); - return dpgContext?.rlcOptions?.azureArm && hasSubscriptionIdParameter; -} export function getClassicalOperation( dpgContext: SdkContext, - client: Client, + client: SdkClientType, classicFile: SourceFile, - operationGroup: OperationGroup, - layer: number = operationGroup.namespaceHierarchies.length - 1 + operationGroup: [string[], ServiceOperation[]], + layer: number = operationGroup[0].length - 1 ) { - // TODO: remove this logic once client-level parameter design is finalized - // https://github.com/Azure/autorest.typescript/issues/2618 - const hasSubscriptionIdPromoted = shouldPromoteSubscriptionId( - dpgContext, - operationGroup - ); - const modularClientName = `${getClientName(client.tcgcClient)}Context`; + const prefixes = operationGroup[0]; + const operations = operationGroup[1]; + const { rlcClientName } = getModularClientOptions(dpgContext, client); const hasClientContextImport = classicFile .getImportDeclarations() .filter((i) => { return ( i.getModuleSpecifierValue() === `${"../".repeat(layer + 2)}api/${normalizeName( - modularClientName, + rlcClientName, NameType.File )}.js` ); }); if (!hasClientContextImport || hasClientContextImport.length === 0) { classicFile.addImportDeclaration({ - namedImports: [client.rlcClientName], + namedImports: [rlcClientName], moduleSpecifier: `${"../".repeat(layer + 2)}api/${normalizeName( - modularClientName, + rlcClientName, NameType.File )}.js` }); @@ -60,18 +52,18 @@ export function getClassicalOperation( string | undefined >(); const operationDeclarations: OptionalKind[] = - operationGroup.operations.map((operation) => { + operations.map((operation) => { const declarations = getOperationFunction( dpgContext, - operation, - modularClientName + [prefixes, operation], + rlcClientName ); operationMap.set(declarations, operation.oriName); return declarations; }); const interfaceNamePrefix = getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer @@ -81,18 +73,17 @@ export function getClassicalOperation( .getInterfaces() .filter((i) => i.getName() === interfaceName)[0]; const properties: OptionalKind[] = []; - if (layer !== operationGroup.namespaceHierarchies.length - 1) { + if (layer !== prefixes.length - 1) { properties.push({ kind: StructureKind.PropertySignature, - name: - normalizeName( - (layer === operationGroup.namespaceHierarchies.length - 1 - ? operationGroup.namespaceHierarchies[layer] - : operationGroup.namespaceHierarchies[layer + 1]) ?? "", - NameType.Property - ) ?? operationGroup.propertyName, + name: normalizeName( + (layer === prefixes.length - 1 + ? prefixes[layer] + : prefixes[layer + 1]) ?? "", + NameType.Property + ), type: `${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer + 1 @@ -105,9 +96,6 @@ export function getClassicalOperation( name: getClassicalMethodName(d), type: `(${d.parameters ?.filter((p) => p.name !== "context") - ?.filter( - (p) => !(hasSubscriptionIdPromoted && p.name === "subscriptionId") - ) .map( (p) => p.name + @@ -134,10 +122,10 @@ export function getClassicalOperation( }); } - if (layer === operationGroup.namespaceHierarchies.length - 1) { + if (layer === prefixes.length - 1) { classicFile.addFunction({ name: `get${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer @@ -146,21 +134,14 @@ export function getClassicalOperation( parameters: [ { name: "context", - type: client.rlcClientName - }, - ...(hasSubscriptionIdPromoted - ? [{ name: "subscriptionId", type: "string" }] - : []) + type: rlcClientName + } ], statements: `return { ${operationDeclarations .map((d) => { return `${getClassicalMethodName(d)}: (${d.parameters ?.filter((p) => p.name !== "context") - ?.filter( - (p) => - !(hasSubscriptionIdPromoted && p.name === "subscriptionId") - ) .map( (p) => p.name + @@ -184,7 +165,7 @@ export function getClassicalOperation( } const operationFunctionName = `get${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer @@ -197,57 +178,50 @@ export function getClassicalOperation( if (returnStatement) { let statement = `, ...get${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer + 1 - )}Operations(context${ - hasSubscriptionIdPromoted ? ", subscriptionId" : "" - })}`; - if (layer !== operationGroup.namespaceHierarchies.length - 1) { + )}Operations(context)}`; + if (layer !== prefixes.length - 1) { statement = `, ${normalizeName( - operationGroup.namespaceHierarchies[layer + 1] ?? "FIXME", + prefixes[layer + 1] ?? "FIXME", NameType.Property )}: get${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer + 1 - )}Operations(context${ - hasSubscriptionIdPromoted ? ", subscriptionId" : "" - })}`; + )}Operations(context)}`; } const newReturnStatement = returnStatement.replace(/}$/, statement); existFunction.setBodyText(newReturnStatement); } } else { - classicFile.addFunction({ + const functions = { name: operationFunctionName, isExported: true, parameters: [ { name: "context", - type: client.rlcClientName - }, - ...(hasSubscriptionIdPromoted - ? [{ name: "subscriptionId", type: "string" }] - : []) + type: rlcClientName + } ], returnType: `${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer )}Operations`, statements: - layer !== operationGroup.namespaceHierarchies.length - 1 + layer !== prefixes.length - 1 ? `return { ${normalizeName( - operationGroup.namespaceHierarchies[layer + 1] ?? "FIXME", + prefixes[layer + 1] ?? "FIXME", NameType.Property )}: get${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer + 1 @@ -255,13 +229,14 @@ export function getClassicalOperation( }` : `return { ...get${getClassicalLayerPrefix( - operationGroup, + prefixes, NameType.Interface, "", layer - )}(context${hasSubscriptionIdPromoted ? ", subscriptionId" : ""}) + )}(context) }` - }); + }; + classicFile.addFunction(functions); } function getClassicalMethodName( diff --git a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts index 486a061c37..c93c1581f8 100644 --- a/packages/typespec-ts/src/modular/helpers/clientHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/clientHelpers.ts @@ -1,12 +1,14 @@ -import { Client, ModularCodeModel } from "../modularCodeModel.js"; +import { ModularEmitterOptions } from "../interfaces.js"; import { OptionalKind, ParameterDeclarationStructure, StatementedNode } from "ts-morph"; import { + SdkClientType, SdkHttpParameter, - SdkParameter + SdkParameter, + SdkServiceOperation } from "@azure-tools/typespec-client-generator-core"; import { @@ -23,44 +25,58 @@ interface ClientParameterOptions { onClientOnly?: boolean; requiredOnly?: boolean; optionalOnly?: boolean; + skipArmSpecific?: boolean; + skipEndpointTemplate?: boolean; + apiVersionAsRequired?: boolean; } export function getClientParameters( - _client: Client, + client: SdkClientType, dpgContext: SdkContext, options: ClientParameterOptions = { requiredOnly: false, onClientOnly: false, - optionalOnly: false + optionalOnly: false, + skipArmSpecific: false, + skipEndpointTemplate: false, + apiVersionAsRequired: true } ) { - const client = _client.tcgcClient; const clientParams: (SdkParameter | SdkHttpParameter)[] = []; for (const property of client.initialization.properties) { if ( property.type.kind === "union" && property.type.variantTypes[0]?.kind === "endpoint" ) { - clientParams.push(...property.type.variantTypes[0].templateArguments); + if (options.skipEndpointTemplate) { + clientParams.push(property); + } else { + clientParams.push(...property.type.variantTypes[0].templateArguments); + } } else if (property.type.kind === "endpoint") { - clientParams.push(...property.type.templateArguments); + clientParams.push(property); } else if (!clientParams.find((p) => p.name === property.name)) { clientParams.push(property); } } + const hasDefaultValue = (p: SdkParameter | SdkHttpParameter) => p.clientDefaultValue || p.__raw?.defaultValue || p.type.kind === "constant"; const isRequired = (p: SdkParameter | SdkHttpParameter) => - !p.optional && !hasDefaultValue(p); + !p.optional && + ((!hasDefaultValue(p) && + !( + p.type.kind === "endpoint" && + p.type.templateArguments[0] && + hasDefaultValue(p.type.templateArguments[0]) + )) || + (options.apiVersionAsRequired && p.isApiVersionParam)); const isOptional = (p: SdkParameter | SdkHttpParameter) => p.optional || hasDefaultValue(p); const skipCredentials = (p: SdkParameter | SdkHttpParameter) => p.kind !== "credential"; const skipMethodParam = (p: SdkParameter | SdkHttpParameter) => - p.kind !== "method" || - (p.kind === "method" && - p.isApiVersionParam && - _client.parameters.find((p) => p.isApiVersion)); + p.kind !== "method"; const armSpecific = (p: SdkParameter | SdkHttpParameter) => !(p.kind === "endpoint" && dpgContext.arm); const filters = [ @@ -70,7 +86,7 @@ export function getClientParameters( : undefined, options.optionalOnly ? isOptional : undefined, options.onClientOnly ? skipMethodParam : undefined, - armSpecific + options.skipArmSpecific ? undefined : armSpecific ]; const params = clientParams.filter((p) => filters.every((filter) => !filter || filter(p)) @@ -80,15 +96,16 @@ export function getClientParameters( } export function getClientParametersDeclaration( - _client: Client, + client: SdkClientType, dpgContext: SdkContext, options: ClientParameterOptions = { optionalOnly: false, requiredOnly: false, - onClientOnly: false + onClientOnly: false, + skipArmSpecific: false, + apiVersionAsRequired: false } ): OptionalKind[] { - const client = _client.tcgcClient; const name = getClientName(client); const optionsParam = { name: "options", @@ -97,7 +114,7 @@ export function getClientParametersDeclaration( }; const params: OptionalKind[] = [ - ...getClientParameters(_client, dpgContext, options).map< + ...getClientParameters(client, dpgContext, options).map< OptionalKind >((p) => { const typeExpression = getClientParameterTypeExpression(dpgContext, p); @@ -151,57 +168,68 @@ export function getClientParameterName( export function buildGetClientEndpointParam( context: StatementedNode, dpgContext: SdkContext, - client: Client + client: SdkClientType ): string { + let coreEndpointParam = ""; + if (dpgContext.rlcOptions?.flavor === "azure") { + coreEndpointParam = `options.endpoint ?? options.baseUrl`; + } else { + // unbranded does not have the deprecated baseUrl parameter + coreEndpointParam = `options.endpoint`; + } // Special case: endpoint URL not defined - if (client.url === "") { - const endpointParam = getClientParameters(client, dpgContext, { - onClientOnly: true - }).find((x) => x.kind === "endpoint" || x.kind === "path"); - if (endpointParam) { - if (dpgContext.rlcOptions?.flavor === "azure") { - return `options.endpoint ?? options.baseUrl ?? String(${getClientParameterName(endpointParam)})`; - } else { - // unbranded does not have the deprecated baseUrl parameter - return `options.endpoint ?? String(${getClientParameterName(endpointParam)})`; + const endpointParam = getClientParameters(client, dpgContext, { + onClientOnly: true, + skipEndpointTemplate: true, + skipArmSpecific: true + }).find((x) => x.kind === "endpoint" || x.kind === "path"); + if (endpointParam) { + if ( + endpointParam.type.kind === "union" && + endpointParam.type.variantTypes[0]?.kind === "endpoint" + ) { + const params = endpointParam.type.variantTypes[0].templateArguments; + let parameterizedEndpointUrl = + endpointParam.type.variantTypes[0].serverUrl; + for (const templateParam of params) { + const paramName = getClientParameterName(templateParam); + if (templateParam.clientDefaultValue) { + const defaultValue = + typeof templateParam.clientDefaultValue === "string" + ? `"${templateParam.clientDefaultValue}"` + : templateParam.clientDefaultValue; + context.addStatements( + `const ${paramName} = options.${paramName} ?? ${defaultValue};` + ); + } else if (templateParam.optional) { + context.addStatements(`const ${paramName} = options.${paramName};`); + } + parameterizedEndpointUrl = parameterizedEndpointUrl.replace( + `{${templateParam.name}}`, + `\${${getClientParameterName(templateParam)}}` + ); } + const endpointUrl = `const endpointUrl = ${coreEndpointParam} ?? \`${parameterizedEndpointUrl}\`;`; + context.addStatements(endpointUrl); + return "endpointUrl"; + } else if (endpointParam.type.kind === "endpoint") { + const clientDefaultValue = + endpointParam.type.templateArguments[0]?.clientDefaultValue; + const defaultValueStr = + clientDefaultValue && typeof clientDefaultValue === "string" + ? `"${clientDefaultValue}"` + : clientDefaultValue + ? clientDefaultValue + : `String(${getClientParameterName(endpointParam)})`; + const endpointUrl = `const endpointUrl = ${coreEndpointParam} ?? ${defaultValueStr};`; + context.addStatements(endpointUrl); + return "endpointUrl"; } + const endpointUrl = `const endpointUrl = ${coreEndpointParam} ?? String(${getClientParameterName(endpointParam)});`; + context.addStatements(endpointUrl); + return "endpointUrl"; } - const urlParams = getClientParameters(client, dpgContext).filter( - (x) => x.kind === "endpoint" || x.kind === "path" - ); - - for (const param of urlParams) { - const paramName = getClientParameterName(param); - if (param.clientDefaultValue) { - const defaultValue = - typeof param.clientDefaultValue === "string" - ? `"${param.clientDefaultValue}"` - : param.clientDefaultValue; - context.addStatements( - `const ${paramName} = options.${paramName} ?? ${defaultValue};` - ); - } else if (param.optional) { - context.addStatements(`const ${paramName} = options.${paramName};`); - } - } - - let parameterizedEndpointUrl = client.url; - for (const param of urlParams) { - parameterizedEndpointUrl = parameterizedEndpointUrl.replace( - `{${param.serializedName}}`, - `\${${getClientParameterName(param)}}` - ); - } - let endpointUrl = ""; - if (dpgContext.rlcOptions?.flavor === "azure") { - endpointUrl = `const endpointUrl = options.endpoint ?? options.baseUrl ?? \`${parameterizedEndpointUrl}\``; - } else { - // unbranded does not have the deprecated baseUrl parameter - endpointUrl = `const endpointUrl = options.endpoint ?? \`${parameterizedEndpointUrl}\``; - } - context.addStatements(endpointUrl); return "endpointUrl"; } @@ -214,16 +242,16 @@ export function buildGetClientEndpointParam( */ export function buildGetClientOptionsParam( context: StatementedNode, - codeModel: ModularCodeModel, + emitterOptions: ModularEmitterOptions, endpointParam: string ): string { const userAgentOptions = buildUserAgentOptions( context, - codeModel, + emitterOptions, "azsdk-js-api" ); - const loggingOptions = buildLoggingOptions(codeModel.options.flavor); - const credentials = buildCredentials(codeModel, endpointParam); + const loggingOptions = buildLoggingOptions(emitterOptions.options.flavor); + const credentials = buildCredentials(emitterOptions, endpointParam); let expr = "const { apiVersion: _, ...updatedOptions } = {"; @@ -246,16 +274,16 @@ export function buildGetClientOptionsParam( } export function buildGetClientCredentialParam( - client: Client, - codeModel: ModularCodeModel + client: SdkClientType, + emitterOptions: ModularEmitterOptions ): string { if ( - codeModel.options.addCredentials && - (codeModel.options.credentialScopes || - codeModel.options.credentialKeyHeaderName) + emitterOptions.options.addCredentials && + (emitterOptions.options.credentialScopes || + emitterOptions.options.credentialKeyHeaderName) ) { return ( - client.parameters.find((x) => isCredentialType(x.type))?.clientName ?? + client.initialization.properties.find((x) => isCredentialType(x))?.name ?? "undefined" ); } else { @@ -264,14 +292,14 @@ export function buildGetClientCredentialParam( } function buildCredentials( - codeModel: ModularCodeModel, + emitterOptions: ModularEmitterOptions, endpointParam: string ): string | undefined { - if (!codeModel.options.addCredentials) { + if (!emitterOptions.options.addCredentials) { return undefined; } - const { credentialScopes, credentialKeyHeaderName } = codeModel.options; + const { credentialScopes, credentialKeyHeaderName } = emitterOptions.options; const scopesString = credentialScopes ? credentialScopes.map((cs) => `"${cs}"`).join(", ") || @@ -302,7 +330,7 @@ function buildLoggingOptions(flavor?: PackageFlavor): string | undefined { export function buildUserAgentOptions( context: StatementedNode, - codeModel: ModularCodeModel, + emitterOptions: ModularEmitterOptions, sdkUserAgentPrefix: string ): string { const userAgentStatements = []; @@ -311,10 +339,10 @@ export function buildUserAgentOptions( userAgentStatements.push(prefixFromOptions); const clientPackageName = - codeModel.options.packageDetails?.nameWithoutScope ?? - codeModel.options.packageDetails?.name ?? + emitterOptions.options.packageDetails?.nameWithoutScope ?? + emitterOptions.options.packageDetails?.name ?? ""; - const packageVersion = codeModel.options.packageDetails?.version ?? ""; + const packageVersion = emitterOptions.options.packageDetails?.version ?? ""; const userAgentInfoStatement = packageVersion && clientPackageName && sdkUserAgentPrefix.includes("api") diff --git a/packages/typespec-ts/src/modular/helpers/namingHelpers.ts b/packages/typespec-ts/src/modular/helpers/namingHelpers.ts index e25577ca0c..7e7a9258c1 100644 --- a/packages/typespec-ts/src/modular/helpers/namingHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/namingHelpers.ts @@ -4,19 +4,11 @@ import { ReservedModelNames } from "@azure-tools/rlc-common"; import { - SdkClient, SdkClientType, SdkServiceOperation } from "@azure-tools/typespec-client-generator-core"; -import * as path from "path"; +import { ServiceOperation } from "../../utils/operationUtil.js"; import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; -import { SdkContext } from "../../utils/interfaces.js"; -import { - Client, - ModularCodeModel, - Operation, - OperationGroup -} from "../modularCodeModel.js"; export function getClientName( client: SdkClientType @@ -36,7 +28,7 @@ export interface GuardedName { } export function getOperationName( - operation: Operation, + operation: ServiceOperation, options: { casing: "camel" | "pascal" } = { casing: "camel" } ): GuardedName { const casingFn = options.casing === "camel" ? toCamelCase : toPascalCase; @@ -65,25 +57,20 @@ export function isReservedName(name: string, nameType: NameType): boolean { } export function getClassicalLayerPrefix( - operationGroup: OperationGroup | Operation, + prefixes: string[], nameType: NameType, separator: string = "", - layer: number = operationGroup.namespaceHierarchies.length - 1 + layer: number = prefixes.length - 1 ): string { const prefix: string[] = []; if (layer < 0) { return prefix.join(separator); } if (layer === 0) { - return normalizeName( - operationGroup.namespaceHierarchies[0] ?? "", - nameType - ); + return normalizeName(prefixes[0] ?? "", nameType); } for (let i = 0; i <= layer; i++) { - prefix.push( - normalizeName(operationGroup.namespaceHierarchies[i] ?? "", nameType) - ); + prefix.push(normalizeName(prefixes[i] ?? "", nameType)); } return prefix.join(separator); } @@ -91,49 +78,3 @@ export function getClassicalLayerPrefix( export function isDefined(thing: T | undefined | null): thing is T { return typeof thing !== "undefined" && thing !== null; } - -export function getRLCIndexFilePath( - dpgContext: SdkContext, - client: Client | SdkClient, - ext: "js" | "ts" = "ts" -): string { - return path.join( - ...[ - dpgContext.generationPathDetail?.rlcSourcesDir, - getSubfolder(client, dpgContext), - `index.${ext}` - ].filter(isDefined) - ); -} - -export function getModularModelFilePath( - codeModel: ModularCodeModel, - client: Client | SdkClient, - ext: "js" | "ts" = "ts" -): string { - return path.join( - ...[ - codeModel.modularOptions.sourceRoot, - getSubfolder(client), - "models", - `models.${ext}` - ].filter(isDefined) - ); -} - -function getSubfolder(client: Client): string | undefined; -function getSubfolder( - client: Client | SdkClient, - dpgContext?: SdkContext -): string | undefined; -function getSubfolder( - client: Client | SdkClient, - dpgContext?: SdkContext -): string | undefined { - return ( - (client as Client).subfolder ?? - (dpgContext?.rlcOptions!.batch && dpgContext?.rlcOptions!.batch?.length > 1 - ? normalizeName(client.name.replace("Client", ""), NameType.File) - : undefined) - ); -} diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 51f4dca51c..d0ccfb0672 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -1,12 +1,3 @@ -import { - BodyParameter, - Client, - ModularCodeModel, - Operation, - Parameter, - Property, - Type -} from "../modularCodeModel.js"; import { FunctionDeclarationStructure, OptionalKind, @@ -14,11 +5,17 @@ import { } from "ts-morph"; import { NoTarget, Program } from "@typespec/compiler"; import { PagingHelpers, PollingHelpers } from "../static-helpers-metadata.js"; -import { getType, isTypeNullable } from "./typeHelpers.js"; +import { + getNullableValidType, + isSpreadBodyParameter, + isTypeNullable +} from "./typeHelpers.js"; import { getClassicalLayerPrefix, getOperationName } from "./namingHelpers.js"; import { getCollectionFormatHelper, - hasCollectionFormatInfo + hasCollectionFormatInfo, + isBinaryPayload, + ServiceOperation } from "../../utils/operationUtil.js"; import { isNormalUnion, @@ -31,7 +28,7 @@ import { import { toPascalCase } from "../../utils/casingUtils.js"; import { AzurePollingDependencies } from "../external-dependencies.js"; -import { NameType } from "@azure-tools/rlc-common"; +import { NameType, normalizeName } from "@azure-tools/rlc-common"; import { buildModelDeserializer } from "../serialization/buildDeserializerFunction.js"; import { buildModelSerializer } from "../serialization/buildSerializerFunction.js"; import { refkey } from "../../framework/refkey.js"; @@ -40,17 +37,38 @@ import { resolveReference } from "../../framework/reference.js"; import { useDependencies } from "../../framework/hooks/useDependencies.js"; import { useSdkTypes } from "../../framework/hooks/sdkTypes.js"; import { isAzureCoreErrorType } from "../../utils/modelUtils.js"; -import { getTypeExpression } from "../type-expressions/get-type-expression.js"; +import { + getTypeExpression, + normalizeModelPropertyName +} from "../type-expressions/get-type-expression.js"; import { SdkContext } from "../../utils/interfaces.js"; +import { + isReadOnly, + SdkBodyParameter, + SdkClientType, + SdkConstantType, + SdkHttpOperation, + SdkHttpParameter, + SdkLroPagingServiceMethod, + SdkLroServiceMethod, + SdkMethod, + SdkModelPropertyType, + SdkModelType, + SdkPagingServiceMethod, + SdkServiceParameter, + SdkType +} from "@azure-tools/typespec-client-generator-core"; export function getSendPrivateFunction( dpgContext: SdkContext, - operation: Operation, + client: SdkClientType, + method: [string[], ServiceOperation], clientType: string ): OptionalKind { + const operation = method[1]; const parameters = getOperationSignatureParameters( dpgContext, - operation, + method, clientType ); const { name } = getOperationName(operation); @@ -64,20 +82,31 @@ export function getSendPrivateFunction( returnType: resolveReference(dependencies.StreamableMethod) }; - const operationPath = operation.url; - const operationMethod = operation.method.toLowerCase(); - const optionalParamName = parameters.filter((p) => - p.type?.toString().endsWith("OptionalParams") - )[0]?.name; - + const operationPath = operation.operation.path; + const operationMethod = operation.operation.verb.toLowerCase(); + const optionalParamName = getOptionalParamsName(parameters); + const hasQueryApiVersion = operation.operation.parameters.some( + (p) => p.isApiVersionParam && p.onClient && p.kind === "query" + ); + const hasClientApiVersion = client.initialization.properties.some( + (p) => p.isApiVersionParam && p.onClient && p.kind === "method" + ); const statements: string[] = []; + if (hasClientApiVersion && !hasQueryApiVersion) { + statements.push( + `context.pipeline.removePolicy({ name: "ClientApiVersionPolicy"});` + ); + } + statements.push( `return context.path("${operationPath}", ${getPathParameters( dpgContext, - operation + operation, + optionalParamName )}).${operationMethod}({...${resolveReference(dependencies.operationOptionsToRequestParameters)}(${optionalParamName}), ${getRequestParameters( dpgContext, - operation + operation, + optionalParamName )}});` ); @@ -89,7 +118,7 @@ export function getSendPrivateFunction( export function getDeserializePrivateFunction( context: SdkContext, - operation: Operation + operation: ServiceOperation ): OptionalKind { const { name } = getOperationName(operation); const dependencies = useDependencies(); @@ -108,14 +137,15 @@ export function getDeserializePrivateFunction( // TODO: Support operation overloads // TODO: Support multiple responses - const response = operation.responses[0]!; + const response = operation.response; + const restResponse = operation.operation.responses[0]; let returnType; - if (isLroOnly && operation.method.toLowerCase() !== "patch") { + if (isLroOnly && operation.operation.verb.toLowerCase() !== "patch") { returnType = buildLroReturnType(context, operation); - } else if (response?.type?.type) { + } else if (response.type && restResponse) { returnType = { - name: response.type.name, - type: getTypeExpression(context, response.type.tcgcType!) + name: (restResponse as any).name ?? "", + type: getTypeExpression(context, restResponse.type!) }; } else { returnType = { name: "", type: "void" }; @@ -142,16 +172,18 @@ export function getDeserializePrivateFunction( "}" ); const deserializedType = isLroOnly - ? operation?.lroMetadata?.finalResult - : response.type; - const hasLroSubPath = operation?.lroMetadata?.finalResultPath !== undefined; + ? operation?.lroMetadata?.finalResponse?.result + : restResponse + ? restResponse.type + : response.type; + const lroSubPath = isLroOnly + ? operation?.lroMetadata?.finalResponse?.resultPath + : undefined; const deserializePrefix = "result.body"; - const deserializedRoot = hasLroSubPath - ? `${deserializePrefix}.${operation?.lroMetadata?.finalResultPath}` - : `${deserializePrefix}`; - if (isLroOnly && hasLroSubPath) { + const deserializedRoot = `${deserializePrefix}${lroSubPath ? "." + lroSubPath : ""}`; + if (isLroOnly && lroSubPath) { statements.push( `if(${deserializedRoot.split(".").join("?.")} === undefined) { throw createRestError(\`Expected a result in the response at position "${deserializedRoot}"\`, result); @@ -160,10 +192,11 @@ export function getDeserializePrivateFunction( ); } - if (deserializedType?.tcgcType) { + if (deserializedType) { + const contentTypes = operation.operation.responses[0]?.contentTypes; const deserializeFunctionName = buildModelDeserializer( context, - deserializedType.tcgcType, + deserializedType, false, true ); @@ -177,21 +210,14 @@ export function getDeserializePrivateFunction( context, deserializedType, deserializedRoot, - response.isBinaryPayload ? "binary" : deserializedType.format + isBinaryPayload(context, response.type!.__raw!, contentTypes!) + ? "binary" + : getEncodeForType(deserializedType) )}` ); } } else if (returnType.type === "void") { statements.push("return;"); - } else if (deserializedType) { - statements.push( - `return ${deserializeResponseValue( - context, - deserializedType, - deserializedRoot, - response.isBinaryPayload ? "binary" : deserializedType.format - )}` - ); } else { statements.push("return;"); } @@ -202,12 +228,22 @@ export function getDeserializePrivateFunction( }; } +function getOptionalParamsName( + parameters: OptionalKind[] +) { + return ( + parameters.filter((p) => p.type?.toString().endsWith("OptionalParams"))[0] + ?.name ?? "options" + ); +} + function getOperationSignatureParameters( context: SdkContext, - operation: Operation, + method: [string[], ServiceOperation], clientType: string ): OptionalKind[] { - const optionsType = getOperationOptionsName(operation, true); + const operation = method[1]; + const optionsType = getOperationOptionsName(method, true); const parameters: Map< string, OptionalKind @@ -216,30 +252,31 @@ function getOperationSignatureParameters( operation.parameters .filter( (p) => - p.implementation === "Method" && - p.type.type !== "constant" && + p.onClient === false && + p.type.kind !== "constant" && + operation.operation.parameters.filter((param) => { + return ( + param.correspondingMethodParams.length === 1 && + param.correspondingMethodParams[0] === p + ); + })[0]?.kind !== "cookie" && p.clientDefaultValue === undefined && - !p.optional + !p.optional && + !( + p.isGeneratedName && + (p.name === "contentType" || p.name === "accept") + ) // skip tcgc generated contentType and accept header parameter ) .map((p) => { return { - name: p.clientName, - type: getTypeExpression(context, p.tcgcType ?? p.type.tcgcType!) + name: p.name, + type: getTypeExpression(context, p.type) }; }) .forEach((p) => { parameters.set(p.name, p); }); - if (operation.bodyParameter && operation.bodyParameter.optional === false) { - parameters.set(operation.bodyParameter?.clientName, { - hasQuestionToken: operation.bodyParameter.optional, - ...{ - name: operation.bodyParameter.clientName, - type: getTypeExpression(context, operation.bodyParameter.type.tcgcType!) - } - }); - } // Add context as the first parameter const contextParam = { name: "context", type: clientType }; @@ -260,47 +297,54 @@ function getOperationSignatureParameters( */ export function getOperationFunction( context: SdkContext, - operation: Operation, + method: [string[], ServiceOperation], clientType: string ): OptionalKind & { propertyName?: string } { + const operation = method[1]; + // Extract required parameters + const parameters: OptionalKind[] = + getOperationSignatureParameters(context, method, clientType); + const optionalParamName = getOptionalParamsName(parameters); if (isPagingOnlyOperation(operation)) { // Case 1: paging-only operation - return getPagingOnlyOperationFunction(context, operation, clientType); + return getPagingOnlyOperationFunction( + context, + [method[0], operation], + clientType + ); } else if (isLroOnlyOperation(operation)) { // Case 2: lro-only operation - return getLroOnlyOperationFunction(context, operation, clientType); + return getLroOnlyOperationFunction( + context, + [method[0], operation], + clientType, + optionalParamName + ); } else if (isLroAndPagingOperation(operation)) { // Case 3: both paging + lro operation is not supported yet so handle them as normal operation and customization may be needed // https://github.com/Azure/autorest.typescript/issues/2313 } - if (operation.name === "floatSeconds") { - operation; - } - // Extract required parameters - const parameters: OptionalKind[] = - getOperationSignatureParameters(context, operation, clientType); // TODO: Support operation overloads - const response = operation.responses[0]!; + const response = operation.response; let returnType = { name: "", type: "void" }; - if (response.type?.type) { - const type = - extractPagingType(response.type, operation.itemName) ?? response.type; + if (response.type) { + const type = response.type; returnType = { - name: type.name ?? "", - type: getTypeExpression(context, type.tcgcType!) + name: (type as any).name ?? "", + type: getTypeExpression(context, type!) }; } const { name, fixme = [] } = getOperationName(operation); const functionStatement = { docs: [ - ...getDocsFromDescription(operation.description), + ...getDocsFromDescription(operation.doc), ...getFixmeForMultilineDocs(fixme) ], isAsync: true, isExported: true, name, - propertyName: operation.name, + propertyName: normalizeName(operation.name, NameType.Property), parameters, returnType: `Promise<${returnType.type}>` }; @@ -321,12 +365,14 @@ export function getOperationFunction( function getLroOnlyOperationFunction( context: SdkContext, - operation: Operation, - clientType: string + method: [string[], SdkLroServiceMethod], + clientType: string, + optionalParamName: string = "options" ) { + const operation = method[1]; // Extract required parameters const parameters: OptionalKind[] = - getOperationSignatureParameters(context, operation, clientType); + getOperationSignatureParameters(context, method, clientType); const returnType = buildLroReturnType(context, operation); const { name, fixme = [] } = getOperationName(operation); const pollerLikeReference = resolveReference( @@ -337,13 +383,13 @@ function getLroOnlyOperationFunction( ); const functionStatement = { docs: [ - ...getDocsFromDescription(operation.description), + ...getDocsFromDescription(operation.doc), ...getFixmeForMultilineDocs(fixme) ], isAsync: false, isExported: true, name, - propertyName: operation.name, + propertyName: normalizeName(operation.name, NameType.Property), parameters, returnType: `${pollerLikeReference}<${operationStateReference}<${returnType.type}>, ${returnType.type}>` }; @@ -351,17 +397,29 @@ function getLroOnlyOperationFunction( const getLongRunningPollerReference = resolveReference( PollingHelpers.GetLongRunningPoller ); - const resourceLocationConfig = operation.lroMetadata?.finalStateVia - ? `resourceLocationConfig: "${operation.lroMetadata?.finalStateVia}"` - : ""; + const lroMetadata = + operation.kind === "lro" || operation.kind === "lropaging" + ? operation.lroMetadata + : undefined; + const allowedFinalLocation = [ + "azure-async-operation", + "location", + "original-uri", + "operation-location" + ]; + const resourceLocationConfig = + lroMetadata?.finalStateVia && + allowedFinalLocation.includes(lroMetadata?.finalStateVia) + ? `resourceLocationConfig: "${lroMetadata?.finalStateVia}"` + : ""; const statements: string[] = []; statements.push(` return ${getLongRunningPollerReference}(context, _${name}Deserialize, ${getExpectedStatuses( operation )}, { - updateIntervalInMs: options?.updateIntervalInMs, - abortSignal: options?.abortSignal, + updateIntervalInMs: ${optionalParamName}?.updateIntervalInMs, + abortSignal: ${optionalParamName}?.abortSignal, getInitialResponse: () => _${name}Send(${parameters .map((p) => p.name) .join(", ")}), @@ -377,13 +435,16 @@ function getLroOnlyOperationFunction( }; } -function buildLroReturnType(context: SdkContext, operation: Operation) { +function buildLroReturnType( + context: SdkContext, + operation: SdkLroServiceMethod +) { const metadata = operation.lroMetadata; - if (metadata !== undefined && metadata.finalResult !== undefined) { - const type = metadata.finalResult; + if (metadata !== undefined && metadata.finalResponse !== undefined) { + const type = metadata.finalResponse.result; return { name: type.name, - type: getTypeExpression(context, type.tcgcType!) + type: getTypeExpression(context, type) }; } return { name: "", type: "void" }; @@ -391,22 +452,22 @@ function buildLroReturnType(context: SdkContext, operation: Operation) { function getPagingOnlyOperationFunction( context: SdkContext, - operation: Operation, + method: [string[], SdkPagingServiceMethod], clientType: string ) { + const operation = method[1]; // Extract required parameters const parameters: OptionalKind[] = - getOperationSignatureParameters(context, operation, clientType); + getOperationSignatureParameters(context, method, clientType); // TODO: Support operation overloads - const response = operation.responses[0]!; + const response = operation.response; let returnType = { name: "", type: "void" }; - if (response.type?.type) { - const type = - extractPagingType(response.type, operation.itemName) ?? response.type; + if (response.type && response.type.kind === "array") { + const type = response.type; returnType = { - name: type.name ?? "", - type: getTypeExpression(context, type.tcgcType!) + name: (type.valueType as any).name ?? "", + type: getTypeExpression(context, type.valueType) }; } const { name, fixme = [] } = getOperationName(operation); @@ -418,24 +479,33 @@ function getPagingOnlyOperationFunction( ); const functionStatement = { docs: [ - ...getDocsFromDescription(operation.description), + ...getDocsFromDescription(operation.doc), ...getFixmeForMultilineDocs(fixme) ], isAsync: false, isExported: true, name, - propertyName: operation.name, + propertyName: normalizeName(operation.name, NameType.Property), parameters, returnType: `${pagedAsyncIterableIteratorReference}<${returnType.type}>` }; const statements: string[] = []; const options = []; - if (operation.itemName) { - options.push(`itemName: "${operation.itemName}"`); + // TODO pending tcgc issue to fix https://github.com/Azure/typespec-azure/issues/1985 + const itemName = + operation.response.resultPath !== "" && operation.response.resultPath + ? operation.response.resultPath + : operation.__raw_paged_metadata?.itemsSegments + ? operation.__raw_paged_metadata.itemsSegments[0] + : undefined; + if (itemName) { + options.push(`itemName: "${itemName}"`); } - if (operation.continuationTokenName) { - options.push(`nextLinkName: "${operation.continuationTokenName}"`); + if (operation.__raw_paged_metadata?.nextLinkSegments) { + options.push( + `nextLinkName: "${operation.__raw_paged_metadata.nextLinkSegments[0]}"` + ); } statements.push( `return ${buildPagedAsyncIteratorReference}( @@ -453,31 +523,15 @@ function getPagingOnlyOperationFunction( }; } -function extractPagingType(type: Type, itemName?: string): Type | undefined { - if (!itemName) { - return undefined; - } - const allProperties = [ - ...(type.properties ?? []), - ...(type.parents ?? []).flatMap((p) => p.properties ?? []) - ]; - const prop = allProperties - .filter((prop) => prop.restApiName === itemName) - .map((prop) => prop.type); - if (prop.length === 0) { - return undefined; - } - return prop[0]?.type === "list" && prop[0].elementType - ? prop[0].elementType - : undefined; -} export function getOperationOptionsName( - operation: Operation, + method: [string[], ServiceOperation], includeGroupName = false ) { + const prefixes = method[0]; + const operation = method[1]; const prefix = includeGroupName && operation.name.indexOf("_") === -1 - ? getClassicalLayerPrefix(operation, NameType.Interface) + ? getClassicalLayerPrefix(prefixes, NameType.Interface) : ""; const optionName = `${prefix}${toPascalCase(operation.name)}OptionalParams`; return optionName; @@ -490,20 +544,22 @@ export function getOperationOptionsName( */ function getRequestParameters( dpgContext: SdkContext, - operation: Operation + operation: ServiceOperation, + optionalParamName: string = "options" ): string { - if (!operation.parameters) { + if (!operation.operation.parameters) { return ""; } - const operationParameters = operation.parameters.filter( - (p) => p.implementation !== "Client" && !isContentType(p) + const operationParameters = operation.operation.parameters.filter( + (p) => (!p.onClient || p.isApiVersionParam) && !isContentType(p) ); - const contentTypeParameter = operation.parameters.find(isContentType); + const contentTypeParameter = + operation.operation.parameters.find(isContentType); const parametersImplementation: Record< "header" | "query" | "body", - { paramMap: string; param: Parameter }[] + { paramMap: string; param: SdkServiceParameter }[] > = { header: [], query: [], @@ -511,13 +567,17 @@ function getRequestParameters( }; for (const param of operationParameters) { - if ( - param.location === "header" || - param.location === "query" || - param.location === "body" - ) { - parametersImplementation[param.location].push({ - paramMap: getParameterMap(dpgContext, param), + if (param.kind === "header" || param.kind === "query") { + // skip tcgc generated contentType and accept non constant type header parameter + if ( + param.isGeneratedName && + !isConstant(param.type) && + (param.name === "contentType" || param.name === "accept") + ) { + continue; + } + parametersImplementation[param.kind].push({ + paramMap: getParameterMap(dpgContext, param, optionalParamName), param }); } @@ -526,13 +586,20 @@ function getRequestParameters( let paramStr = ""; if (contentTypeParameter) { - paramStr = `${getContentTypeValue(contentTypeParameter)},`; + paramStr = `${getContentTypeValue(contentTypeParameter, optionalParamName)},`; } if (parametersImplementation.header.length) { paramStr = `${paramStr}\nheaders: {${parametersImplementation.header - .map((i) => buildHeaderParameter(dpgContext.program, i.paramMap, i.param)) - .join(",\n")}},`; + .map((i) => + buildHeaderParameter( + dpgContext.program, + i.paramMap, + i.param, + optionalParamName + ) + ) + .join(",\n")}, ...${optionalParamName}.requestOptions?.headers },`; } if (parametersImplementation.query.length) { @@ -541,14 +608,14 @@ function getRequestParameters( .join(",\n")}},`; } if ( - operation.bodyParameter === undefined && + operation.operation.bodyParam === undefined && parametersImplementation.body.length ) { paramStr = `${paramStr}\nbody: {${parametersImplementation.body .map((i) => i.paramMap) .join(",\n")}}`; - } else if (operation.bodyParameter !== undefined) { - paramStr = `${paramStr}${buildBodyParameter(dpgContext, operation.bodyParameter)}`; + } else if (operation.operation.bodyParam !== undefined) { + paramStr = `${paramStr}${buildBodyParameter(dpgContext, operation.operation.bodyParam)}`; } return paramStr; } @@ -557,8 +624,10 @@ function getRequestParameters( function buildHeaderParameter( program: Program, paramMap: string, - param: Parameter + param: SdkServiceParameter, + optionalParamName: string = "options" ): string { + const paramName = param.name; if (!param.optional && isTypeNullable(param.type) === true) { reportDiagnostic(program, { code: "nullable-required-header", @@ -568,10 +637,10 @@ function buildHeaderParameter( } const conditions = []; if (param.optional) { - conditions.push(`options?.${param.clientName} !== undefined`); + conditions.push(`${optionalParamName}?.${paramName} !== undefined`); } if (isTypeNullable(param.type) === true) { - conditions.push(`options?.${param.clientName} !== null`); + conditions.push(`${optionalParamName}?.${paramName} !== null`); } return conditions.length > 0 ? `...(${conditions.join(" && ")} ? {${paramMap}} : {})` @@ -580,26 +649,30 @@ function buildHeaderParameter( function buildBodyParameter( context: SdkContext, - bodyParameter: BodyParameter | undefined + bodyParameter: SdkBodyParameter | undefined, + optionalParamName: string = "options" ) { - if (!bodyParameter || !bodyParameter.type.tcgcType) { + if (!bodyParameter || !bodyParameter.type) { return ""; } const serializerFunctionName = buildModelSerializer( context, - bodyParameter.type.tcgcType!, + getNullableValidType(bodyParameter.type), false, true ); + const bodyParamName = normalizeName(bodyParameter.name, NameType.Parameter); const bodyNameExpression = bodyParameter.optional - ? `options["${bodyParameter.clientName}"]` - : bodyParameter.clientName; + ? `${optionalParamName}["${bodyParamName}"]` + : bodyParamName; const nullOrUndefinedPrefix = getPropertySerializationPrefix( + context, bodyParameter, - bodyParameter.optional ? "options" : undefined + bodyParameter.optional ? optionalParamName : undefined ); - if (serializerFunctionName) { + // if a model being used in both spread and non spread operation, we should only leverage the deserializer in non spread operation + if (serializerFunctionName && !isSpreadBodyParameter(bodyParameter)) { return `\nbody: ${nullOrUndefinedPrefix}${serializerFunctionName}(${bodyNameExpression}),`; } else if (isAzureCoreErrorType(context.program, bodyParameter.type.__raw)) { return `\nbody: ${nullOrUndefinedPrefix}${bodyNameExpression},`; @@ -609,9 +682,11 @@ function buildBodyParameter( bodyParameter.type, bodyNameExpression, !bodyParameter.optional, - bodyParameter.isBinaryPayload ? "binary" : bodyParameter.format + isBinaryPayload(context, bodyParameter.__raw!, bodyParameter.contentTypes) + ? "binary" + : getEncodeForType(bodyParameter.type) ); - return `\nbody: ${serializedBody === bodyNameExpression ? "" : nullOrUndefinedPrefix}${serializedBody},`; + return `\nbody: ${serializedBody.startsWith(nullOrUndefinedPrefix) ? "" : nullOrUndefinedPrefix}${serializedBody},`; } function getEncodingFormat(type: { format?: string }) { @@ -629,208 +704,210 @@ function getEncodingFormat(type: { format?: string }) { */ export function getParameterMap( context: SdkContext, - param: Parameter | Property + param: SdkServiceParameter, + optionalParamName: string = "options" ): string { - if (isConstant(param)) { - return getConstantValue(param); + if (isConstant(param.type)) { + return `"${param.name}": ${getConstantValue(param.type)}`; } - if (hasCollectionFormatInfo((param as any).location, (param as any).format)) { - return getCollectionFormat(context, param as Parameter); + if (hasCollectionFormatInfo(param.kind, (param as any).collectionFormat)) { + return getCollectionFormat(context, param, optionalParamName); } // if the parameter or property is optional, we don't need to handle the default value if (isOptional(param)) { - return getOptional(context, param); + return getOptional(context, param, optionalParamName); } if (isRequired(param)) { return getRequired(context, param); } - throw new Error(`Parameter ${param.clientName} is not supported`); + throw new Error(`Parameter ${param.name} is not supported`); } -function getCollectionFormat(context: SdkContext, param: Parameter) { - const collectionInfo = getCollectionFormatHelper( - param.location, - param.format ?? "" - ); +function getCollectionFormat( + context: SdkContext, + param: SdkServiceParameter, + optionalParamName: string = "options" +) { + const serializedName = getPropertySerializedName(param); + const format = (param as any).collectionFormat; + const collectionInfo = getCollectionFormatHelper(param.kind, format ?? ""); if (!collectionInfo) { throw "Has collection format info but without helper function detected"; } - const isMulti = (param.format ?? "").toLowerCase() === "multi"; - const additionalParam = isMulti ? `, "${param.restApiName}"` : ""; + const isMulti = format.toLowerCase() === "multi"; + const additionalParam = isMulti ? `, "${serializedName}"` : ""; if (!param.optional) { - return `"${param.restApiName}": ${collectionInfo}(${serializeRequestValue( + return `"${serializedName}": ${collectionInfo}(${serializeRequestValue( context, param.type, - param.clientName, + param.name, true, - param.format + getEncodeForType(param.type) )}${additionalParam})`; } - return `"${param.restApiName}": options?.${ - param.clientName + return `"${serializedName}": ${optionalParamName}?.${ + param.name } !== undefined ? ${collectionInfo}(${serializeRequestValue( context, param.type, - "options?." + param.clientName, + `${optionalParamName}?.${param.name}`, false, - param.format + getEncodeForType(param.type) )}${additionalParam}): undefined`; } -function isContentType(param: Parameter): boolean { +function isContentType(param: SdkServiceParameter): boolean { return ( - param.location === "header" && - param.restApiName.toLowerCase() === "content-type" + param.kind === "header" && + param.serializedName.toLowerCase() === "content-type" ); } -function getContentTypeValue(param: Parameter | Property) { - const defaultValue = - param.clientDefaultValue ?? param.type.clientDefaultValue; - +function getContentTypeValue( + param: SdkServiceParameter, + optionalParamName: string = "options" +) { + const defaultValue = param.clientDefaultValue; + // allow customers to customize the content type if it's guessed by tcgc. + if (isConstant(param.type)) { + return `contentType: ${getConstantValue(param.type)}`; + } if (defaultValue) { - return `contentType: options.${param.clientName} as any ?? "${defaultValue}"`; + return `contentType: ${optionalParamName}.${param.name} as any ?? "${defaultValue}"`; } else { return `contentType: ${ !param.optional ? "contentType" - : "options." + param.clientName + " as any" + : `${optionalParamName}.` + param.name + " as any" }`; } } -type RequiredType = (Parameter | Property) & { - type: { optional: false | undefined; value: string }; -}; - -function isRequired(param: Parameter | Property): param is RequiredType { +function isRequired(param: SdkModelPropertyType) { return !param.optional; } -function getRequired(context: SdkContext, param: RequiredType) { - if (param.type.type === "model") { +function getRequired(context: SdkContext, param: SdkModelPropertyType) { + const serializedName = getPropertySerializedName(param); + const clientValue = `${param.onClient ? "context." : ""}${param.name}`; + if (param.type.kind === "model") { const { propertiesStr } = getRequestModelMapping( context, - param.type, - param.clientName + { ...param.type, optional: param.optional }, + clientValue ); - return `"${param.restApiName}": { ${propertiesStr.join(",")} }`; + return `"${serializedName}": { ${propertiesStr.join(",")} }`; } - return `"${param.restApiName}": ${serializeRequestValue( + return `"${serializedName}": ${serializeRequestValue( context, param.type, - param.clientName, + clientValue, true, - param.format === undefined && - (param as Parameter).location === "header" && - param.type.type === "datetime" - ? "headerDefault" - : param.format + getEncodeForType(param.type) )}`; } -type ConstantType = (Parameter | Property) & { - type: { type: "constant"; value: string }; -}; - -function getConstantValue(param: ConstantType) { - const defaultValue = - param.clientDefaultValue ?? - param.type.clientDefaultValue ?? - param.type.value; - - if (!defaultValue) { - throw new Error( - `Constant ${param.clientName} does not have a default value` - ); +function getConstantValue(param: SdkConstantType) { + if (typeof param.value === "string") { + return `"${param.value}"`; } - - return `"${param.restApiName}": ${getType(param.type).name}`; + return `${param.value}`; } -function isConstant(param: Parameter | Property): param is ConstantType { - return param.type.type === "constant"; +function isConstant(param: SdkType): param is SdkConstantType { + return param.kind === "constant"; } -type OptionalType = (Parameter | Property) & { - type: { optional: true }; -}; - -function isOptional(param: Parameter | Property): param is OptionalType { +function isOptional(param: SdkModelPropertyType) { return Boolean(param.optional); } -function getOptional(context: SdkContext, param: OptionalType) { - if (param.type.type === "model") { +function getOptional( + context: SdkContext, + param: SdkHttpParameter, + optionalParamName: string +) { + const serializedName = getPropertySerializedName(param); + const paramName = `${param.onClient ? "context." : `${optionalParamName}?.`}${param.name}`; + if (param.type.kind === "model") { const { propertiesStr, directAssignment } = getRequestModelMapping( context, - param.type, - "options?." + param.clientName + "?." + { ...param.type, optional: param.optional }, + paramName + "?." ); const serializeContent = directAssignment === true ? propertiesStr.join(",") : `{${propertiesStr.join(",")}}`; - return `"${param.restApiName}": ${serializeContent}`; + return `"${serializedName}": ${serializeContent}`; } - if ( - param.restApiName === "api-version" && - (param as any).location === "query" - ) { - return `"${param.restApiName}": ${ - param.clientDefaultValue - ? `options?.${param.clientName} ?? "${param.clientDefaultValue}"` - : `options?.${param.clientName}` - }`; - } - return `"${param.restApiName}": ${serializeRequestValue( + return `"${serializedName}": ${serializeRequestValue( context, param.type, - `options?.${param.clientName}`, + paramName, false, - param.format === undefined && - (param as Parameter).location === "header" && - param.type.type === "datetime" - ? "headerDefault" - : param.format + getEncodeForType(param.type) )}`; } +/** + * Get the encode for SDK type + */ +function getEncodeForType( + type: SdkType | SdkHttpParameter | SdkModelPropertyType +) { + return (type as any).encode; +} + +/** + * Get the optionality for SDK type + */ +function getOptionalForType( + type: SdkType | SdkHttpParameter | SdkModelPropertyType +) { + return (type as any).optional; +} + /** * Builds the assignment for when a property or parameter has a default value */ -function getDefaultValue(param: Parameter | Property) { - return param.clientDefaultValue ?? param.type.clientDefaultValue; +function getDefaultValue(param: SdkServiceParameter) { + return param.clientDefaultValue; } /** * Extracts the path parameters */ -function getPathParameters(dpgContext: SdkContext, operation: Operation) { - if (!operation.parameters) { +function getPathParameters( + dpgContext: SdkContext, + operation: ServiceOperation, + optionalParamName: string = "options" +) { + if (!operation.operation.parameters) { return ""; } let pathParams = ""; - for (const param of operation.parameters) { - if (param.location === "path") { + for (const param of operation.operation.parameters) { + if (param.kind === "path") { // Path parameters cannot be optional if (param.optional) { reportDiagnostic(dpgContext.program, { code: "optional-path-param", target: NoTarget, format: { - paramName: param.clientName + paramName: param } }); } pathParams += `${pathParams !== "" ? "," : ""} ${getPathParamExpr( param, - getDefaultValue(param) + getDefaultValue(param) as string, + optionalParamName )}`; } } @@ -838,19 +915,32 @@ function getPathParameters(dpgContext: SdkContext, operation: Operation) { return pathParams; } -function getPathParamExpr(param: Parameter, defaultValue?: string) { +function getPathParamExpr( + param: SdkServiceParameter, + defaultValue?: string, + optionalParamName: string = "options" +) { + if (isConstant(param.type)) { + return getConstantValue(param.type); + } + const paramName = param.onClient + ? `context.${param.name}` + : param.optional + ? `${optionalParamName}["${param.name}"]` + : param.name; const value = defaultValue ? typeof defaultValue === "string" - ? `options[${param.clientName}] ?? "${defaultValue}"` - : `options[${param.clientName}] ?? ${defaultValue}` - : param.clientName; - if (param.skipUrlEncoding === true) { + ? `${paramName} ?? "${defaultValue}"` + : `${paramName} ?? ${defaultValue}` + : paramName; + // TODO allowReserved is not supported in Query and Header parameter yet. + if (param.kind === "path" && param.allowReserved === true) { return `{value: ${value}, allowReserved: true}`; } return value; } -function getNullableCheck(name: string, type: Type) { +function getNullableCheck(name: string, type: SdkType) { if (!isTypeNullable(type)) { return ""; } @@ -869,42 +959,47 @@ interface RequestModelMappingResult { } export function getRequestModelMapping( context: SdkContext, - modelPropertyType: Type, + modelPropertyType: SdkModelType & { optional?: boolean }, propertyPath: string = "body" ): RequestModelMappingResult { const props: string[] = []; const allParents = getAllAncestors(modelPropertyType); - const properties: Property[] = + const properties: SdkModelPropertyType[] = getAllProperties(modelPropertyType, allParents) ?? []; if (properties.length <= 0) { return { propertiesStr: [] }; } for (const property of properties) { - if (property.readonly) { + if (property.kind === "property" && isReadOnly(property)) { continue; } const dot = propertyPath.endsWith("?") ? "." : ""; - + const serializedName = getPropertySerializedName(property); const propertyPathWithDot = `${propertyPath ? `${propertyPath}${dot}` : `${dot}`}`; const nullOrUndefinedPrefix = getPropertySerializationPrefix( + context, property, propertyPath ); - const propertyFullName = getPropertyFullName(property, propertyPathWithDot); + const propertyFullName = getPropertyFullName( + context, + property, + propertyPathWithDot + ); const serializeFunctionName = buildModelSerializer( context, - property.type.tcgcType!, + getNullableValidType(property.type), false, true ); if (serializeFunctionName) { props.push( - `"${property.restApiName}": ${nullOrUndefinedPrefix}${serializeFunctionName}(${propertyFullName})` + `"${serializedName}": ${nullOrUndefinedPrefix}${serializeFunctionName}(${propertyFullName})` ); } else if (isAzureCoreErrorType(context.program, property.type.__raw)) { props.push( - `"${property.restApiName}": ${nullOrUndefinedPrefix}${propertyFullName}` + `"${serializedName}": ${nullOrUndefinedPrefix}${propertyFullName}` ); } else { const serializedValue = serializeRequestValue( @@ -912,60 +1007,67 @@ export function getRequestModelMapping( property.type, propertyFullName, !property.optional, - property.format + getEncodeForType(property.type) ); - props.push(`"${property.restApiName}": ${serializedValue}`); + props.push(`"${serializedName}": ${serializedValue}`); } } return { propertiesStr: props }; } +function getPropertySerializedName(property: SdkModelPropertyType) { + return property.kind !== "credential" && property.kind !== "method" + ? property.serializedName + : property.name; +} + /** * This function helps translating an RLC response to an HLC response, * extracting properties from body and headers and building the HLC response object */ export function getResponseMapping( context: SdkContext, - type: Type, + type: SdkType, propertyPath: string = "result.body" ) { - const allParents = getAllAncestors(type); - const properties = getAllProperties(type, allParents) ?? []; + const allParents = type.kind === "model" ? getAllAncestors(type) : []; + const properties = + type.kind === "model" ? getAllProperties(type, allParents) : []; const props: string[] = []; for (const property of properties) { const dot = propertyPath.endsWith("?") ? "." : ""; - + const serializedName = getPropertySerializedName(property); const restValue = `${ propertyPath ? `${propertyPath}${dot}` : `${dot}` - }["${property.restApiName}"]`; + }["${serializedName}"]`; + const nullOrUndefinedPrefix = property.optional || isTypeNullable(property.type) ? `!${restValue}? ${restValue}: ` : ""; const deserializeFunctionName = buildModelDeserializer( context, - property.type.tcgcType!, + getNullableValidType(property.type), false, true ); + const propertyName = normalizeModelPropertyName(context, property); if (deserializeFunctionName) { props.push( - `"${property.clientName}": ${nullOrUndefinedPrefix}${deserializeFunctionName}(${restValue})` + `${propertyName}: ${nullOrUndefinedPrefix}${deserializeFunctionName}(${restValue})` ); } else if (isAzureCoreErrorType(context.program, property.type.__raw)) { - props.push( - `"${property.clientName}": ${nullOrUndefinedPrefix}${restValue}` - ); + props.push(`${propertyName}: ${nullOrUndefinedPrefix}${restValue}`); } else { const deserializeValue = deserializeResponseValue( context, property.type, - `${propertyPath}${dot}["${property.restApiName}"]`, - property.format + `${propertyPath}${dot}["${serializedName}"]`, + getEncodeForType(property.type) ); props.push( - `"${property.clientName}": ${deserializeValue === `${propertyPath}${dot}["${property.restApiName}"]` ? "" : nullOrUndefinedPrefix}${deserializeValue}` + `${propertyName}: ${deserializeValue === `${propertyPath}${dot}["${serializedName}"]` ? "" : nullOrUndefinedPrefix}${deserializeValue}` ); } } @@ -979,7 +1081,7 @@ export function getResponseMapping( */ export function serializeRequestValue( context: SdkContext, - type: Type, + type: SdkType, clientValue: string, required: boolean, format?: string @@ -987,50 +1089,48 @@ export function serializeRequestValue( const getSdkType = useSdkTypes(); const dependencies = useDependencies(); const nullOrUndefinedPrefix = - isTypeNullable(type) || type.optional || !required + isTypeNullable(type) || getOptionalForType(type) || !required ? `!${clientValue}? ${clientValue}: ` : ""; - switch (type.type) { - case "datetime": - switch (type.format ?? format) { + switch (type.kind) { + case "utcDateTime": + switch (type.encode ?? format) { case "rfc7231": - case "headerDefault": return `${nullOrUndefinedPrefix}${clientValue}.toUTCString()`; case "unixTimestamp": return `${nullOrUndefinedPrefix}((${clientValue}.getTime() / 1000) | 0)`; case "rfc3339": default: - return `${getNullableCheck(clientValue, type)} ${clientValue}${ - required ? "" : "?" - }.toISOString()`; + return `${nullOrUndefinedPrefix}${clientValue}.toISOString()`; } - case "list": { + case "array": { const prefix = nullOrUndefinedPrefix + clientValue; - if (type.elementType) { + if (type.valueType) { const elementNullOrUndefinedPrefix = - isTypeNullable(type.elementType) || type.elementType.optional + isTypeNullable(type.valueType) || getOptionalForType(type.valueType) ? "!p ? p : " : ""; const serializeFunctionName = buildModelSerializer( context, - type.elementType.tcgcType!, + getNullableValidType(type.valueType), false, true ); if (serializeFunctionName) { return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${serializeFunctionName}(p)})`; } else if ( - isAzureCoreErrorType(context.program, type.elementType.__raw) + isAzureCoreErrorType(context.program, type.valueType.__raw) ) { return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}p})`; } else { - return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${serializeRequestValue(context, type.elementType, "p", true, type.elementType?.format)}})`; + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${serializeRequestValue(context, type.valueType, "p", true, getEncodeForType(type.valueType))}})`; } } return clientValue; } - case "byte-array": - if (format !== "binary") { + case "bytes": + // TODO https://github.com/Azure/typespec-azure/issues/1999 + if (format !== "binary" && format !== "bytes") { const uint8ArrayToStringReference = resolveReference( dependencies.uint8ArrayToString ); @@ -1046,10 +1146,16 @@ export function serializeRequestValue( }")`; } return clientValue; - case "combined": + case "union": if (isNormalUnion(type)) { return `${clientValue}`; - } else if (isSpecialHandledUnion(type)) { + } else if ( + isSpecialHandledUnion({ + ...type, + isNonExhaustive: + context.rlcOptions?.experimentalExtensibleEnums ?? false + }) + ) { const sdkType = getSdkType(type.__raw!); const serializerRefkey = refkey(sdkType, "serializer"); const serializeFunctionName = resolveReference(serializerRefkey); @@ -1057,6 +1163,16 @@ export function serializeRequestValue( } else { return `${clientValue} as any`; } + case "model": // this is to build serialization logic for spread model types + return `{${getRequestModelMapping(context, type, "").propertiesStr.join(",")}}`; + case "nullable": + return serializeRequestValue( + context, + type.type, + clientValue, + false, + getEncodeForType(type.type) + ); default: if (clientValue === "constructorParam") { return `${clientValue} as any`; @@ -1072,7 +1188,7 @@ export function serializeRequestValue( */ export function deserializeResponseValue( context: SdkContext, - type: Type, + type: SdkType, restValue: string, format?: string ): string { @@ -1081,25 +1197,25 @@ export function deserializeResponseValue( dependencies.stringToUint8Array ); const nullOrUndefinedPrefix = - isTypeNullable(type) || type.optional + isTypeNullable(type) || getOptionalForType(type) ? `!${restValue}? ${restValue}: ` : ""; - switch (type.type) { - case "datetime": - return `${nullOrUndefinedPrefix} new Date(${type.format === "unixTimestamp" ? `${restValue} * 1000` : restValue})`; - case "list": { + switch (type.kind) { + case "utcDateTime": + return `${nullOrUndefinedPrefix} new Date(${type.encode === "unixTimestamp" ? `${restValue} * 1000` : restValue})`; + case "array": { const prefix = nullOrUndefinedPrefix + restValue; let elementNullOrUndefinedPrefix = ""; if ( - type.elementType && - (isTypeNullable(type.elementType) || type.elementType.optional) + type.valueType && + (isTypeNullable(type.valueType) || getOptionalForType(type.valueType)) ) { elementNullOrUndefinedPrefix = "!p ? p :"; } - const deserializeFunctionName = type.elementType + const deserializeFunctionName = type.valueType ? buildModelDeserializer( context, - type.elementType.tcgcType!, + getNullableValidType(type.valueType), false, true ) @@ -1107,29 +1223,34 @@ export function deserializeResponseValue( if (deserializeFunctionName) { return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${deserializeFunctionName}(p)})`; } else if ( - type.elementType && - isAzureCoreErrorType(context.program, type.elementType.__raw) + type.valueType && + isAzureCoreErrorType(context.program, type.valueType.__raw) ) { return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}p})`; - } else if (type.elementType) { - return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${deserializeResponseValue(context, type.elementType, "p", type.format)}})`; + } else if (type.valueType) { + return `${prefix}.map((p: any) => { return ${elementNullOrUndefinedPrefix}${deserializeResponseValue(context, type.valueType, "p", getEncodeForType(type.valueType))}})`; } else { return restValue; } } - case "byte-array": - if (format !== "binary") { + case "bytes": + if (format !== "binary" && format !== "bytes") { return `typeof ${restValue} === 'string' ? ${stringToUint8ArrayReference}(${restValue}, "${format ?? "base64"}") : ${restValue}`; } return restValue; - case "combined": + case "union": if (isNormalUnion(type)) { return `${restValue}`; } else if (isSpecialHandledUnion(type)) { const deserializeFunctionName = type - ? buildModelDeserializer(context, type.tcgcType!, false, true) + ? buildModelDeserializer( + context, + getNullableValidType(type), + false, + true + ) : undefined; if (deserializeFunctionName) { return `${deserializeFunctionName}(${restValue})`; @@ -1139,94 +1260,97 @@ export function deserializeResponseValue( } else { return `${restValue} as any`; } + case "model": // generate deserialize logic for spread model types + return `{${getResponseMapping(context, type, "").join(",")}}`; + case "nullable": + return deserializeResponseValue( + context, + type.type, + restValue, + getEncodeForType(type.type) + ); default: return restValue; } } -export function isLroAndPagingOperation(op: Operation): boolean { - return op.discriminator === "lropaging"; -} - -export function isLroOnlyOperation(op: Operation): boolean { - return op.discriminator === "lro"; +export function isLroAndPagingOperation( + op: SdkMethod +): op is SdkLroPagingServiceMethod { + return op.kind === "lropaging"; } -export function hasPagingOnlyOperation( - client: Client, - needRLC?: boolean -): boolean; -export function hasPagingOnlyOperation( - codeModel: ModularCodeModel, - needRLC?: boolean -): boolean; -export function hasPagingOnlyOperation( - clientOrCodeModel: Client | ModularCodeModel, - needRLC: boolean = false -): boolean { - let clients: Client[] = []; - if ((clientOrCodeModel as any)?.operationGroups) { - clients = [clientOrCodeModel as Client]; - } else if ((clientOrCodeModel as any)?.clients) { - clients = (clientOrCodeModel as ModularCodeModel).clients; - } - return clients.some( - (c) => - (needRLC ? c.rlcHelperDetails.hasPaging : false) || - (c.operationGroups ?? []).some((og) => - (og.operations ?? []).some(isPagingOnlyOperation) - ) - ); +export function isLroOnlyOperation( + op: SdkMethod +): op is SdkLroServiceMethod { + return op.kind === "lro"; } -export function isPagingOnlyOperation(op: Operation): boolean { - return op.discriminator === "paging"; +export function isPagingOnlyOperation( + op: SdkMethod +): op is SdkPagingServiceMethod { + return op.kind === "paging"; } -export function getAllProperties(type: Type, parents?: Type[]): Property[] { - const propertiesMap: Map = new Map(); +export function getAllProperties( + type: SdkType, + parents?: SdkType[] +): SdkModelPropertyType[] { + const propertiesMap: Map = new Map(); if (!type) { return []; } parents?.forEach((p) => { getAllProperties(p).forEach((prop) => { - propertiesMap.set(prop.clientName, prop); + propertiesMap.set(prop.name, prop); }); }); - type.properties?.forEach((p) => { - propertiesMap.set(p.clientName, p); - }); + type.kind === "model" && + type.properties + ?.filter((p) => { + return p.kind === "property"; + }) + .forEach((p) => { + propertiesMap.set(p.name, p); + }); return [...propertiesMap.values()]; } -export function getAllAncestors(type: Type): Type[] { - const ancestors: Type[] = []; - type?.parents?.forEach((p) => { - ancestors.push(p); - ancestors.push(...getAllAncestors(p)); - }); +export function getAllAncestors(type: SdkType): SdkType[] { + const ancestors: SdkType[] = []; + if (type.kind === "model" && type.baseModel) { + ancestors.push(type.baseModel); + ancestors.push(...getAllAncestors(type.baseModel)); + } return ancestors; } export function getPropertySerializationPrefix( - modularType: Property | Parameter, + context: SdkContext, + property: SdkServiceParameter | SdkModelPropertyType, propertyPath?: string ) { - const propertyFullName = getPropertyFullName(modularType, propertyPath); - if (modularType.optional || isTypeNullable(modularType.type)) { - return `!${propertyFullName} ? ${propertyFullName} :`; + const propertyFullName = getPropertyFullName(context, property, propertyPath); + if (property.optional || isTypeNullable(property.type)) { + return `!${propertyFullName}? ${propertyFullName}:`; } return ""; } export function getPropertyFullName( - modularType: Property | Parameter, + context: SdkContext, + property: SdkServiceParameter | SdkModelPropertyType, propertyPath?: string ) { - let fullName = `${modularType.clientName}`; - if (propertyPath) { - fullName = `${propertyPath}["${modularType.clientName}"]`; + const normalizedPropertyName = normalizeModelPropertyName(context, property) + .replace(/^"/g, "") + .replace(/"$/g, ""); + let fullName = normalizedPropertyName; + if (propertyPath === "" && property.optional) { + fullName = `options?.${normalizedPropertyName}`; + } else if (propertyPath) { + fullName = `${propertyPath}["${normalizedPropertyName}"]`; } return fullName; } @@ -1235,14 +1359,12 @@ export function getPropertyFullName( * Get an expression representing an array of expected status codes for the operation * @param operation The operation */ -export function getExpectedStatuses(operation: Operation): string { - const statusCodes = operation.responses.flatMap((x) => - x.statusCodes.filter((s) => s !== "default") - ); +export function getExpectedStatuses(operation: ServiceOperation): string { + const statusCodes = operation.operation.responses.map((x) => x.statusCodes); // LROs may call the same path but with GET to get the operation status. if ( isLroOnlyOperation(operation) && - operation.method !== "GET" && + operation.operation.verb !== "get" && !statusCodes.includes(200) ) { statusCodes.push(200); diff --git a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts index 7084b411e2..1c4ff7571d 100644 --- a/packages/typespec-ts/src/modular/helpers/typeHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/typeHelpers.ts @@ -1,272 +1,18 @@ import { SdkBodyParameter, + SdkModelPropertyType, SdkType } from "@azure-tools/typespec-client-generator-core"; -import { Type } from "../modularCodeModel.js"; -/** - * Represents metadata for a given Type to generate the TypeScript equivalent. - */ -export interface TypeMetadata { - name: string; - originModule?: string; - isRelative?: boolean; - nullable?: boolean; - modifier?: "Array"; -} - -// Mapping of simple types to their TypeScript equivalents. -const simpleTypeMap: Record = { - Key: { - name: "KeyCredential" - }, - OAuth2: { - name: "TokenCredential" - }, - boolean: { name: "boolean" }, - datetime: { name: "Date" }, - float: { name: "number" }, - integer: { name: "number" }, - "byte-array": { name: "Uint8Array" }, - string: { name: "string" }, - any: { name: "Record" }, - unknown: { name: "any" } -}; - -function handleAnomymousModelName(type: Type) { - let retVal = `{`; - for (const prop of type.properties ?? []) { - const propName = prop.clientName ?? prop.restApiName ?? ""; - const propTypeName = getType(prop.type, prop.type.format).name; - if (!propName || !propTypeName) { - continue; - } - retVal += `"${propName}"${prop.optional ? "?" : ""}: ${propTypeName};`; - } - - retVal += `}`; - return retVal; -} - -function handleNullableTypeName(type: { - name?: string; - nullable?: boolean; -}): string { - if (!type.name) { - throw new Error("Unable to process type without name"); - } - let name = type.name; - - if (type.nullable) { - name = `(${name} | null)`; - } - - return name; -} - -/** - * Maps a given Type to its TypeScript representation metadata. - */ -export function getType(type: Type, format?: string): TypeMetadata { - // Handle simple type conversions - const simpleType = simpleTypeMap[type.type]; - if (simpleType) { - const typeMetadata: TypeMetadata = { ...simpleType }; - if (isTypeNullable(type)) { - typeMetadata.nullable = true; - typeMetadata.name = handleNullableTypeName(typeMetadata); - } - return typeMetadata; - } - - switch (type.type) { - case "constant": - return handleConstantType(type); - - case "enum": - return handleEnumType(type); - - case "list": - return handleListType(type); - - case "model": - return handleModelType(type); - - case "duration": - return handleDurationType(type, format); - - case "combined": - return handleCombinedType(type); - - case "dict": - return handleDictType(type); - - case "never": - return { name: "never", nullable: isTypeNullable(type) }; - default: - throw new Error(`Unsupported type ${type.type}`); - } -} - -/** - * Handles the conversion of constant types to TypeScript representation metadata. - */ -function handleConstantType(type: Type): TypeMetadata { - let typeName: string = type.value?.toString() ?? "undefined"; - if (type.valueType?.type === "string") { - typeName = type.value ? `"${type.value}"` : "undefined"; - } - const name = handleNullableTypeName({ - name: typeName, - nullable: isTypeNullable(type) - }); - return { name, nullable: isTypeNullable(type) }; -} - -/** - * Handles the conversion of enum types to TypeScript representation metadata. - */ -function handleEnumType(type: Type): TypeMetadata { - if (!type.name) { - const valueType = !type.isFixed - ? ((type.values?.[0] as Type).valueType?.type ?? "string") + " | " - : ""; - return { - name: `${valueType}${type.values - ?.map((e) => { - return getType(e as Type).name; - }) - .join(" | ")}`, - nullable: isTypeNullable(type) - }; - } - const name = handleNullableTypeName({ - name: type.name, - nullable: isTypeNullable(type) - }); - return { - name, - nullable: isTypeNullable(type), - originModule: "models.js" - }; +export function isTypeNullable(type: SdkType) { + return Boolean(type.kind === "nullable"); } -export function isTypeNullable(type: Type) { - return Boolean(type.tcgcType?.kind === "nullable"); -} - -/** - * Handles the conversion of list types to TypeScript representation metadata. - */ -function handleListType(type: Type): TypeMetadata { - if (!type.elementType) { - throw new Error("Unable to process Array with no elementType"); - } - - const elementTypeMetadata = getType( - type.elementType, - type.elementType.format - ); - - let name = `${elementTypeMetadata.name}[]`; - - const isTypeNullable = type.tcgcType?.kind === "nullable"; - - if (isTypeNullable) { - name = `(${name} | null)`; - } - - const listTypeMetadata: TypeMetadata = { - name: name, - nullable: isTypeNullable, - originModule: type.elementType?.type === "model" ? "models.js" : undefined - }; - - return listTypeMetadata; -} - -/** - * Handles the conversion of model types to TypeScript representation metadata. - */ -function handleModelType(type: Type): TypeMetadata { - let name = !type.name ? handleAnomymousModelName(type) : type.name; - name = handleNullableTypeName({ - name, - nullable: isTypeNullable(type) - }); - return { - name, - nullable: isTypeNullable(type), - originModule: "models.js" - }; -} - -/** - * Handles the conversion of duration types to TypeScript representation metadata. - */ -function handleDurationType(type: Type, format?: string): TypeMetadata { - const isFormatSeconds = format === "seconds"; - let name = isFormatSeconds ? "number" : "string"; - name = handleNullableTypeName({ name, nullable: isTypeNullable(type) }); - return { - name, - nullable: isTypeNullable(type) - }; -} - -/** - * Handles the conversion of combined types to TypeScript representation metadata. - */ -function handleCombinedType(type: Type): TypeMetadata { - if (!type.types) { - throw new Error("Unable to process combined without combinedTypes"); - } - const name = - type.name ?? - type.types - .map((t) => { - const sdkType = getType(t, t.format).name; - return `${sdkType}`; - }) - .join(" | "); - return { name: `(${name})`, nullable: isTypeNullable(type) }; -} - -/** - * Handles the conversion of dict types to TypeScript representation metadata. - */ -function handleDictType(type: Type): TypeMetadata { - if (!type.elementType) { - throw new Error("Unable to process dict without elemetType info"); +export function getNullableValidType(type: SdkType): SdkType { + if (type.kind === "nullable") { + return type.type; } - if (type.name && type.name !== "Record") { - return { - name: type.name - }; - } - const elementType = getType(type.elementType, type.elementType.format); - const elementName = elementType.name; - const name = handleNullableTypeName({ - name: `Record`, - nullable: isTypeNullable(type) - }); - return { - name, - nullable: isTypeNullable(type) - }; -} - -/** - * Generates a TypeScript type representation for a given client name, type, and format. - */ -export function buildType(clientName?: string, type?: Type, format?: string) { - if (!type) { - throw new Error("Type should be defined"); - } - - const typeMetadata = getType(type, format); - - return { name: clientName ?? "", type: typeMetadata.name }; + return type; } const NumericTypeKinds = [ @@ -299,12 +45,10 @@ export function isDateTimeTypeKind(kind: string): boolean { return DateTimeTypeKinds.includes(kind); } -export function isCredentialType(type: Type): boolean { - const credentialTypes = ["OAuth2", "Key"]; - return ( - credentialTypes.includes(type.type) || - (type.type === "combined" && (type.types?.every(isCredentialType) ?? false)) - ); +export function isCredentialType( + type: SdkType | SdkModelPropertyType +): boolean { + return type.kind === "credential"; } /** diff --git a/packages/typespec-ts/src/modular/interfaces.ts b/packages/typespec-ts/src/modular/interfaces.ts index 583eafd74c..c863e8678c 100644 --- a/packages/typespec-ts/src/modular/interfaces.ts +++ b/packages/typespec-ts/src/modular/interfaces.ts @@ -1,12 +1,20 @@ -import { OptionalKind, ParameterDeclarationStructure } from "ts-morph"; -import { Parameter } from "./modularCodeModel.js"; +import { RLCOptions } from "@azure-tools/rlc-common"; +import { Project } from "ts-morph"; -export interface ClientDetails { - name: string; - params?: OptionalKind[]; - description: string; - baseUrl?: string; - credentialsParam?: Parameter; +export interface ModularOptions { + sourceRoot: string; + compatibilityMode: boolean; + experimentalExtensibleEnums: boolean; +} +export interface ModularEmitterOptions { + options: RLCOptions; + modularOptions: ModularOptions; + project: Project; +} + +export interface ModularClientOptions { + subfolder?: string; + rlcClientName: string; } export interface OperationPathAndDeserDetails { diff --git a/packages/typespec-ts/src/modular/modularCodeModel.ts b/packages/typespec-ts/src/modular/modularCodeModel.ts deleted file mode 100644 index d06653dbc9..0000000000 --- a/packages/typespec-ts/src/modular/modularCodeModel.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { - HelperFunctionDetails, - Imports, - OperationResponse, - RLCOptions -} from "@azure-tools/rlc-common"; -import { - SdkBodyParameter, - SdkClientType, - SdkHttpOperation, - SdkType -} from "@azure-tools/typespec-client-generator-core"; -import { UsageFlags, Type as TypespecType } from "@typespec/compiler"; -import { Project } from "ts-morph"; - -export interface ModularOptions { - sourceRoot: string; - compatibilityMode: boolean; - experimentalExtensibleEnums: boolean; -} -export interface ModularCodeModel { - options: RLCOptions; - modularOptions: ModularOptions; - namespace?: string; - subnamespaceToClients?: any; - clients: Client[]; - types: Type[]; - project: Project; - runtimeImports: Imports; -} - -export interface Header { - type: Type; - restApiName: string; -} - -export interface Property { - clientDefaultValue?: any; - clientName: string; - restApiName: string; - type: Type; - optional?: boolean; - description: string; - readonly?: boolean; - format?: string; -} - -export interface BodyParameter { - contentTypes: string[]; - type: Type; - restApiName: string; - location: "body"; - optional: boolean; - format?: string; - description: string; - clientName: string; - inOverload: boolean; - isBinaryPayload: boolean; - tcgcType: SdkBodyParameter; -} - -export interface OperationGroup { - className: string; - propertyName: string; - operations: Operation[]; - namespaceHierarchies: string[]; -} -export interface Policy { - type: string; - key: string; -} - -export interface XmlMetadata {} -export interface EnumValue { - name: string; - value: string; - description: string; -} -export interface Type { - name?: string; - description?: string; - type: - | "string" - | "Key" - | "OAuth2" - | "constant" - | "model" - | "list" - | "byte-array" - | "datetime" - | "float" - | "duration" - | "enum" - | "integer" - | "float" - | "boolean" - | "dict" - | "combined" - | "any" - | "unknown" - | "never"; - policy?: Policy; - apiVersions?: any[]; - clientDefaultValue?: any; - value?: string; - values?: EnumValue[]; - isFixed?: boolean; - isNonExhaustive?: boolean; - valueType?: Type; - elementType?: Type; - parents?: Type[]; - xmlMetadata?: XmlMetadata; - format?: string; - properties?: Property[]; - types?: Type[]; - coreTypeInfo?: "ErrorType" | "LroType"; - usage?: UsageFlags; - alias?: string; - aliasType?: string; - discriminator?: string; - discriminatorValue?: string; - isPolymorphicBaseModel?: boolean; - tcgcType?: SdkType; - __raw?: TypespecType; - nullable?: boolean; - optional?: boolean; -} - -export interface Client { - name: string; - description: string; - parameters: Parameter[]; - operationGroups: OperationGroup[]; - url: string; - apiVersions: any[]; - rlcClientName: string; - subfolder?: string; - rlcHelperDetails: HelperFunctionDetails; - tcgcClient: SdkClientType; -} - -export type ParameterLocation = - | "endpointPath" - | "header" - | "query" - | "path" - | "body" - | "other"; - -export interface Parameter { - optional: boolean; - description: string; - clientName: string; - inOverload: boolean; - restApiName: string; - location: ParameterLocation; - type: Type; - implementation: string; - skipUrlEncoding?: boolean; - clientDefaultValue?: string | null; - in_docstring?: boolean; - checkClientInput?: boolean; - delimiter?: any; - explode?: boolean; - groupedBy?: any; - inDocstring?: boolean; - inOverriden?: boolean; - isApiVersion?: boolean; - format?: string; - tcgcType?: SdkType; -} - -export interface Response { - headers: Header[]; - statusCodes: (number | "default")[]; - discriminator: string; - type: Type; - addedOn?: string; - isBinaryPayload?: boolean; -} - -export interface Operation { - name: string; - oriName?: string; - description: string; - summary: string; - url: string; - method: string; - parameters: Parameter[]; - bodyParameter?: BodyParameter; - responses: Response[]; - exceptions: Response[]; - groupName: string; - discriminator: string; - isOverload: boolean; - overloads: any[]; - apiVersions: any[]; - itemName?: string; - continuationTokenName?: string; - addedOn?: string; - rlcResponse?: OperationResponse; - namespaceHierarchies: string[]; - lroMetadata?: LroOperationMetadata; -} - -export interface LroOperationMetadata { - finalStateVia?: string; - finalResult?: Type; - /** The path to the field in the 'finalEnvelopeResult' that contains the 'finalResult'. */ - finalResultPath?: string; -} diff --git a/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts b/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts index 6d81adf2ae..14d507b777 100644 --- a/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts +++ b/packages/typespec-ts/src/modular/serialization/buildDeserializerFunction.ts @@ -11,7 +11,6 @@ import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; import { SdkContext } from "../../utils/interfaces.js"; import { getResponseMapping } from "../helpers/operationHelpers.js"; -import { getType } from "../buildCodeModel.js"; import { normalizeModelName } from "../emitModels.js"; import { NameType } from "@azure-tools/rlc-common"; import { isAzureCoreErrorType } from "../../utils/modelUtils.js"; @@ -344,11 +343,7 @@ function buildModelTypeDeserializer( ? "...item," : ""; - const propertiesStr = getResponseMapping( - context, - getType(context, type.__raw!), - "item" - ); + const propertiesStr = getResponseMapping(context, type, "item"); const propertiesDeserialization = propertiesStr.filter((p) => p.trim()); const output = []; diff --git a/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts b/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts index dbb559d4e8..6d4f5a6dd8 100644 --- a/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts +++ b/packages/typespec-ts/src/modular/serialization/buildSerializerFunction.ts @@ -11,7 +11,6 @@ import { toCamelCase, toPascalCase } from "../../utils/casingUtils.js"; import { SdkContext } from "../../utils/interfaces.js"; import { getRequestModelMapping } from "../helpers/operationHelpers.js"; -import { getType } from "../buildCodeModel.js"; import { normalizeModelName } from "../emitModels.js"; import { NameType } from "@azure-tools/rlc-common"; import { isAzureCoreErrorType } from "../../utils/modelUtils.js"; @@ -339,7 +338,7 @@ function buildModelTypeSerializer( const { directAssignment, propertiesStr } = getRequestModelMapping( context, - getType(context, type.__raw!), + type, "item" ); if (additionalPropertiesSpread) { diff --git a/packages/typespec-ts/src/modular/serialization/serializeUtils.ts b/packages/typespec-ts/src/modular/serialization/serializeUtils.ts index e8fbc773bd..d1fd7435ff 100644 --- a/packages/typespec-ts/src/modular/serialization/serializeUtils.ts +++ b/packages/typespec-ts/src/modular/serialization/serializeUtils.ts @@ -1,4 +1,3 @@ -import { Type } from "../modularCodeModel.js"; import { getAllAncestors } from "../helpers/operationHelpers.js"; import { SdkModelType, @@ -26,10 +25,10 @@ export function isSupportedSerializeType(type: SdkType): boolean { * 6. nested model i.e. model with property that is a model with one of the above three conditions. * If we consider array type, with all the above 6 types as the element types. */ -const specialVariantMap = new Map(); +const specialVariantMap = new Map(); export function isSpecialUnionVariant( - t: Type, - variantStack: Type[] = [] + t: SdkType & { isNonExhaustive?: boolean }, + variantStack: SdkType[] = [] ): boolean { if (variantStack.length <= 0) { variantStack.push(t); @@ -41,40 +40,40 @@ export function isSpecialUnionVariant( } if ( - t.type === "datetime" || - t.type === "byte-array" || - (t.type === "model" && + t.kind === "utcDateTime" || + t.kind === "bytes" || + (t.kind === "model" && t.properties ?.filter((p) => { return !( variantStack.includes(p.type) || ancestors.includes(p.type) || - (p.type.type === "list" && - p.type.elementType && - (variantStack.includes(p.type.elementType) || - ancestors.includes(p.type.elementType))) + (p.type.kind === "array" && + p.type.valueType && + (variantStack.includes(p.type.valueType) || + ancestors.includes(p.type.valueType))) ); }) ?.some( (p) => - p.clientName !== p.restApiName || + (p.kind === "property" && p.name !== p.serializedName) || isSpecialUnionVariant(p.type, [...variantStack, p.type]) )) || isPolymorphicUnion(t) || - (t.type === "list" && - t.elementType && - !variantStack.includes(t.elementType) && - !ancestors.includes(t.elementType) && - isSpecialUnionVariant(t.elementType, [...variantStack, t.elementType])) || - (t.type === "combined" && - t.types + (t.kind === "array" && + t.valueType && + !variantStack.includes(t.valueType) && + !ancestors.includes(t.valueType) && + isSpecialUnionVariant(t.valueType, [...variantStack, t.valueType])) || + (t.kind === "union" && + t.variantTypes ?.filter((p) => { return !(variantStack.includes(p) || ancestors.includes(p)); }) ?.some((p) => { return isSpecialUnionVariant(p, [...variantStack, p]); })) || - (t.type === "enum" && !(t.isFixed || t.isNonExhaustive)) + (t.kind === "enum" && !(t.isFixed || t.isNonExhaustive)) ) { specialVariantMap.set(t, true); variantStack.pop(); @@ -85,11 +84,11 @@ export function isSpecialUnionVariant( return false; } -export function isNormalUnion(t: Type): boolean { +export function isNormalUnion(t: SdkType): boolean { return ( - t.type === "combined" && + t.kind === "union" && !( - t.types?.some((p) => { + t.variantTypes?.some((p) => { return isSpecialUnionVariant(p); }) ?? false ) @@ -109,20 +108,22 @@ export function isDiscriminatedUnion( ); } -export function isSpecialHandledUnion(t: Type): boolean { - return isDiscriminatedUnion(t.tcgcType!) || isPolymorphicUnion(t); +export function isSpecialHandledUnion( + t: SdkType & { isNonExhaustive?: boolean } +): boolean { + return isDiscriminatedUnion(t!) || isPolymorphicUnion(t); } -const polymorphicUnionMap = new Map(); -export function isPolymorphicUnion(t: Type): boolean { +const polymorphicUnionMap = new Map(); +export function isPolymorphicUnion(t: SdkType): boolean { if (polymorphicUnionMap.has(t)) { return polymorphicUnionMap.get(t) ?? false; } const ancestors = getAllAncestors(t); if ( - t.type === "model" && - t.isPolymorphicBaseModel && - t.types + t.kind === "model" && + t.discriminatedSubtypes && + Object.values(t.discriminatedSubtypes) ?.filter((p) => { return !ancestors.includes(p); }) diff --git a/packages/typespec-ts/src/utils/clientUtils.ts b/packages/typespec-ts/src/utils/clientUtils.ts index b3baba6241..6f1a4c9a14 100644 --- a/packages/typespec-ts/src/utils/clientUtils.ts +++ b/packages/typespec-ts/src/utils/clientUtils.ts @@ -1,6 +1,12 @@ -import { SdkClient } from "@azure-tools/typespec-client-generator-core"; +import { + SdkClient, + SdkClientType, + SdkServiceOperation +} from "@azure-tools/typespec-client-generator-core"; import { getNamespaceFullName, listServices } from "@typespec/compiler"; import { SdkContext } from "./interfaces.js"; +import { NameType, normalizeName } from "@azure-tools/rlc-common"; +import { ModularClientOptions } from "../modular/interfaces.js"; export function getRLCClients(dpgContext: SdkContext): SdkClient[] { const services = listServices(dpgContext.program); @@ -23,3 +29,19 @@ export function getRLCClients(dpgContext: SdkContext): SdkClient[] { export function isRLCMultiEndpoint(dpgContext: SdkContext): boolean { return getRLCClients(dpgContext).length > 1; } + +export function getModularClientOptions( + context: SdkContext, + client: SdkClientType +) { + const clientOptions: ModularClientOptions = { + rlcClientName: `${client.name.replace("Client", "")}Context` + }; + if (context.sdkPackage.clients.length > 1) { + clientOptions.subfolder = normalizeName( + client.name.replace("Client", ""), + NameType.File + ); + } + return clientOptions; +} diff --git a/packages/typespec-ts/src/utils/operationUtil.ts b/packages/typespec-ts/src/utils/operationUtil.ts index 3a6217ee34..9958b8ce22 100644 --- a/packages/typespec-ts/src/utils/operationUtil.ts +++ b/packages/typespec-ts/src/utils/operationUtil.ts @@ -23,7 +23,15 @@ import { getWireName, listOperationGroups, listOperationsInOperationGroup, - SdkClient + SdkBodyParameter, + SdkClient, + SdkClientType, + SdkHttpOperation, + SdkHttpParameter, + SdkMethod, + SdkMethodParameter, + SdkServiceMethod, + SdkServiceOperation } from "@azure-tools/typespec-client-generator-core"; import { Model, Operation, Program, Type } from "@typespec/compiler"; import { @@ -408,6 +416,19 @@ export function extractPagedMetadataNested( return paged; } +export function hasCollectionFormatInfo( + paramType: string, + paramFormat: string +) { + return ( + getHasMultiCollection(paramType, paramFormat) || + getHasSsvCollection(paramType, paramFormat) || + getHasTsvCollection(paramType, paramFormat) || + getHasCsvCollection(paramType, paramFormat) || + getHasPipeCollection(paramType, paramFormat) + ); +} + export function getSpecialSerializeInfo( dpgContext: SdkContext, paramType: string, @@ -465,19 +486,6 @@ function getHasPipeCollection(paramType: string, paramFormat: string) { return paramType === "query" && paramFormat === "pipes"; } -export function hasCollectionFormatInfo( - paramType: string, - paramFormat: string -) { - return ( - getHasMultiCollection(paramType, paramFormat) || - getHasSsvCollection(paramType, paramFormat) || - getHasTsvCollection(paramType, paramFormat) || - getHasCsvCollection(paramType, paramFormat) || - getHasPipeCollection(paramType, paramFormat) - ); -} - export function getCollectionFormatHelper( paramType: string, paramFormat: string @@ -546,3 +554,87 @@ export function parseItemName(paged: PagedResultMetadata): string | undefined { // TODO: support the nested item names return (paged.itemsSegments ?? [])[0]; } + +export type ServiceOperation = SdkServiceMethod & { + oriName?: string; +}; + +export function getMethodHierarchiesMap( + context: SdkContext, + client: SdkClientType +): Map { + const methodQueue: [string[], SdkMethod][] = + client.methods.map((m) => { + return [[], m]; + }); + const operationHierarchiesMap: Map = new Map< + string, + ServiceOperation[] + >(); + while (methodQueue.length > 0) { + const method = methodQueue.pop(); + if (!method) { + continue; + } + const prefixes = method[0]; + const operationOrGroup = method[1]; + + if (operationOrGroup.kind === "clientaccessor") { + operationOrGroup.response.methods.forEach((m) => + methodQueue.push([[...prefixes, operationOrGroup.response.name], m]) + ); + } else { + const prefixKey = + context.rlcOptions?.hierarchyClient || + context.rlcOptions?.enableOperationGroup + ? prefixes.join("/") + : ""; + const groupName = prefixes + .map((p) => normalizeName(p, NameType.OperationGroup)) + .join(""); + if ( + context.rlcOptions?.hierarchyClient === false && + context.rlcOptions?.enableOperationGroup && + groupName !== "" && + !operationOrGroup.name.startsWith(groupName + "_") + ) { + (operationOrGroup as ServiceOperation).oriName = operationOrGroup.name; + operationOrGroup.name = `${groupName}_${operationOrGroup.name}`; + } + + operationOrGroup.parameters.map((p) => { + return resolveParameterNameConflict(operationOrGroup, p); + }); + operationOrGroup.operation.parameters.map((p) => { + return resolveParameterNameConflict(operationOrGroup, p); + }); + if ( + operationOrGroup.operation.bodyParam?.name === operationOrGroup.name + ) { + operationOrGroup.operation.bodyParam = resolveParameterNameConflict( + operationOrGroup, + operationOrGroup.operation.bodyParam + ) as SdkBodyParameter; + } + const operations = operationHierarchiesMap.get(prefixKey); + operationHierarchiesMap.set(prefixKey, [ + ...(operations ?? []), + operationOrGroup + ]); + } + } + return operationHierarchiesMap; +} + +function resolveParameterNameConflict( + operationOrGroup: SdkServiceMethod, + p: SdkMethodParameter | SdkHttpParameter | SdkBodyParameter +): SdkMethodParameter | SdkHttpParameter | SdkBodyParameter { + const paramName = normalizeName(p.name, NameType.Parameter, true); + if (paramName === operationOrGroup.name) { + p.name = `${paramName}Parameter`; + } else { + p.name = paramName; + } + return p; +} diff --git a/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts b/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts index f8d6af6e50..ad90e869dc 100644 --- a/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureArmManagedIdentity.spec.ts @@ -4,7 +4,7 @@ describe("Azure Arm Resources Rest Client", () => { let client: CommonPropertiesClient; beforeEach(() => { - client = new CommonPropertiesClient({ + client = new CommonPropertiesClient(SUBSCRIPTION_ID_EXPECTED, { endpoint: "http://localhost:3002", allowInsecureConnection: true }); @@ -72,7 +72,6 @@ describe("Azure Arm Resources Rest Client", () => { // managed identity tracked resource it("should get models commonTypes managedIdentityTrackedResources", async () => { const result = await client.get( - SUBSCRIPTION_ID_EXPECTED, RESOURCE_GROUP_EXPECTED, "identity" ); @@ -108,7 +107,6 @@ describe("Azure Arm Resources Rest Client", () => { it("should put models commonTypes managedIdentityTrackedResources", async () => { const result = await client.createWithSystemAssigned( - SUBSCRIPTION_ID_EXPECTED, RESOURCE_GROUP_EXPECTED, "identity", { @@ -148,7 +146,6 @@ describe("Azure Arm Resources Rest Client", () => { it("should patch models commonTypes managedIdentityTrackedResources", async () => { const result = await client.updateWithUserAssignedAndSystemAssigned( - SUBSCRIPTION_ID_EXPECTED, RESOURCE_GROUP_EXPECTED, "identity", { diff --git a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts index 72d463055d..6b7d2728c1 100644 --- a/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/encodeBytes.spec.ts @@ -163,16 +163,12 @@ describe("EncodeBytesClient Modular Client", () => { }); it(`should post bytes with custom content type`, async () => { - const result = await client.requestBody.customContentType(pngFile, { - contentType: "image/png" - }); + const result = await client.requestBody.customContentType(pngFile); assert.isUndefined(result); }).timeout(10000); it(`should post bytes with custom content type`, async () => { - const result = await client.requestBody.octetStream(pngFile, { - contentType: "application/octet-stream" - }); + const result = await client.requestBody.octetStream(pngFile); assert.isUndefined(result); }); }); diff --git a/packages/typespec-ts/test/modularIntegration/generated/authentication/api-key/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/authentication/api-key/src/index.d.ts index 1afae402ce..519d8e6934 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/authentication/api-key/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/authentication/api-key/src/index.d.ts @@ -7,8 +7,8 @@ export declare class ApiKeyClient { private _client; readonly pipeline: Pipeline; constructor(credential: KeyCredential, options?: ApiKeyClientOptionalParams); - valid(options?: ValidOptionalParams): Promise; invalid(options?: InvalidOptionalParams): Promise; + valid(options?: ValidOptionalParams): Promise; } export declare interface ApiKeyClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/authentication/http/custom/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/authentication/http/custom/src/index.d.ts index a8f5070031..5f729c295e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/authentication/http/custom/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/authentication/http/custom/src/index.d.ts @@ -7,8 +7,8 @@ export declare class CustomClient { private _client; readonly pipeline: Pipeline; constructor(credential: KeyCredential, options?: CustomClientOptionalParams); - valid(options?: ValidOptionalParams): Promise; invalid(options?: InvalidOptionalParams): Promise; + valid(options?: ValidOptionalParams): Promise; } export declare interface CustomClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/authentication/oauth2/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/authentication/oauth2/src/index.d.ts index 94b6bab8f4..028d21f5e9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/authentication/oauth2/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/authentication/oauth2/src/index.d.ts @@ -10,8 +10,8 @@ export declare class OAuth2Client { private _client; readonly pipeline: Pipeline; constructor(credential: TokenCredential, options?: OAuth2ClientOptionalParams); - valid(options?: ValidOptionalParams): Promise; invalid(options?: InvalidOptionalParams): Promise; + valid(options?: ValidOptionalParams): Promise; } export declare interface OAuth2ClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/authentication/union/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/authentication/union/src/index.d.ts index 6ac8b28b5f..96ce7bf62b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/authentication/union/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/authentication/union/src/index.d.ts @@ -8,8 +8,8 @@ export declare class UnionClient { private _client; readonly pipeline: Pipeline; constructor(credential: KeyCredential | TokenCredential, options?: UnionClientOptionalParams); - validKey(options?: ValidKeyOptionalParams): Promise; validToken(options?: ValidTokenOptionalParams): Promise; + validKey(options?: ValidKeyOptionalParams): Promise; } export declare interface UnionClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts index b0e05b9dbd..aea3d94001 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/access/src/index.d.ts @@ -13,15 +13,15 @@ export declare class AccessClient { private _client; readonly pipeline: Pipeline; constructor(options?: AccessClientOptionalParams); - noDecoratorInPublic(name: string, options?: NoDecoratorInPublicOptionalParams): Promise; - publicDecoratorInPublic(name: string, options?: PublicDecoratorInPublicOptionalParams): Promise; - noDecoratorInInternal(name: string, options?: NoDecoratorInInternalOptionalParams): Promise; - internalDecoratorInInternal(name: string, options?: InternalDecoratorInInternalOptionalParams): Promise; - publicDecoratorInInternal(name: string, options?: PublicDecoratorInInternalOptionalParams): Promise; - public(name: string, options?: PublicOptionalParams): Promise; - internal(name: string, options?: InternalOptionalParams): Promise; - operation(name: string, options?: OperationOptionalParams): Promise; discriminator(kind: string, options?: DiscriminatorOptionalParams): Promise; + operation(name: string, options?: OperationOptionalParams): Promise; + internal(name: string, options?: InternalOptionalParams): Promise; + public(name: string, options?: PublicOptionalParams): Promise; + publicDecoratorInInternal(name: string, options?: PublicDecoratorInInternalOptionalParams): Promise; + internalDecoratorInInternal(name: string, options?: InternalDecoratorInInternalOptionalParams): Promise; + noDecoratorInInternal(name: string, options?: NoDecoratorInInternalOptionalParams): Promise; + publicDecoratorInPublic(name: string, options?: PublicDecoratorInPublicOptionalParams): Promise; + noDecoratorInPublic(name: string, options?: NoDecoratorInPublicOptionalParams): Promise; } export declare interface AccessClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/flatten-property/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/flatten-property/src/index.d.ts index 09fffd56d0..3154d12461 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/flatten-property/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/flatten-property/src/index.d.ts @@ -21,8 +21,8 @@ export declare class FlattenPropertyClient { private _client; readonly pipeline: Pipeline; constructor(options?: FlattenPropertyClientOptionalParams); - putFlattenModel(input: FlattenModel, options?: PutFlattenModelOptionalParams): Promise; putNestedFlattenModel(input: NestedFlattenModel, options?: PutNestedFlattenModelOptionalParams): Promise; + putFlattenModel(input: FlattenModel, options?: PutFlattenModelOptionalParams): Promise; } export declare interface FlattenPropertyClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/usage/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/usage/src/index.d.ts index 34c9490ff6..a3c169c30c 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/usage/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/client-generator-core/usage/src/index.d.ts @@ -35,9 +35,9 @@ export declare class UsageClient { private _client; readonly pipeline: Pipeline; constructor(options?: UsageClientOptionalParams); - inputToInputOutput(body: InputModel, options?: InputToInputOutputOptionalParams): Promise; - outputToInputOutput(options?: OutputToInputOutputOptionalParams): Promise; modelInReadOnlyProperty(body: RoundTripModel, options?: ModelInReadOnlyPropertyOptionalParams): Promise; + outputToInputOutput(options?: OutputToInputOutputOptionalParams): Promise; + inputToInputOutput(body: InputModel, options?: InputToInputOutputOptionalParams): Promise; } export declare interface UsageClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts index b0f8a94c62..4e57d63ed6 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/basic/src/index.d.ts @@ -6,13 +6,13 @@ export declare class BasicClient { private _client; readonly pipeline: Pipeline; constructor(options?: BasicClientOptionalParams); - createOrUpdate(id: number, resource: User, options?: CreateOrUpdateOptionalParams): Promise; - createOrReplace(id: number, resource: User, options?: CreateOrReplaceOptionalParams): Promise; - get(id: number, options?: GetOptionalParams): Promise; - list(options?: ListOptionalParams): PagedAsyncIterableIterator; - delete(id: number, options?: DeleteOptionalParams): Promise; - export(id: number, format: string, options?: ExportOptionalParams): Promise; exportAllUsers(format: string, options?: ExportAllUsersOptionalParams): Promise; + export(id: number, format: string, options?: ExportOptionalParams): Promise; + delete(id: number, options?: DeleteOptionalParams): Promise; + list(options?: ListOptionalParams): PagedAsyncIterableIterator; + get(id: number, options?: GetOptionalParams): Promise; + createOrReplace(id: number, resource: User, options?: CreateOrReplaceOptionalParams): Promise; + createOrUpdate(id: number, resource: User, options?: CreateOrUpdateOptionalParams): Promise; } export declare interface BasicClientOptionalParams extends ClientOptions { @@ -27,7 +27,6 @@ export declare interface CreateOrReplaceOptionalParams extends OperationOptions } export declare interface CreateOrUpdateOptionalParams extends OperationOptions { - contentType?: string; } export declare interface DeleteOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts index d4c9fc312f..fa88bbb051 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/lro/standard/src/index.d.ts @@ -39,9 +39,9 @@ export declare class StandardClient { private _client; readonly pipeline: Pipeline; constructor(options?: StandardClientOptionalParams); - createOrReplace(name: string, resource: User, options?: CreateOrReplaceOptionalParams): PollerLike, User>; - delete(name: string, options?: DeleteOptionalParams): PollerLike, void>; export(name: string, format: string, options?: ExportOptionalParams): PollerLike, ExportedUser>; + delete(name: string, options?: DeleteOptionalParams): PollerLike, void>; + createOrReplace(name: string, resource: User, options?: CreateOrReplaceOptionalParams): PollerLike, User>; } export declare interface StandardClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts index 7147d9ece5..19067ae946 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/model/src/index.d.ts @@ -17,9 +17,9 @@ export declare class ModelClient { private _client; readonly pipeline: Pipeline; constructor(options?: ModelClientOptionalParams); - get(options?: GetOptionalParams): Promise; - put(body: number[], options?: PutOptionalParams): Promise; post(body: AzureEmbeddingModel, options?: PostOptionalParams): Promise; + put(body: number[], options?: PutOptionalParams): Promise; + get(options?: GetOptionalParams): Promise; } export declare interface ModelClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts index 3409347c11..6dc6befb89 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/page/src/index.d.ts @@ -40,11 +40,11 @@ export declare class PageClient { private _client; readonly pipeline: Pipeline; constructor(options?: PageClientOptionalParams); - listWithPage(options?: ListWithPageOptionalParams): PagedAsyncIterableIterator; - listWithParameters(bodyInput: ListItemInputBody, options?: ListWithParametersOptionalParams): PagedAsyncIterableIterator; - listWithCustomPageModel(options?: ListWithCustomPageModelOptionalParams): PagedAsyncIterableIterator; - listFirstItem(options?: ListFirstItemOptionalParams): PagedAsyncIterableIterator; listSecondItem(options?: ListSecondItemOptionalParams): PagedAsyncIterableIterator; + listFirstItem(options?: ListFirstItemOptionalParams): PagedAsyncIterableIterator; + listWithCustomPageModel(options?: ListWithCustomPageModelOptionalParams): PagedAsyncIterableIterator; + listWithParameters(bodyInput: ListItemInputBody, options?: ListWithParametersOptionalParams): PagedAsyncIterableIterator; + listWithPage(options?: ListWithPageOptionalParams): PagedAsyncIterableIterator; } export declare interface PageClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts index 07b873e0bd..59f7d7a95b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/scalar/src/index.d.ts @@ -29,11 +29,11 @@ export declare class ScalarClient { private _client; readonly pipeline: Pipeline; constructor(options?: ScalarClientOptionalParams); - get(options?: GetOptionalParams): Promise; - put(body: string, options?: PutOptionalParams): Promise; - post(body: AzureLocationModel, options?: PostOptionalParams): Promise; - header(region: string, options?: HeaderOptionalParams): Promise; query(region: string, options?: QueryOptionalParams): Promise; + header(region: string, options?: HeaderOptionalParams): Promise; + post(body: AzureLocationModel, options?: PostOptionalParams): Promise; + put(body: string, options?: PutOptionalParams): Promise; + get(options?: GetOptionalParams): Promise; } export declare interface ScalarClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts index 616bb4e110..5b63c53da5 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/traits/src/index.d.ts @@ -25,8 +25,8 @@ export declare class TraitsClient { private _client; readonly pipeline: Pipeline; constructor(options?: TraitsClientOptionalParams); - smokeTest(id: number, foo: string, options?: SmokeTestOptionalParams): Promise; repeatableAction(id: number, body: UserActionParam, options?: RepeatableActionOptionalParams): Promise; + smokeTest(id: number, foo: string, options?: SmokeTestOptionalParams): Promise; } export declare interface TraitsClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/common-properties/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/common-properties/src/index.d.ts index acc180aa01..552ce3f092 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/common-properties/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/common-properties/src/index.d.ts @@ -5,10 +5,10 @@ import { Pipeline } from '@azure/core-rest-pipeline'; export declare class CommonPropertiesClient { private _client; readonly pipeline: Pipeline; - constructor(options?: CommonPropertiesClientOptionalParams); - get(subscriptionId: string, resourceGroupName: string, managedIdentityTrackedResourceName: string, options?: GetOptionalParams): Promise; - createWithSystemAssigned(subscriptionId: string, resourceGroupName: string, managedIdentityTrackedResourceName: string, resource: ManagedIdentityTrackedResource, options?: CreateWithSystemAssignedOptionalParams): Promise; - updateWithUserAssignedAndSystemAssigned(subscriptionId: string, resourceGroupName: string, managedIdentityTrackedResourceName: string, properties: ManagedIdentityTrackedResource, options?: UpdateWithUserAssignedAndSystemAssignedOptionalParams): Promise; + constructor(subscriptionId: string, options?: CommonPropertiesClientOptionalParams); + updateWithUserAssignedAndSystemAssigned(resourceGroupName: string, managedIdentityTrackedResourceName: string, properties: ManagedIdentityTrackedResource, options?: UpdateWithUserAssignedAndSystemAssignedOptionalParams): Promise; + createWithSystemAssigned(resourceGroupName: string, managedIdentityTrackedResourceName: string, resource: ManagedIdentityTrackedResource, options?: CreateWithSystemAssignedOptionalParams): Promise; + get(resourceGroupName: string, managedIdentityTrackedResourceName: string, options?: GetOptionalParams): Promise; } export declare interface CommonPropertiesClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/resources/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/resources/src/index.d.ts index 0870c76f6e..4567079236 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/resources/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/resource-manager/resources/src/index.d.ts @@ -48,11 +48,11 @@ export declare interface NestedListByTopLevelTrackedResourceOptionalParams exten } export declare interface NestedOperations { - get: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, options?: NestedGetOptionalParams) => Promise; - createOrReplace: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, resource: NestedProxyResource, options?: NestedCreateOrReplaceOptionalParams) => PollerLike, NestedProxyResource>; - update: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, properties: NestedProxyResource, options?: NestedUpdateOptionalParams) => PollerLike, NestedProxyResource>; - delete: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, options?: NestedDeleteOptionalParams) => PollerLike, void>; listByTopLevelTrackedResource: (resourceGroupName: string, topLevelTrackedResourceName: string, options?: NestedListByTopLevelTrackedResourceOptionalParams) => PagedAsyncIterableIterator; + delete: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, options?: NestedDeleteOptionalParams) => PollerLike, void>; + update: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, properties: NestedProxyResource, options?: NestedUpdateOptionalParams) => PollerLike, NestedProxyResource>; + createOrReplace: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, resource: NestedProxyResource, options?: NestedCreateOrReplaceOptionalParams) => PollerLike, NestedProxyResource>; + get: (resourceGroupName: string, topLevelTrackedResourceName: string, nextedProxyResourceName: string, options?: NestedGetOptionalParams) => Promise; } export declare interface NestedProxyResource extends ProxyResource { @@ -99,9 +99,9 @@ export declare class ResourcesClient { private _client; readonly pipeline: Pipeline; constructor(subscriptionId: string, options?: ResourcesClientOptionalParams); - readonly topLevel: TopLevelOperations; - readonly nested: NestedOperations; readonly singleton: SingletonOperations; + readonly nested: NestedOperations; + readonly topLevel: TopLevelOperations; } export declare interface ResourcesClientOptionalParams extends ClientOptions { @@ -127,10 +127,10 @@ export declare interface SingletonListByResourceGroupOptionalParams extends Oper } export declare interface SingletonOperations { - getByResourceGroup: (resourceGroupName: string, options?: SingletonGetByResourceGroupOptionalParams) => Promise; - createOrUpdate: (resourceGroupName: string, resource: SingletonTrackedResource, options?: SingletonCreateOrUpdateOptionalParams) => PollerLike, SingletonTrackedResource>; - update: (resourceGroupName: string, properties: SingletonTrackedResource, options?: SingletonUpdateOptionalParams) => Promise; listByResourceGroup: (resourceGroupName: string, options?: SingletonListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; + update: (resourceGroupName: string, properties: SingletonTrackedResource, options?: SingletonUpdateOptionalParams) => Promise; + createOrUpdate: (resourceGroupName: string, resource: SingletonTrackedResource, options?: SingletonCreateOrUpdateOptionalParams) => PollerLike, SingletonTrackedResource>; + getByResourceGroup: (resourceGroupName: string, options?: SingletonGetByResourceGroupOptionalParams) => Promise; } export declare interface SingletonTrackedResource extends TrackedResource { @@ -175,13 +175,13 @@ export declare interface TopLevelListBySubscriptionOptionalParams extends Operat } export declare interface TopLevelOperations { - get: (resourceGroupName: string, topLevelTrackedResourceName: string, options?: TopLevelGetOptionalParams) => Promise; - createOrReplace: (resourceGroupName: string, topLevelTrackedResourceName: string, resource: TopLevelTrackedResource, options?: TopLevelCreateOrReplaceOptionalParams) => PollerLike, TopLevelTrackedResource>; - update: (resourceGroupName: string, topLevelTrackedResourceName: string, properties: TopLevelTrackedResource, options?: TopLevelUpdateOptionalParams) => PollerLike, TopLevelTrackedResource>; - delete: (resourceGroupName: string, topLevelTrackedResourceName: string, options?: TopLevelDeleteOptionalParams) => PollerLike, void>; - listByResourceGroup: (resourceGroupName: string, options?: TopLevelListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; - listBySubscription: (options?: TopLevelListBySubscriptionOptionalParams) => PagedAsyncIterableIterator; actionSync: (resourceGroupName: string, topLevelTrackedResourceName: string, body: NotificationDetails, options?: TopLevelActionSyncOptionalParams) => Promise; + listBySubscription: (options?: TopLevelListBySubscriptionOptionalParams) => PagedAsyncIterableIterator; + listByResourceGroup: (resourceGroupName: string, options?: TopLevelListByResourceGroupOptionalParams) => PagedAsyncIterableIterator; + delete: (resourceGroupName: string, topLevelTrackedResourceName: string, options?: TopLevelDeleteOptionalParams) => PollerLike, void>; + update: (resourceGroupName: string, topLevelTrackedResourceName: string, properties: TopLevelTrackedResource, options?: TopLevelUpdateOptionalParams) => PollerLike, TopLevelTrackedResource>; + createOrReplace: (resourceGroupName: string, topLevelTrackedResourceName: string, resource: TopLevelTrackedResource, options?: TopLevelCreateOrReplaceOptionalParams) => PollerLike, TopLevelTrackedResource>; + get: (resourceGroupName: string, topLevelTrackedResourceName: string, options?: TopLevelGetOptionalParams) => Promise; } export declare interface TopLevelTrackedResource extends TrackedResource { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts index 6588f5f6d6..34a903daad 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/naming/src/index.d.ts @@ -15,8 +15,8 @@ export declare interface ClientModelLanguageOptionalParams extends OperationOpti } export declare interface ClientModelOperations { - client: (body: ClientModel, options?: ClientModelClientOptionalParams) => Promise; language: (body: TSModel, options?: ClientModelLanguageOptionalParams) => Promise; + client: (body: ClientModel, options?: ClientModelClientOptionalParams) => Promise; } export declare interface ClientNameAndJsonEncodedNameModel { @@ -49,15 +49,15 @@ export declare class NamingClient { private _client; readonly pipeline: Pipeline; constructor(options?: NamingClientOptionalParams); - clientName(options?: ClientNameOptionalParams): Promise; - parameter(clientName: string, options?: ParameterOptionalParams): Promise; - client(body: ClientNameModel, options?: ClientOptionalParams): Promise; - language(body: LanguageClientNameModel, options?: LanguageOptionalParams): Promise; - compatibleWithEncodedName(body: ClientNameAndJsonEncodedNameModel, options?: CompatibleWithEncodedNameOptionalParams): Promise; - request(clientName: string, options?: RequestOptionalParams): Promise; - response(options?: ResponseOptionalParams): Promise; - readonly clientModel: ClientModelOperations; readonly unionEnum: UnionEnumOperations; + readonly clientModel: ClientModelOperations; + response(options?: ResponseOptionalParams): Promise; + request(clientName: string, options?: RequestOptionalParams): Promise; + compatibleWithEncodedName(body: ClientNameAndJsonEncodedNameModel, options?: CompatibleWithEncodedNameOptionalParams): Promise; + language(body: LanguageClientNameModel, options?: LanguageOptionalParams): Promise; + client(body: ClientNameModel, options?: ClientOptionalParams): Promise; + parameter(clientName: string, options?: ParameterOptionalParams): Promise; + clientName(options?: ClientNameOptionalParams): Promise; } export declare interface NamingClientOptionalParams extends ClientOptions { @@ -77,8 +77,8 @@ export declare interface TSModel { } export declare interface UnionEnumOperations { - unionEnumName: (body: ClientExtensibleEnum, options?: UnionEnumUnionEnumNameOptionalParams) => Promise; unionEnumMemberName: (body: ExtensibleEnum, options?: UnionEnumUnionEnumMemberNameOptionalParams) => Promise; + unionEnumName: (body: ClientExtensibleEnum, options?: UnionEnumUnionEnumNameOptionalParams) => Promise; } export declare interface UnionEnumUnionEnumMemberNameOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts index 95e0dcad6b..147a3e7f52 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/client-operation-group/src/index.d.ts @@ -8,9 +8,9 @@ export declare class FirstClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: FirstClientOptionalParams); - one(options?: OneOptionalParams): Promise; - readonly group3: Group3Operations; readonly group4: Group4Operations; + readonly group3: Group3Operations; + one(options?: OneOptionalParams): Promise; } export declare interface FirstClientOptionalParams extends ClientOptions { @@ -20,8 +20,8 @@ export declare interface FiveOptionalParams extends OperationOptions { } export declare interface Group3Operations { - two: (options?: Group3TwoOptionalParams) => Promise; three: (options?: Group3ThreeOptionalParams) => Promise; + two: (options?: Group3TwoOptionalParams) => Promise; } export declare interface Group3ThreeOptionalParams extends OperationOptions { @@ -51,8 +51,8 @@ export declare class SecondClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: SecondClientOptionalParams); - five(options?: FiveOptionalParams): Promise; readonly group5: Group5Operations; + five(options?: FiveOptionalParams): Promise; } export declare interface SecondClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/default/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/default/src/index.d.ts index 29121a66b1..c449c1e4d4 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/default/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/default/src/index.d.ts @@ -6,8 +6,8 @@ export declare interface BarFiveOptionalParams extends OperationOptions { } export declare interface BarOperations { - five: (options?: BarFiveOptionalParams) => Promise; six: (options?: BarSixOptionalParams) => Promise; + five: (options?: BarFiveOptionalParams) => Promise; } export declare interface BarSixOptionalParams extends OperationOptions { @@ -30,8 +30,8 @@ export declare interface FooFourOptionalParams extends OperationOptions { } export declare interface FooOperations { - three: (options?: FooThreeOptionalParams) => Promise; four: (options?: FooFourOptionalParams) => Promise; + three: (options?: FooThreeOptionalParams) => Promise; } export declare interface FooThreeOptionalParams extends OperationOptions { @@ -59,12 +59,12 @@ export declare class ServiceClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: ServiceClientOptionalParams); - one(options?: OneOptionalParams): Promise; - two(options?: TwoOptionalParams): Promise; - readonly baz: BazOperations; - readonly qux: QuxOperations; - readonly foo: FooOperations; readonly bar: BarOperations; + readonly foo: FooOperations; + readonly qux: QuxOperations; + readonly baz: BazOperations; + two(options?: TwoOptionalParams): Promise; + one(options?: OneOptionalParams): Promise; } export declare interface ServiceClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts index 22ba7e50c6..493c345dfd 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/multi-client/src/index.d.ts @@ -6,9 +6,9 @@ export declare class ClientAClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: ClientAClientOptionalParams); - renamedOne(options?: RenamedOneOptionalParams): Promise; - renamedThree(options?: RenamedThreeOptionalParams): Promise; renamedFive(options?: RenamedFiveOptionalParams): Promise; + renamedThree(options?: RenamedThreeOptionalParams): Promise; + renamedOne(options?: RenamedOneOptionalParams): Promise; } export declare interface ClientAClientOptionalParams extends ClientOptions { @@ -18,9 +18,9 @@ export declare class ClientBClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: ClientBClientOptionalParams); - renamedTwo(options?: RenamedTwoOptionalParams): Promise; - renamedFour(options?: RenamedFourOptionalParams): Promise; renamedSix(options?: RenamedSixOptionalParams): Promise; + renamedFour(options?: RenamedFourOptionalParams): Promise; + renamedTwo(options?: RenamedTwoOptionalParams): Promise; } export declare interface ClientBClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/renamed-operation/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/renamed-operation/src/index.d.ts index fb6baa5855..48d88a723a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/renamed-operation/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/renamed-operation/src/index.d.ts @@ -5,9 +5,9 @@ import { Pipeline } from '@azure/core-rest-pipeline'; export declare type ClientType = "default" | "multi-client" | "renamed-operation" | "two-operation-group" | "client-operation-group"; export declare interface GroupOperations { - renamedTwo: (options?: GroupRenamedTwoOptionalParams) => Promise; - renamedFour: (options?: GroupRenamedFourOptionalParams) => Promise; renamedSix: (options?: GroupRenamedSixOptionalParams) => Promise; + renamedFour: (options?: GroupRenamedFourOptionalParams) => Promise; + renamedTwo: (options?: GroupRenamedTwoOptionalParams) => Promise; } export declare interface GroupRenamedFourOptionalParams extends OperationOptions { @@ -29,10 +29,10 @@ export declare class RenamedOperationClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: RenamedOperationClientOptionalParams); - renamedOne(options?: RenamedOneOptionalParams): Promise; - renamedThree(options?: RenamedThreeOptionalParams): Promise; - renamedFive(options?: RenamedFiveOptionalParams): Promise; readonly group: GroupOperations; + renamedFive(options?: RenamedFiveOptionalParams): Promise; + renamedThree(options?: RenamedThreeOptionalParams): Promise; + renamedOne(options?: RenamedOneOptionalParams): Promise; } export declare interface RenamedOperationClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/client/structure/two-operation-group/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/client/structure/two-operation-group/src/index.d.ts index 1d34fb18fd..84c502dc82 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/client/structure/two-operation-group/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/client/structure/two-operation-group/src/index.d.ts @@ -11,9 +11,9 @@ export declare interface Group1OneOptionalParams extends OperationOptions { } export declare interface Group1Operations { - one: (options?: Group1OneOptionalParams) => Promise; - three: (options?: Group1ThreeOptionalParams) => Promise; four: (options?: Group1FourOptionalParams) => Promise; + three: (options?: Group1ThreeOptionalParams) => Promise; + one: (options?: Group1OneOptionalParams) => Promise; } export declare interface Group1ThreeOptionalParams extends OperationOptions { @@ -23,9 +23,9 @@ export declare interface Group2FiveOptionalParams extends OperationOptions { } export declare interface Group2Operations { - two: (options?: Group2TwoOptionalParams) => Promise; - five: (options?: Group2FiveOptionalParams) => Promise; six: (options?: Group2SixOptionalParams) => Promise; + five: (options?: Group2FiveOptionalParams) => Promise; + two: (options?: Group2TwoOptionalParams) => Promise; } export declare interface Group2SixOptionalParams extends OperationOptions { @@ -38,8 +38,8 @@ export declare class TwoOperationGroupClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, clientParam: ClientType, options?: TwoOperationGroupClientOptionalParams); - readonly group1: Group1Operations; readonly group2: Group2Operations; + readonly group1: Group1Operations; } export declare interface TwoOperationGroupClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.d.ts index e505dfd63f..b031f9cf37 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/bytes/src/index.d.ts @@ -18,11 +18,11 @@ export declare class BytesClient { private _client; readonly pipeline: Pipeline; constructor(options?: BytesClientOptionalParams); - readonly query: QueryOperations; - readonly property: PropertyOperations; - readonly header: HeaderOperations; - readonly requestBody: RequestBodyOperations; readonly responseBody: ResponseBodyOperations; + readonly requestBody: RequestBodyOperations; + readonly header: HeaderOperations; + readonly property: PropertyOperations; + readonly query: QueryOperations; } export declare interface BytesClientOptionalParams extends ClientOptions { @@ -45,10 +45,10 @@ export declare interface HeaderDefaultOptionalParams extends OperationOptions { } export declare interface HeaderOperations { - default: (value: Uint8Array, options?: HeaderDefaultOptionalParams) => Promise; - base64: (value: Uint8Array, options?: HeaderBase64OptionalParams) => Promise; - base64url: (value: Uint8Array, options?: HeaderBase64urlOptionalParams) => Promise; base64urlArray: (value: Uint8Array[], options?: HeaderBase64urlArrayOptionalParams) => Promise; + base64url: (value: Uint8Array, options?: HeaderBase64urlOptionalParams) => Promise; + base64: (value: Uint8Array, options?: HeaderBase64OptionalParams) => Promise; + default: (value: Uint8Array, options?: HeaderDefaultOptionalParams) => Promise; } export declare interface PropertyBase64OptionalParams extends OperationOptions { @@ -64,10 +64,10 @@ export declare interface PropertyDefaultOptionalParams extends OperationOptions } export declare interface PropertyOperations { - default: (body: DefaultBytesProperty, options?: PropertyDefaultOptionalParams) => Promise; - base64: (body: Base64BytesProperty, options?: PropertyBase64OptionalParams) => Promise; - base64url: (body: Base64urlBytesProperty, options?: PropertyBase64urlOptionalParams) => Promise; base64urlArray: (body: Base64urlArrayBytesProperty, options?: PropertyBase64urlArrayOptionalParams) => Promise; + base64url: (body: Base64urlBytesProperty, options?: PropertyBase64urlOptionalParams) => Promise; + base64: (body: Base64BytesProperty, options?: PropertyBase64OptionalParams) => Promise; + default: (body: DefaultBytesProperty, options?: PropertyDefaultOptionalParams) => Promise; } export declare interface QueryBase64OptionalParams extends OperationOptions { @@ -83,10 +83,10 @@ export declare interface QueryDefaultOptionalParams extends OperationOptions { } export declare interface QueryOperations { - default: (value: Uint8Array, options?: QueryDefaultOptionalParams) => Promise; - base64: (value: Uint8Array, options?: QueryBase64OptionalParams) => Promise; - base64url: (value: Uint8Array, options?: QueryBase64urlOptionalParams) => Promise; base64urlArray: (value: Uint8Array[], options?: QueryBase64urlArrayOptionalParams) => Promise; + base64url: (value: Uint8Array, options?: QueryBase64urlOptionalParams) => Promise; + base64: (value: Uint8Array, options?: QueryBase64OptionalParams) => Promise; + default: (value: Uint8Array, options?: QueryDefaultOptionalParams) => Promise; } export declare interface RequestBodyBase64OptionalParams extends OperationOptions { @@ -96,22 +96,20 @@ export declare interface RequestBodyBase64urlOptionalParams extends OperationOpt } export declare interface RequestBodyCustomContentTypeOptionalParams extends OperationOptions { - contentType?: string; } export declare interface RequestBodyDefaultOptionalParams extends OperationOptions { } export declare interface RequestBodyOctetStreamOptionalParams extends OperationOptions { - contentType?: string; } export declare interface RequestBodyOperations { - default: (value: Uint8Array, options?: RequestBodyDefaultOptionalParams) => Promise; - octetStream: (value: Uint8Array, options?: RequestBodyOctetStreamOptionalParams) => Promise; - customContentType: (value: Uint8Array, options?: RequestBodyCustomContentTypeOptionalParams) => Promise; - base64: (value: Uint8Array, options?: RequestBodyBase64OptionalParams) => Promise; base64url: (value: Uint8Array, options?: RequestBodyBase64urlOptionalParams) => Promise; + base64: (value: Uint8Array, options?: RequestBodyBase64OptionalParams) => Promise; + customContentType: (value: Uint8Array, options?: RequestBodyCustomContentTypeOptionalParams) => Promise; + octetStream: (value: Uint8Array, options?: RequestBodyOctetStreamOptionalParams) => Promise; + default: (value: Uint8Array, options?: RequestBodyDefaultOptionalParams) => Promise; } export declare interface ResponseBodyBase64OptionalParams extends OperationOptions { @@ -130,11 +128,11 @@ export declare interface ResponseBodyOctetStreamOptionalParams extends Operation } export declare interface ResponseBodyOperations { - default: (options?: ResponseBodyDefaultOptionalParams) => Promise; - octetStream: (options?: ResponseBodyOctetStreamOptionalParams) => Promise; - customContentType: (options?: ResponseBodyCustomContentTypeOptionalParams) => Promise; - base64: (options?: ResponseBodyBase64OptionalParams) => Promise; base64url: (options?: ResponseBodyBase64urlOptionalParams) => Promise; + base64: (options?: ResponseBodyBase64OptionalParams) => Promise; + customContentType: (options?: ResponseBodyCustomContentTypeOptionalParams) => Promise; + octetStream: (options?: ResponseBodyOctetStreamOptionalParams) => Promise; + default: (options?: ResponseBodyDefaultOptionalParams) => Promise; } export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.d.ts index d6bb540973..8ed5a8c89a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/datetime/src/index.d.ts @@ -6,10 +6,10 @@ export declare class DatetimeClient { private _client; readonly pipeline: Pipeline; constructor(options?: DatetimeClientOptionalParams); - readonly query: QueryOperations; - readonly property: PropertyOperations; - readonly header: HeaderOperations; readonly responseHeader: ResponseHeaderOperations; + readonly header: HeaderOperations; + readonly property: PropertyOperations; + readonly query: QueryOperations; } export declare interface DatetimeClientOptionalParams extends ClientOptions { @@ -23,11 +23,11 @@ export declare interface HeaderDefaultOptionalParams extends OperationOptions { } export declare interface HeaderOperations { - default: (value: Date, options?: HeaderDefaultOptionalParams) => Promise; - rfc3339: (value: Date, options?: HeaderRfc3339OptionalParams) => Promise; - rfc7231: (value: Date, options?: HeaderRfc7231OptionalParams) => Promise; - unixTimestamp: (value: Date, options?: HeaderUnixTimestampOptionalParams) => Promise; unixTimestampArray: (value: Date[], options?: HeaderUnixTimestampArrayOptionalParams) => Promise; + unixTimestamp: (value: Date, options?: HeaderUnixTimestampOptionalParams) => Promise; + rfc7231: (value: Date, options?: HeaderRfc7231OptionalParams) => Promise; + rfc3339: (value: Date, options?: HeaderRfc3339OptionalParams) => Promise; + default: (value: Date, options?: HeaderDefaultOptionalParams) => Promise; } export declare interface HeaderRfc3339OptionalParams extends OperationOptions { @@ -46,11 +46,11 @@ export declare interface PropertyDefaultOptionalParams extends OperationOptions } export declare interface PropertyOperations { - default: (body: DefaultDatetimeProperty, options?: PropertyDefaultOptionalParams) => Promise; - rfc3339: (body: Rfc3339DatetimeProperty, options?: PropertyRfc3339OptionalParams) => Promise; - rfc7231: (body: Rfc7231DatetimeProperty, options?: PropertyRfc7231OptionalParams) => Promise; - unixTimestamp: (body: UnixTimestampDatetimeProperty, options?: PropertyUnixTimestampOptionalParams) => Promise; unixTimestampArray: (body: UnixTimestampArrayDatetimeProperty, options?: PropertyUnixTimestampArrayOptionalParams) => Promise; + unixTimestamp: (body: UnixTimestampDatetimeProperty, options?: PropertyUnixTimestampOptionalParams) => Promise; + rfc7231: (body: Rfc7231DatetimeProperty, options?: PropertyRfc7231OptionalParams) => Promise; + rfc3339: (body: Rfc3339DatetimeProperty, options?: PropertyRfc3339OptionalParams) => Promise; + default: (body: DefaultDatetimeProperty, options?: PropertyDefaultOptionalParams) => Promise; } export declare interface PropertyRfc3339OptionalParams extends OperationOptions { @@ -69,11 +69,11 @@ export declare interface QueryDefaultOptionalParams extends OperationOptions { } export declare interface QueryOperations { - default: (value: Date, options?: QueryDefaultOptionalParams) => Promise; - rfc3339: (value: Date, options?: QueryRfc3339OptionalParams) => Promise; - rfc7231: (value: Date, options?: QueryRfc7231OptionalParams) => Promise; - unixTimestamp: (value: Date, options?: QueryUnixTimestampOptionalParams) => Promise; unixTimestampArray: (value: Date[], options?: QueryUnixTimestampArrayOptionalParams) => Promise; + unixTimestamp: (value: Date, options?: QueryUnixTimestampOptionalParams) => Promise; + rfc7231: (value: Date, options?: QueryRfc7231OptionalParams) => Promise; + rfc3339: (value: Date, options?: QueryRfc3339OptionalParams) => Promise; + default: (value: Date, options?: QueryDefaultOptionalParams) => Promise; } export declare interface QueryRfc3339OptionalParams extends OperationOptions { @@ -92,10 +92,10 @@ export declare interface ResponseHeaderDefaultOptionalParams extends OperationOp } export declare interface ResponseHeaderOperations { - default: (options?: ResponseHeaderDefaultOptionalParams) => Promise; - rfc3339: (options?: ResponseHeaderRfc3339OptionalParams) => Promise; - rfc7231: (options?: ResponseHeaderRfc7231OptionalParams) => Promise; unixTimestamp: (options?: ResponseHeaderUnixTimestampOptionalParams) => Promise; + rfc7231: (options?: ResponseHeaderRfc7231OptionalParams) => Promise; + rfc3339: (options?: ResponseHeaderRfc3339OptionalParams) => Promise; + default: (options?: ResponseHeaderDefaultOptionalParams) => Promise; } export declare interface ResponseHeaderRfc3339OptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.d.ts index d5d531d085..a0dd0c9b57 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/duration/src/index.d.ts @@ -10,9 +10,9 @@ export declare class DurationClient { private _client; readonly pipeline: Pipeline; constructor(options?: DurationClientOptionalParams); - readonly query: QueryOperations; - readonly property: PropertyOperations; readonly header: HeaderOperations; + readonly property: PropertyOperations; + readonly query: QueryOperations; } export declare interface DurationClientOptionalParams extends ClientOptions { @@ -49,12 +49,12 @@ export declare interface HeaderIso8601OptionalParams extends OperationOptions { } export declare interface HeaderOperations { - default: (duration: string, options?: HeaderDefaultOptionalParams) => Promise; - iso8601: (duration: string, options?: HeaderIso8601OptionalParams) => Promise; - iso8601Array: (duration: string[], options?: HeaderIso8601ArrayOptionalParams) => Promise; - int32Seconds: (duration: number, options?: HeaderInt32SecondsOptionalParams) => Promise; - floatSeconds: (duration: number, options?: HeaderFloatSecondsOptionalParams) => Promise; float64Seconds: (duration: number, options?: HeaderFloat64SecondsOptionalParams) => Promise; + floatSeconds: (duration: number, options?: HeaderFloatSecondsOptionalParams) => Promise; + int32Seconds: (duration: number, options?: HeaderInt32SecondsOptionalParams) => Promise; + iso8601Array: (duration: string[], options?: HeaderIso8601ArrayOptionalParams) => Promise; + iso8601: (duration: string, options?: HeaderIso8601OptionalParams) => Promise; + default: (duration: string, options?: HeaderDefaultOptionalParams) => Promise; } export declare interface Int32SecondsDurationProperty { @@ -84,12 +84,12 @@ export declare interface PropertyIso8601OptionalParams extends OperationOptions } export declare interface PropertyOperations { - default: (body: DefaultDurationProperty, options?: PropertyDefaultOptionalParams) => Promise; - iso8601: (body: ISO8601DurationProperty, options?: PropertyIso8601OptionalParams) => Promise; - int32Seconds: (body: Int32SecondsDurationProperty, options?: PropertyInt32SecondsOptionalParams) => Promise; - floatSeconds: (body: FloatSecondsDurationProperty, options?: PropertyFloatSecondsOptionalParams) => Promise; - float64Seconds: (body: Float64SecondsDurationProperty, options?: PropertyFloat64SecondsOptionalParams) => Promise; floatSecondsArray: (body: FloatSecondsDurationArrayProperty, options?: PropertyFloatSecondsArrayOptionalParams) => Promise; + float64Seconds: (body: Float64SecondsDurationProperty, options?: PropertyFloat64SecondsOptionalParams) => Promise; + floatSeconds: (body: FloatSecondsDurationProperty, options?: PropertyFloatSecondsOptionalParams) => Promise; + int32Seconds: (body: Int32SecondsDurationProperty, options?: PropertyInt32SecondsOptionalParams) => Promise; + iso8601: (body: ISO8601DurationProperty, options?: PropertyIso8601OptionalParams) => Promise; + default: (body: DefaultDurationProperty, options?: PropertyDefaultOptionalParams) => Promise; } export declare interface QueryDefaultOptionalParams extends OperationOptions { @@ -111,12 +111,12 @@ export declare interface QueryIso8601OptionalParams extends OperationOptions { } export declare interface QueryOperations { - default: (input: string, options?: QueryDefaultOptionalParams) => Promise; - iso8601: (input: string, options?: QueryIso8601OptionalParams) => Promise; - int32Seconds: (input: number, options?: QueryInt32SecondsOptionalParams) => Promise; - floatSeconds: (input: number, options?: QueryFloatSecondsOptionalParams) => Promise; - float64Seconds: (input: number, options?: QueryFloat64SecondsOptionalParams) => Promise; int32SecondsArray: (input: number[], options?: QueryInt32SecondsArrayOptionalParams) => Promise; + float64Seconds: (input: number, options?: QueryFloat64SecondsOptionalParams) => Promise; + floatSeconds: (input: number, options?: QueryFloatSecondsOptionalParams) => Promise; + int32Seconds: (input: number, options?: QueryInt32SecondsOptionalParams) => Promise; + iso8601: (input: string, options?: QueryIso8601OptionalParams) => Promise; + default: (input: string, options?: QueryDefaultOptionalParams) => Promise; } export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/encode/numeric/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/encode/numeric/src/index.d.ts index 4bf5b483f1..287846bfd0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/encode/numeric/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/encode/numeric/src/index.d.ts @@ -13,9 +13,9 @@ export declare interface NumericClientOptionalParams extends ClientOptions { } export declare interface PropertyOperations { - safeintAsString: (value: SafeintAsStringProperty, options?: PropertySafeintAsStringOptionalParams) => Promise; - uint32AsStringOptional: (value: Uint32AsStringProperty, options?: PropertyUint32AsStringOptionalOptionalParams) => Promise; uint8AsString: (value: Uint8AsStringProperty, options?: PropertyUint8AsStringOptionalParams) => Promise; + uint32AsStringOptional: (value: Uint32AsStringProperty, options?: PropertyUint32AsStringOptionalOptionalParams) => Promise; + safeintAsString: (value: SafeintAsStringProperty, options?: PropertySafeintAsStringOptionalParams) => Promise; } export declare interface PropertySafeintAsStringOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/basic/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/basic/src/index.d.ts index 03d399a782..819ac7181b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/basic/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/basic/src/index.d.ts @@ -6,8 +6,8 @@ export declare class BasicClient { private _client; readonly pipeline: Pipeline; constructor(options?: BasicClientOptionalParams); - readonly explicitBody: ExplicitBodyOperations; readonly implicitBody: ImplicitBodyOperations; + readonly explicitBody: ExplicitBodyOperations; } export declare interface BasicClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/body-optionality/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/body-optionality/src/index.d.ts index 9b8897e6d2..666db44d14 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/body-optionality/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/body-optionality/src/index.d.ts @@ -10,9 +10,9 @@ export declare class BodyOptionalityClient { private _client; readonly pipeline: Pipeline; constructor(options?: BodyOptionalityClientOptionalParams); - requiredExplicit(body: BodyModel, options?: RequiredExplicitOptionalParams): Promise; - requiredImplicit(name: string, options?: RequiredImplicitOptionalParams): Promise; readonly optionalExplicit: OptionalExplicitOperations; + requiredImplicit(name: string, options?: RequiredImplicitOptionalParams): Promise; + requiredExplicit(body: BodyModel, options?: RequiredExplicitOptionalParams): Promise; } export declare interface BodyOptionalityClientOptionalParams extends ClientOptions { @@ -23,8 +23,8 @@ export declare interface OptionalExplicitOmitOptionalParams extends OperationOpt } export declare interface OptionalExplicitOperations { - set: (options?: OptionalExplicitSetOptionalParams) => Promise; omit: (options?: OptionalExplicitOmitOptionalParams) => Promise; + set: (options?: OptionalExplicitSetOptionalParams) => Promise; } export declare interface OptionalExplicitSetOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/index.d.ts index c2945c0caf..4de5b37875 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/collection-format/src/index.d.ts @@ -6,8 +6,8 @@ export declare class CollectionFormatClient { private _client; readonly pipeline: Pipeline; constructor(options?: CollectionFormatClientOptionalParams); - readonly query: QueryOperations; readonly header: HeaderOperations; + readonly query: QueryOperations; } export declare interface CollectionFormatClientOptionalParams extends ClientOptions { @@ -27,11 +27,11 @@ export declare interface QueryMultiOptionalParams extends OperationOptions { } export declare interface QueryOperations { - multi: (colors: string[], options?: QueryMultiOptionalParams) => Promise; - ssv: (colors: string[], options?: QuerySsvOptionalParams) => Promise; - tsv: (colors: string[], options?: QueryTsvOptionalParams) => Promise; - pipes: (colors: string[], options?: QueryPipesOptionalParams) => Promise; csv: (colors: string[], options?: QueryCsvOptionalParams) => Promise; + pipes: (colors: string[], options?: QueryPipesOptionalParams) => Promise; + tsv: (colors: string[], options?: QueryTsvOptionalParams) => Promise; + ssv: (colors: string[], options?: QuerySsvOptionalParams) => Promise; + multi: (colors: string[], options?: QueryMultiOptionalParams) => Promise; } export declare interface QueryPipesOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts index 3a4ec6f23f..c57d6c8d7f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/parameters/spread/src/index.d.ts @@ -3,11 +3,11 @@ import { OperationOptions } from '@azure-rest/core-client'; import { Pipeline } from '@azure/core-rest-pipeline'; export declare interface AliasOperations { - spreadAsRequestBody: (name: string, options?: AliasSpreadAsRequestBodyOptionalParams) => Promise; - spreadParameterWithInnerModel: (id: string, xMsTestHeader: string, name: string, options?: AliasSpreadParameterWithInnerModelOptionalParams) => Promise; - spreadAsRequestParameter: (id: string, xMsTestHeader: string, name: string, options?: AliasSpreadAsRequestParameterOptionalParams) => Promise; + spreadParameterWithInnerAlias: (id: string, name: string, age: number, xMsTestHeader: string, options?: AliasSpreadParameterWithInnerAliasOptionalParams) => Promise; spreadWithMultipleParameters: (id: string, xMsTestHeader: string, requiredString: string, requiredIntList: number[], options?: AliasSpreadWithMultipleParametersOptionalParams) => Promise; - spreadParameterWithInnerAlias: (id: string, xMsTestHeader: string, name: string, age: number, options?: AliasSpreadParameterWithInnerAliasOptionalParams) => Promise; + spreadAsRequestParameter: (id: string, xMsTestHeader: string, name: string, options?: AliasSpreadAsRequestParameterOptionalParams) => Promise; + spreadParameterWithInnerModel: (id: string, name: string, xMsTestHeader: string, options?: AliasSpreadParameterWithInnerModelOptionalParams) => Promise; + spreadAsRequestBody: (name: string, options?: AliasSpreadAsRequestBodyOptionalParams) => Promise; } export declare interface AliasSpreadAsRequestBodyOptionalParams extends OperationOptions { @@ -32,11 +32,11 @@ export declare interface BodyParameter { } export declare interface ModelOperations { - spreadAsRequestBody: (name: string, options?: ModelSpreadAsRequestBodyOptionalParams) => Promise; - spreadCompositeRequestOnlyWithBody: (body: BodyParameter, options?: ModelSpreadCompositeRequestOnlyWithBodyOptionalParams) => Promise; - spreadCompositeRequestWithoutBody: (name: string, testHeader: string, options?: ModelSpreadCompositeRequestWithoutBodyOptionalParams) => Promise; - spreadCompositeRequest: (name: string, testHeader: string, body: BodyParameter, options?: ModelSpreadCompositeRequestOptionalParams) => Promise; spreadCompositeRequestMix: (name: string, testHeader: string, prop: string, options?: ModelSpreadCompositeRequestMixOptionalParams) => Promise; + spreadCompositeRequest: (name: string, testHeader: string, body: BodyParameter, options?: ModelSpreadCompositeRequestOptionalParams) => Promise; + spreadCompositeRequestWithoutBody: (name: string, testHeader: string, options?: ModelSpreadCompositeRequestWithoutBodyOptionalParams) => Promise; + spreadCompositeRequestOnlyWithBody: (body: BodyParameter, options?: ModelSpreadCompositeRequestOnlyWithBodyOptionalParams) => Promise; + spreadAsRequestBody: (name: string, options?: ModelSpreadAsRequestBodyOptionalParams) => Promise; } export declare interface ModelSpreadAsRequestBodyOptionalParams extends OperationOptions { @@ -58,8 +58,8 @@ export declare class SpreadClient { private _client; readonly pipeline: Pipeline; constructor(options?: SpreadClientOptionalParams); - readonly model: ModelOperations; readonly alias: AliasOperations; + readonly model: ModelOperations; } export declare interface SpreadClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/content-negotiation/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/content-negotiation/src/index.d.ts index d7a36912a6..a1bac61e87 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/content-negotiation/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/content-negotiation/src/index.d.ts @@ -6,24 +6,22 @@ export declare class ContentNegotiationClient { private _client; readonly pipeline: Pipeline; constructor(options?: ContentNegotiationClientOptionalParams); - readonly sameBody: SameBodyOperations; readonly differentBody: DifferentBodyOperations; + readonly sameBody: SameBodyOperations; } export declare interface ContentNegotiationClientOptionalParams extends ClientOptions { } export declare interface DifferentBodyGetAvatarAsJsonOptionalParams extends OperationOptions { - accept?: "application/json"; } export declare interface DifferentBodyGetAvatarAsPngOptionalParams extends OperationOptions { - accept?: "image/png"; } export declare interface DifferentBodyOperations { - getAvatarAsPng: (options?: DifferentBodyGetAvatarAsPngOptionalParams) => Promise; getAvatarAsJson: (options?: DifferentBodyGetAvatarAsJsonOptionalParams) => Promise; + getAvatarAsPng: (options?: DifferentBodyGetAvatarAsPngOptionalParams) => Promise; } export declare interface PngImageAsJson { @@ -31,16 +29,14 @@ export declare interface PngImageAsJson { } export declare interface SameBodyGetAvatarAsJpegOptionalParams extends OperationOptions { - accept?: "image/jpeg"; } export declare interface SameBodyGetAvatarAsPngOptionalParams extends OperationOptions { - accept?: "image/png"; } export declare interface SameBodyOperations { - getAvatarAsPng: (options?: SameBodyGetAvatarAsPngOptionalParams) => Promise; getAvatarAsJpeg: (options?: SameBodyGetAvatarAsJpegOptionalParams) => Promise; + getAvatarAsPng: (options?: SameBodyGetAvatarAsPngOptionalParams) => Promise; } export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/media-type/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/media-type/src/index.d.ts index a7f35d5855..7539463102 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/media-type/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/media-type/src/index.d.ts @@ -19,18 +19,16 @@ export declare interface StringBodyGetAsTextOptionalParams extends OperationOpti } export declare interface StringBodyOperations { - sendAsText: (text: string, options?: StringBodySendAsTextOptionalParams) => Promise; - getAsText: (options?: StringBodyGetAsTextOptionalParams) => Promise; - sendAsJson: (text: string, options?: StringBodySendAsJsonOptionalParams) => Promise; getAsJson: (options?: StringBodyGetAsJsonOptionalParams) => Promise; + sendAsJson: (text: string, options?: StringBodySendAsJsonOptionalParams) => Promise; + getAsText: (options?: StringBodyGetAsTextOptionalParams) => Promise; + sendAsText: (text: string, options?: StringBodySendAsTextOptionalParams) => Promise; } export declare interface StringBodySendAsJsonOptionalParams extends OperationOptions { - contentType?: string; } export declare interface StringBodySendAsTextOptionalParams extends OperationOptions { - contentType?: string; } export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts index 9297bdfdfa..2e7fdbb259 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-main/src/index.d.ts @@ -27,10 +27,10 @@ export declare class ResiliencyServiceDrivenClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, serviceDeploymentVersion: string, options?: ResiliencyServiceDrivenClientOptionalParams); - addOperation(options?: AddOperationOptionalParams): Promise; - fromNone(options?: FromNoneOptionalParams): Promise; - fromOneRequired(parameter: string, options?: FromOneRequiredOptionalParams): Promise; fromOneOptional(options?: FromOneOptionalOptionalParams): Promise; + fromOneRequired(parameter: string, options?: FromOneRequiredOptionalParams): Promise; + fromNone(options?: FromNoneOptionalParams): Promise; + addOperation(options?: AddOperationOptionalParams): Promise; } export declare interface ResiliencyServiceDrivenClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts index efb2c9892a..537bead151 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/resiliency/srv-driven-old/src/index.d.ts @@ -20,9 +20,9 @@ export declare class ResiliencyServiceDrivenClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, serviceDeploymentVersion: string, options?: ResiliencyServiceDrivenClientOptionalParams); - fromNone(options?: FromNoneOptionalParams): Promise; - fromOneRequired(parameter: string, options?: FromOneRequiredOptionalParams): Promise; fromOneOptional(options?: FromOneOptionalOptionalParams): Promise; + fromOneRequired(parameter: string, options?: FromOneRequiredOptionalParams): Promise; + fromNone(options?: FromNoneOptionalParams): Promise; } export declare interface ResiliencyServiceDrivenClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/serialization/encoded-name/json/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/serialization/encoded-name/json/src/index.d.ts index af115d75a9..4898f205ec 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/serialization/encoded-name/json/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/serialization/encoded-name/json/src/index.d.ts @@ -9,8 +9,8 @@ export declare class JsonClient { private _client; readonly pipeline: Pipeline; constructor(options?: JsonClientOptionalParams); - send(body: JsonEncodedNameModel, options?: SendOptionalParams): Promise; get(options?: GetOptionalParams): Promise; + send(body: JsonEncodedNameModel, options?: SendOptionalParams): Promise; } export declare interface JsonClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts index b26635ddeb..90f3fe2998 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/server/path/multiple/src/index.d.ts @@ -6,8 +6,8 @@ export declare class MultipleClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, options?: MultipleClientOptionalParams); - noOperationParams(options?: NoOperationParamsOptionalParams): Promise; withOperationPathParam(keyword: string, options?: WithOperationPathParamOptionalParams): Promise; + noOperationParams(options?: NoOperationParamsOptionalParams): Promise; } export declare interface MultipleClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/server/versions/not-versioned/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/server/versions/not-versioned/src/index.d.ts index 97a115d65b..00b750b873 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/server/versions/not-versioned/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/server/versions/not-versioned/src/index.d.ts @@ -6,9 +6,9 @@ export declare class NotVersionedClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, options?: NotVersionedClientOptionalParams); - withoutApiVersion(options?: WithoutApiVersionOptionalParams): Promise; - withQueryApiVersion(apiVersion: string, options?: WithQueryApiVersionOptionalParams): Promise; withPathApiVersion(apiVersion: string, options?: WithPathApiVersionOptionalParams): Promise; + withQueryApiVersion(apiVersion: string, options?: WithQueryApiVersionOptionalParams): Promise; + withoutApiVersion(options?: WithoutApiVersionOptionalParams): Promise; } export declare interface NotVersionedClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts index f0a0256c04..b2be835076 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/server/versions/versioned/src/index.d.ts @@ -11,10 +11,10 @@ export declare class VersionedClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, options?: VersionedClientOptionalParams); - withoutApiVersion(options?: WithoutApiVersionOptionalParams): Promise; - withQueryApiVersion(options?: WithQueryApiVersionOptionalParams): Promise; - withPathApiVersion(apiVersion: string, options?: WithPathApiVersionOptionalParams): Promise; withQueryOldApiVersion(options?: WithQueryOldApiVersionOptionalParams): Promise; + withPathApiVersion(options?: WithPathApiVersionOptionalParams): Promise; + withQueryApiVersion(options?: WithQueryApiVersionOptionalParams): Promise; + withoutApiVersion(options?: WithoutApiVersionOptionalParams): Promise; } export declare interface VersionedClientOptionalParams extends ClientOptions { @@ -28,11 +28,9 @@ export declare interface WithPathApiVersionOptionalParams extends OperationOptio } export declare interface WithQueryApiVersionOptionalParams extends OperationOptions { - apiVersion?: string; } export declare interface WithQueryOldApiVersionOptionalParams extends OperationOptions { - apiVersion?: string; } export { } diff --git a/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts index dce6b783c4..1cdcb34aa9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/special-words/src/index.d.ts @@ -106,39 +106,39 @@ export declare interface ModelPropertiesSameAsModelOptionalParams extends Operat } export declare interface ModelsOperations { - withAnd: (body: And, options?: ModelsWithAndOptionalParams) => Promise; - withAs: (body: As, options?: ModelsWithAsOptionalParams) => Promise; - withAssert: (body: Assert, options?: ModelsWithAssertOptionalParams) => Promise; - withAsync: (body: Async, options?: ModelsWithAsyncOptionalParams) => Promise; - withAwait: (body: Await, options?: ModelsWithAwaitOptionalParams) => Promise; - withBreak: (body: Break, options?: ModelsWithBreakOptionalParams) => Promise; - withClass: (body: Class, options?: ModelsWithClassOptionalParams) => Promise; - withConstructor: (body: Constructor, options?: ModelsWithConstructorOptionalParams) => Promise; - withContinue: (body: Continue, options?: ModelsWithContinueOptionalParams) => Promise; - withDef: (body: Def, options?: ModelsWithDefOptionalParams) => Promise; - withDel: (body: Del, options?: ModelsWithDelOptionalParams) => Promise; - withElif: (body: Elif, options?: ModelsWithElifOptionalParams) => Promise; - withElse: (body: Else, options?: ModelsWithElseOptionalParams) => Promise; - withExcept: (body: Except, options?: ModelsWithExceptOptionalParams) => Promise; - withExec: (body: Exec, options?: ModelsWithExecOptionalParams) => Promise; - withFinally: (body: Finally, options?: ModelsWithFinallyOptionalParams) => Promise; - withFor: (body: For, options?: ModelsWithForOptionalParams) => Promise; - withFrom: (body: From, options?: ModelsWithFromOptionalParams) => Promise; - withGlobal: (body: GlobalModel, options?: ModelsWithGlobalOptionalParams) => Promise; - withIf: (body: If, options?: ModelsWithIfOptionalParams) => Promise; - withImport: (body: Import, options?: ModelsWithImportOptionalParams) => Promise; - withIn: (body: In, options?: ModelsWithInOptionalParams) => Promise; - withIs: (body: Is, options?: ModelsWithIsOptionalParams) => Promise; - withLambda: (body: Lambda, options?: ModelsWithLambdaOptionalParams) => Promise; - withNot: (body: Not, options?: ModelsWithNotOptionalParams) => Promise; - withOr: (body: Or, options?: ModelsWithOrOptionalParams) => Promise; - withPass: (body: Pass, options?: ModelsWithPassOptionalParams) => Promise; - withRaise: (body: Raise, options?: ModelsWithRaiseOptionalParams) => Promise; - withReturn: (body: Return, options?: ModelsWithReturnOptionalParams) => Promise; - withTry: (body: Try, options?: ModelsWithTryOptionalParams) => Promise; - withWhile: (body: While, options?: ModelsWithWhileOptionalParams) => Promise; - withWith: (body: With, options?: ModelsWithWithOptionalParams) => Promise; withYield: (body: Yield, options?: ModelsWithYieldOptionalParams) => Promise; + withWith: (body: With, options?: ModelsWithWithOptionalParams) => Promise; + withWhile: (body: While, options?: ModelsWithWhileOptionalParams) => Promise; + withTry: (body: Try, options?: ModelsWithTryOptionalParams) => Promise; + withReturn: (body: Return, options?: ModelsWithReturnOptionalParams) => Promise; + withRaise: (body: Raise, options?: ModelsWithRaiseOptionalParams) => Promise; + withPass: (body: Pass, options?: ModelsWithPassOptionalParams) => Promise; + withOr: (body: Or, options?: ModelsWithOrOptionalParams) => Promise; + withNot: (body: Not, options?: ModelsWithNotOptionalParams) => Promise; + withLambda: (body: Lambda, options?: ModelsWithLambdaOptionalParams) => Promise; + withIs: (body: Is, options?: ModelsWithIsOptionalParams) => Promise; + withIn: (body: In, options?: ModelsWithInOptionalParams) => Promise; + withImport: (body: Import, options?: ModelsWithImportOptionalParams) => Promise; + withIf: (body: If, options?: ModelsWithIfOptionalParams) => Promise; + withGlobal: (body: GlobalModel, options?: ModelsWithGlobalOptionalParams) => Promise; + withFrom: (body: From, options?: ModelsWithFromOptionalParams) => Promise; + withFor: (body: For, options?: ModelsWithForOptionalParams) => Promise; + withFinally: (body: Finally, options?: ModelsWithFinallyOptionalParams) => Promise; + withExec: (body: Exec, options?: ModelsWithExecOptionalParams) => Promise; + withExcept: (body: Except, options?: ModelsWithExceptOptionalParams) => Promise; + withElse: (body: Else, options?: ModelsWithElseOptionalParams) => Promise; + withElif: (body: Elif, options?: ModelsWithElifOptionalParams) => Promise; + withDel: (body: Del, options?: ModelsWithDelOptionalParams) => Promise; + withDef: (body: Def, options?: ModelsWithDefOptionalParams) => Promise; + withContinue: (body: Continue, options?: ModelsWithContinueOptionalParams) => Promise; + withConstructor: (body: Constructor, options?: ModelsWithConstructorOptionalParams) => Promise; + withClass: (body: Class, options?: ModelsWithClassOptionalParams) => Promise; + withBreak: (body: Break, options?: ModelsWithBreakOptionalParams) => Promise; + withAwait: (body: Await, options?: ModelsWithAwaitOptionalParams) => Promise; + withAsync: (body: Async, options?: ModelsWithAsyncOptionalParams) => Promise; + withAssert: (body: Assert, options?: ModelsWithAssertOptionalParams) => Promise; + withAs: (body: As, options?: ModelsWithAsOptionalParams) => Promise; + withAnd: (body: And, options?: ModelsWithAndOptionalParams) => Promise; } export declare interface ModelsWithAndOptionalParams extends OperationOptions { @@ -320,39 +320,39 @@ export declare interface OperationsNotOptionalParams extends OperationOptions { } export declare interface OperationsOperations { - and: (options?: OperationsAndOptionalParams) => Promise; - as: (options?: OperationsAsOptionalParams) => Promise; - assert: (options?: OperationsAssertOptionalParams) => Promise; - async: (options?: OperationsAsyncOptionalParams) => Promise; - await: (options?: OperationsAwaitOptionalParams) => Promise; - break: (options?: OperationsBreakOptionalParams) => Promise; - class: (options?: OperationsClassOptionalParams) => Promise; - constructor: (options?: OperationsConstructorOptionalParams) => Promise; - continue: (options?: OperationsContinueOptionalParams) => Promise; - def: (options?: OperationsDefOptionalParams) => Promise; - del: (options?: OperationsDelOptionalParams) => Promise; - elif: (options?: OperationsElifOptionalParams) => Promise; - else: (options?: OperationsElseOptionalParams) => Promise; - except: (options?: OperationsExceptOptionalParams) => Promise; - exec: (options?: OperationsExecOptionalParams) => Promise; - finally: (options?: OperationsFinallyOptionalParams) => Promise; - for: (options?: OperationsForOptionalParams) => Promise; - from: (options?: OperationsFromOptionalParams) => Promise; - global: (options?: OperationsGlobalOptionalParams) => Promise; - if: (options?: OperationsIfOptionalParams) => Promise; - import: (options?: OperationsImportOptionalParams) => Promise; - in: (options?: OperationsInOptionalParams) => Promise; - is: (options?: OperationsIsOptionalParams) => Promise; - lambda: (options?: OperationsLambdaOptionalParams) => Promise; - not: (options?: OperationsNotOptionalParams) => Promise; - or: (options?: OperationsOrOptionalParams) => Promise; - pass: (options?: OperationsPassOptionalParams) => Promise; - raise: (options?: OperationsRaiseOptionalParams) => Promise; - return: (options?: OperationsReturnOptionalParams) => Promise; - try: (options?: OperationsTryOptionalParams) => Promise; - while: (options?: OperationsWhileOptionalParams) => Promise; - with: (options?: OperationsWithOptionalParams) => Promise; yield: (options?: OperationsYieldOptionalParams) => Promise; + with: (options?: OperationsWithOptionalParams) => Promise; + while: (options?: OperationsWhileOptionalParams) => Promise; + try: (options?: OperationsTryOptionalParams) => Promise; + return: (options?: OperationsReturnOptionalParams) => Promise; + raise: (options?: OperationsRaiseOptionalParams) => Promise; + pass: (options?: OperationsPassOptionalParams) => Promise; + or: (options?: OperationsOrOptionalParams) => Promise; + not: (options?: OperationsNotOptionalParams) => Promise; + lambda: (options?: OperationsLambdaOptionalParams) => Promise; + is: (options?: OperationsIsOptionalParams) => Promise; + in: (options?: OperationsInOptionalParams) => Promise; + import: (options?: OperationsImportOptionalParams) => Promise; + if: (options?: OperationsIfOptionalParams) => Promise; + global: (options?: OperationsGlobalOptionalParams) => Promise; + from: (options?: OperationsFromOptionalParams) => Promise; + for: (options?: OperationsForOptionalParams) => Promise; + finally: (options?: OperationsFinallyOptionalParams) => Promise; + exec: (options?: OperationsExecOptionalParams) => Promise; + except: (options?: OperationsExceptOptionalParams) => Promise; + else: (options?: OperationsElseOptionalParams) => Promise; + elif: (options?: OperationsElifOptionalParams) => Promise; + del: (options?: OperationsDelOptionalParams) => Promise; + def: (options?: OperationsDefOptionalParams) => Promise; + continue: (options?: OperationsContinueOptionalParams) => Promise; + constructor: (options?: OperationsConstructorOptionalParams) => Promise; + class: (options?: OperationsClassOptionalParams) => Promise; + break: (options?: OperationsBreakOptionalParams) => Promise; + await: (options?: OperationsAwaitOptionalParams) => Promise; + async: (options?: OperationsAsyncOptionalParams) => Promise; + assert: (options?: OperationsAssertOptionalParams) => Promise; + as: (options?: OperationsAsOptionalParams) => Promise; + and: (options?: OperationsAndOptionalParams) => Promise; } export declare interface OperationsOrOptionalParams extends OperationOptions { @@ -384,40 +384,40 @@ export declare interface Or { } export declare interface ParametersOperations { - withAnd: (and: string, options?: ParametersWithAndOptionalParams) => Promise; - withAs: (asParam: string, options?: ParametersWithAsOptionalParams) => Promise; - withAssert: (assertParam: string, options?: ParametersWithAssertOptionalParams) => Promise; - withAsync: (asyncParam: string, options?: ParametersWithAsyncOptionalParams) => Promise; - withAwait: (awaitParam: string, options?: ParametersWithAwaitOptionalParams) => Promise; - withBreak: (breakParam: string, options?: ParametersWithBreakOptionalParams) => Promise; - withClass: (classParam: string, options?: ParametersWithClassOptionalParams) => Promise; - withConstructor: (constructorParam: string, options?: ParametersWithConstructorOptionalParams) => Promise; - withContinue: (continueParam: string, options?: ParametersWithContinueOptionalParams) => Promise; - withDef: (def: string, options?: ParametersWithDefOptionalParams) => Promise; - withDel: (del: string, options?: ParametersWithDelOptionalParams) => Promise; - withElif: (elif: string, options?: ParametersWithElifOptionalParams) => Promise; - withElse: (elseParam: string, options?: ParametersWithElseOptionalParams) => Promise; - withExcept: (except: string, options?: ParametersWithExceptOptionalParams) => Promise; - withExec: (exec: string, options?: ParametersWithExecOptionalParams) => Promise; - withFinally: (finallyParam: string, options?: ParametersWithFinallyOptionalParams) => Promise; - withFor: (forParam: string, options?: ParametersWithForOptionalParams) => Promise; - withFrom: (fromParam: string, options?: ParametersWithFromOptionalParams) => Promise; - withGlobal: (global: string, options?: ParametersWithGlobalOptionalParams) => Promise; - withIf: (ifParam: string, options?: ParametersWithIfOptionalParams) => Promise; - withImport: (importParam: string, options?: ParametersWithImportOptionalParams) => Promise; - withIn: (inParam: string, options?: ParametersWithInOptionalParams) => Promise; - withIs: (is: string, options?: ParametersWithIsOptionalParams) => Promise; - withLambda: (lambda: string, options?: ParametersWithLambdaOptionalParams) => Promise; - withNot: (not: string, options?: ParametersWithNotOptionalParams) => Promise; - withOr: (or: string, options?: ParametersWithOrOptionalParams) => Promise; - withPass: (pass: string, options?: ParametersWithPassOptionalParams) => Promise; - withRaise: (raise: string, options?: ParametersWithRaiseOptionalParams) => Promise; - withReturn: (returnParam: string, options?: ParametersWithReturnOptionalParams) => Promise; - withTry: (tryParam: string, options?: ParametersWithTryOptionalParams) => Promise; - withWhile: (whileParam: string, options?: ParametersWithWhileOptionalParams) => Promise; - withWith: (withParam: string, options?: ParametersWithWithOptionalParams) => Promise; - withYield: (yieldParam: string, options?: ParametersWithYieldOptionalParams) => Promise; withCancellationToken: (cancellationToken: string, options?: ParametersWithCancellationTokenOptionalParams) => Promise; + withYield: (yieldParam: string, options?: ParametersWithYieldOptionalParams) => Promise; + withWith: (withParam: string, options?: ParametersWithWithOptionalParams) => Promise; + withWhile: (whileParam: string, options?: ParametersWithWhileOptionalParams) => Promise; + withTry: (tryParam: string, options?: ParametersWithTryOptionalParams) => Promise; + withReturn: (returnParam: string, options?: ParametersWithReturnOptionalParams) => Promise; + withRaise: (raise: string, options?: ParametersWithRaiseOptionalParams) => Promise; + withPass: (pass: string, options?: ParametersWithPassOptionalParams) => Promise; + withOr: (or: string, options?: ParametersWithOrOptionalParams) => Promise; + withNot: (not: string, options?: ParametersWithNotOptionalParams) => Promise; + withLambda: (lambda: string, options?: ParametersWithLambdaOptionalParams) => Promise; + withIs: (is: string, options?: ParametersWithIsOptionalParams) => Promise; + withIn: (inParam: string, options?: ParametersWithInOptionalParams) => Promise; + withImport: (importParam: string, options?: ParametersWithImportOptionalParams) => Promise; + withIf: (ifParam: string, options?: ParametersWithIfOptionalParams) => Promise; + withGlobal: (global: string, options?: ParametersWithGlobalOptionalParams) => Promise; + withFrom: (fromParam: string, options?: ParametersWithFromOptionalParams) => Promise; + withFor: (forParam: string, options?: ParametersWithForOptionalParams) => Promise; + withFinally: (finallyParam: string, options?: ParametersWithFinallyOptionalParams) => Promise; + withExec: (exec: string, options?: ParametersWithExecOptionalParams) => Promise; + withExcept: (except: string, options?: ParametersWithExceptOptionalParams) => Promise; + withElse: (elseParam: string, options?: ParametersWithElseOptionalParams) => Promise; + withElif: (elif: string, options?: ParametersWithElifOptionalParams) => Promise; + withDel: (del: string, options?: ParametersWithDelOptionalParams) => Promise; + withDef: (def: string, options?: ParametersWithDefOptionalParams) => Promise; + withContinue: (continueParam: string, options?: ParametersWithContinueOptionalParams) => Promise; + withConstructor: (constructorParam: string, options?: ParametersWithConstructorOptionalParams) => Promise; + withClass: (classParam: string, options?: ParametersWithClassOptionalParams) => Promise; + withBreak: (breakParam: string, options?: ParametersWithBreakOptionalParams) => Promise; + withAwait: (awaitParam: string, options?: ParametersWithAwaitOptionalParams) => Promise; + withAsync: (asyncParam: string, options?: ParametersWithAsyncOptionalParams) => Promise; + withAssert: (assertParam: string, options?: ParametersWithAssertOptionalParams) => Promise; + withAs: (asParam: string, options?: ParametersWithAsOptionalParams) => Promise; + withAnd: (and: string, options?: ParametersWithAndOptionalParams) => Promise; } export declare interface ParametersWithAndOptionalParams extends OperationOptions { @@ -542,10 +542,10 @@ export declare class SpecialWordsClient { private _client; readonly pipeline: Pipeline; constructor(options?: SpecialWordsClientOptionalParams); - readonly models: ModelsOperations; - readonly modelProperties: ModelPropertiesOperations; - readonly operations: OperationsOperations; readonly parameters: ParametersOperations; + readonly operations: OperationsOperations; + readonly modelProperties: ModelPropertiesOperations; + readonly models: ModelsOperations; } export declare interface SpecialWordsClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/array/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/array/src/index.d.ts index ad38a430d7..6cbb0f1789 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/array/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/array/src/index.d.ts @@ -6,20 +6,20 @@ export declare class ArrayClient { private _client; readonly pipeline: Pipeline; constructor(options?: ArrayClientOptionalParams); - readonly int32Value: Int32ValueOperations; - readonly int64Value: Int64ValueOperations; - readonly booleanValue: BooleanValueOperations; - readonly stringValue: StringValueOperations; - readonly float32Value: Float32ValueOperations; - readonly datetimeValue: DatetimeValueOperations; - readonly durationValue: DurationValueOperations; - readonly unknownValue: UnknownValueOperations; - readonly modelValue: ModelValueOperations; - readonly nullableFloatValue: NullableFloatValueOperations; - readonly nullableInt32Value: NullableInt32ValueOperations; - readonly nullableBooleanValue: NullableBooleanValueOperations; - readonly nullableStringValue: NullableStringValueOperations; readonly nullableModelValue: NullableModelValueOperations; + readonly nullableStringValue: NullableStringValueOperations; + readonly nullableBooleanValue: NullableBooleanValueOperations; + readonly nullableInt32Value: NullableInt32ValueOperations; + readonly nullableFloatValue: NullableFloatValueOperations; + readonly modelValue: ModelValueOperations; + readonly unknownValue: UnknownValueOperations; + readonly durationValue: DurationValueOperations; + readonly datetimeValue: DatetimeValueOperations; + readonly float32Value: Float32ValueOperations; + readonly stringValue: StringValueOperations; + readonly booleanValue: BooleanValueOperations; + readonly int64Value: Int64ValueOperations; + readonly int32Value: Int32ValueOperations; } export declare interface ArrayClientOptionalParams extends ClientOptions { @@ -29,8 +29,8 @@ export declare interface BooleanValueGetOptionalParams extends OperationOptions } export declare interface BooleanValueOperations { - get: (options?: BooleanValueGetOptionalParams) => Promise; put: (body: boolean[], options?: BooleanValuePutOptionalParams) => Promise; + get: (options?: BooleanValueGetOptionalParams) => Promise; } export declare interface BooleanValuePutOptionalParams extends OperationOptions { @@ -40,8 +40,8 @@ export declare interface DatetimeValueGetOptionalParams extends OperationOptions } export declare interface DatetimeValueOperations { - get: (options?: DatetimeValueGetOptionalParams) => Promise; put: (body: Date[], options?: DatetimeValuePutOptionalParams) => Promise; + get: (options?: DatetimeValueGetOptionalParams) => Promise; } export declare interface DatetimeValuePutOptionalParams extends OperationOptions { @@ -51,8 +51,8 @@ export declare interface DurationValueGetOptionalParams extends OperationOptions } export declare interface DurationValueOperations { - get: (options?: DurationValueGetOptionalParams) => Promise; put: (body: string[], options?: DurationValuePutOptionalParams) => Promise; + get: (options?: DurationValueGetOptionalParams) => Promise; } export declare interface DurationValuePutOptionalParams extends OperationOptions { @@ -62,8 +62,8 @@ export declare interface Float32ValueGetOptionalParams extends OperationOptions } export declare interface Float32ValueOperations { - get: (options?: Float32ValueGetOptionalParams) => Promise; put: (body: number[], options?: Float32ValuePutOptionalParams) => Promise; + get: (options?: Float32ValueGetOptionalParams) => Promise; } export declare interface Float32ValuePutOptionalParams extends OperationOptions { @@ -78,8 +78,8 @@ export declare interface Int32ValueGetOptionalParams extends OperationOptions { } export declare interface Int32ValueOperations { - get: (options?: Int32ValueGetOptionalParams) => Promise; put: (body: number[], options?: Int32ValuePutOptionalParams) => Promise; + get: (options?: Int32ValueGetOptionalParams) => Promise; } export declare interface Int32ValuePutOptionalParams extends OperationOptions { @@ -89,8 +89,8 @@ export declare interface Int64ValueGetOptionalParams extends OperationOptions { } export declare interface Int64ValueOperations { - get: (options?: Int64ValueGetOptionalParams) => Promise; put: (body: number[], options?: Int64ValuePutOptionalParams) => Promise; + get: (options?: Int64ValueGetOptionalParams) => Promise; } export declare interface Int64ValuePutOptionalParams extends OperationOptions { @@ -100,8 +100,8 @@ export declare interface ModelValueGetOptionalParams extends OperationOptions { } export declare interface ModelValueOperations { - get: (options?: ModelValueGetOptionalParams) => Promise; put: (body: InnerModel[], options?: ModelValuePutOptionalParams) => Promise; + get: (options?: ModelValueGetOptionalParams) => Promise; } export declare interface ModelValuePutOptionalParams extends OperationOptions { @@ -111,8 +111,8 @@ export declare interface NullableBooleanValueGetOptionalParams extends Operation } export declare interface NullableBooleanValueOperations { - get: (options?: NullableBooleanValueGetOptionalParams) => Promise<(boolean | null)[]>; put: (body: (boolean | null)[], options?: NullableBooleanValuePutOptionalParams) => Promise; + get: (options?: NullableBooleanValueGetOptionalParams) => Promise<(boolean | null)[]>; } export declare interface NullableBooleanValuePutOptionalParams extends OperationOptions { @@ -122,8 +122,8 @@ export declare interface NullableFloatValueGetOptionalParams extends OperationOp } export declare interface NullableFloatValueOperations { - get: (options?: NullableFloatValueGetOptionalParams) => Promise<(number | null)[]>; put: (body: (number | null)[], options?: NullableFloatValuePutOptionalParams) => Promise; + get: (options?: NullableFloatValueGetOptionalParams) => Promise<(number | null)[]>; } export declare interface NullableFloatValuePutOptionalParams extends OperationOptions { @@ -133,8 +133,8 @@ export declare interface NullableInt32ValueGetOptionalParams extends OperationOp } export declare interface NullableInt32ValueOperations { - get: (options?: NullableInt32ValueGetOptionalParams) => Promise<(number | null)[]>; put: (body: (number | null)[], options?: NullableInt32ValuePutOptionalParams) => Promise; + get: (options?: NullableInt32ValueGetOptionalParams) => Promise<(number | null)[]>; } export declare interface NullableInt32ValuePutOptionalParams extends OperationOptions { @@ -144,8 +144,8 @@ export declare interface NullableModelValueGetOptionalParams extends OperationOp } export declare interface NullableModelValueOperations { - get: (options?: NullableModelValueGetOptionalParams) => Promise<(InnerModel | null)[]>; put: (body: (InnerModel | null)[], options?: NullableModelValuePutOptionalParams) => Promise; + get: (options?: NullableModelValueGetOptionalParams) => Promise<(InnerModel | null)[]>; } export declare interface NullableModelValuePutOptionalParams extends OperationOptions { @@ -155,8 +155,8 @@ export declare interface NullableStringValueGetOptionalParams extends OperationO } export declare interface NullableStringValueOperations { - get: (options?: NullableStringValueGetOptionalParams) => Promise<(string | null)[]>; put: (body: (string | null)[], options?: NullableStringValuePutOptionalParams) => Promise; + get: (options?: NullableStringValueGetOptionalParams) => Promise<(string | null)[]>; } export declare interface NullableStringValuePutOptionalParams extends OperationOptions { @@ -166,8 +166,8 @@ export declare interface StringValueGetOptionalParams extends OperationOptions { } export declare interface StringValueOperations { - get: (options?: StringValueGetOptionalParams) => Promise; put: (body: string[], options?: StringValuePutOptionalParams) => Promise; + get: (options?: StringValueGetOptionalParams) => Promise; } export declare interface StringValuePutOptionalParams extends OperationOptions { @@ -177,8 +177,8 @@ export declare interface UnknownValueGetOptionalParams extends OperationOptions } export declare interface UnknownValueOperations { - get: (options?: UnknownValueGetOptionalParams) => Promise; put: (body: any[], options?: UnknownValuePutOptionalParams) => Promise; + get: (options?: UnknownValueGetOptionalParams) => Promise; } export declare interface UnknownValuePutOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/dictionary/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/dictionary/src/index.d.ts index 875203647d..7f436b2287 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/dictionary/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/dictionary/src/index.d.ts @@ -6,8 +6,8 @@ export declare interface BooleanValueGetOptionalParams extends OperationOptions } export declare interface BooleanValueOperations { - get: (options?: BooleanValueGetOptionalParams) => Promise>; put: (body: Record, options?: BooleanValuePutOptionalParams) => Promise; + get: (options?: BooleanValueGetOptionalParams) => Promise>; } export declare interface BooleanValuePutOptionalParams extends OperationOptions { @@ -17,8 +17,8 @@ export declare interface DatetimeValueGetOptionalParams extends OperationOptions } export declare interface DatetimeValueOperations { - get: (options?: DatetimeValueGetOptionalParams) => Promise>; put: (body: Record, options?: DatetimeValuePutOptionalParams) => Promise; + get: (options?: DatetimeValueGetOptionalParams) => Promise>; } export declare interface DatetimeValuePutOptionalParams extends OperationOptions { @@ -28,17 +28,17 @@ export declare class DictionaryClient { private _client; readonly pipeline: Pipeline; constructor(options?: DictionaryClientOptionalParams); - readonly int32Value: Int32ValueOperations; - readonly int64Value: Int64ValueOperations; - readonly booleanValue: BooleanValueOperations; - readonly stringValue: StringValueOperations; - readonly float32Value: Float32ValueOperations; - readonly datetimeValue: DatetimeValueOperations; - readonly durationValue: DurationValueOperations; - readonly unknownValue: UnknownValueOperations; - readonly modelValue: ModelValueOperations; - readonly recursiveModelValue: RecursiveModelValueOperations; readonly nullableFloatValue: NullableFloatValueOperations; + readonly recursiveModelValue: RecursiveModelValueOperations; + readonly modelValue: ModelValueOperations; + readonly unknownValue: UnknownValueOperations; + readonly durationValue: DurationValueOperations; + readonly datetimeValue: DatetimeValueOperations; + readonly float32Value: Float32ValueOperations; + readonly stringValue: StringValueOperations; + readonly booleanValue: BooleanValueOperations; + readonly int64Value: Int64ValueOperations; + readonly int32Value: Int32ValueOperations; } export declare interface DictionaryClientOptionalParams extends ClientOptions { @@ -48,8 +48,8 @@ export declare interface DurationValueGetOptionalParams extends OperationOptions } export declare interface DurationValueOperations { - get: (options?: DurationValueGetOptionalParams) => Promise>; put: (body: Record, options?: DurationValuePutOptionalParams) => Promise; + get: (options?: DurationValueGetOptionalParams) => Promise>; } export declare interface DurationValuePutOptionalParams extends OperationOptions { @@ -59,8 +59,8 @@ export declare interface Float32ValueGetOptionalParams extends OperationOptions } export declare interface Float32ValueOperations { - get: (options?: Float32ValueGetOptionalParams) => Promise>; put: (body: Record, options?: Float32ValuePutOptionalParams) => Promise; + get: (options?: Float32ValueGetOptionalParams) => Promise>; } export declare interface Float32ValuePutOptionalParams extends OperationOptions { @@ -75,8 +75,8 @@ export declare interface Int32ValueGetOptionalParams extends OperationOptions { } export declare interface Int32ValueOperations { - get: (options?: Int32ValueGetOptionalParams) => Promise>; put: (body: Record, options?: Int32ValuePutOptionalParams) => Promise; + get: (options?: Int32ValueGetOptionalParams) => Promise>; } export declare interface Int32ValuePutOptionalParams extends OperationOptions { @@ -86,8 +86,8 @@ export declare interface Int64ValueGetOptionalParams extends OperationOptions { } export declare interface Int64ValueOperations { - get: (options?: Int64ValueGetOptionalParams) => Promise>; put: (body: Record, options?: Int64ValuePutOptionalParams) => Promise; + get: (options?: Int64ValueGetOptionalParams) => Promise>; } export declare interface Int64ValuePutOptionalParams extends OperationOptions { @@ -97,8 +97,8 @@ export declare interface ModelValueGetOptionalParams extends OperationOptions { } export declare interface ModelValueOperations { - get: (options?: ModelValueGetOptionalParams) => Promise>; put: (body: Record, options?: ModelValuePutOptionalParams) => Promise; + get: (options?: ModelValueGetOptionalParams) => Promise>; } export declare interface ModelValuePutOptionalParams extends OperationOptions { @@ -108,8 +108,8 @@ export declare interface NullableFloatValueGetOptionalParams extends OperationOp } export declare interface NullableFloatValueOperations { - get: (options?: NullableFloatValueGetOptionalParams) => Promise>; put: (body: Record, options?: NullableFloatValuePutOptionalParams) => Promise; + get: (options?: NullableFloatValueGetOptionalParams) => Promise>; } export declare interface NullableFloatValuePutOptionalParams extends OperationOptions { @@ -119,8 +119,8 @@ export declare interface RecursiveModelValueGetOptionalParams extends OperationO } export declare interface RecursiveModelValueOperations { - get: (options?: RecursiveModelValueGetOptionalParams) => Promise>; put: (body: Record, options?: RecursiveModelValuePutOptionalParams) => Promise; + get: (options?: RecursiveModelValueGetOptionalParams) => Promise>; } export declare interface RecursiveModelValuePutOptionalParams extends OperationOptions { @@ -130,8 +130,8 @@ export declare interface StringValueGetOptionalParams extends OperationOptions { } export declare interface StringValueOperations { - get: (options?: StringValueGetOptionalParams) => Promise>; put: (body: Record, options?: StringValuePutOptionalParams) => Promise; + get: (options?: StringValueGetOptionalParams) => Promise>; } export declare interface StringValuePutOptionalParams extends OperationOptions { @@ -141,8 +141,8 @@ export declare interface UnknownValueGetOptionalParams extends OperationOptions } export declare interface UnknownValueOperations { - get: (options?: UnknownValueGetOptionalParams) => Promise>; put: (body: Record, options?: UnknownValuePutOptionalParams) => Promise; + get: (options?: UnknownValueGetOptionalParams) => Promise>; } export declare interface UnknownValuePutOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/enum/extensible/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/enum/extensible/src/index.d.ts index a3b81f671d..0b6947054e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/enum/extensible/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/enum/extensible/src/index.d.ts @@ -21,10 +21,10 @@ export declare interface StringGetUnknownValueOptionalParams extends OperationOp } export declare interface StringOperations { - getKnownValue: (options?: StringGetKnownValueOptionalParams) => Promise; - getUnknownValue: (options?: StringGetUnknownValueOptionalParams) => Promise; - putKnownValue: (body: DaysOfWeekExtensibleEnum, options?: StringPutKnownValueOptionalParams) => Promise; putUnknownValue: (body: DaysOfWeekExtensibleEnum, options?: StringPutUnknownValueOptionalParams) => Promise; + putKnownValue: (body: DaysOfWeekExtensibleEnum, options?: StringPutKnownValueOptionalParams) => Promise; + getUnknownValue: (options?: StringGetUnknownValueOptionalParams) => Promise; + getKnownValue: (options?: StringGetKnownValueOptionalParams) => Promise; } export declare interface StringPutKnownValueOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/enum/fixed/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/enum/fixed/src/index.d.ts index 0e8d906dee..f5fe843f17 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/enum/fixed/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/enum/fixed/src/index.d.ts @@ -18,9 +18,9 @@ export declare interface StringGetKnownValueOptionalParams extends OperationOpti } export declare interface StringOperations { - getKnownValue: (options?: StringGetKnownValueOptionalParams) => Promise; - putKnownValue: (body: DaysOfWeekEnum, options?: StringPutKnownValueOptionalParams) => Promise; putUnknownValue: (body: DaysOfWeekEnum, options?: StringPutUnknownValueOptionalParams) => Promise; + putKnownValue: (body: DaysOfWeekEnum, options?: StringPutKnownValueOptionalParams) => Promise; + getKnownValue: (options?: StringGetKnownValueOptionalParams) => Promise; } export declare interface StringPutKnownValueOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/empty/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/empty/src/index.d.ts index bcf8573d82..ef81818e57 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/empty/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/empty/src/index.d.ts @@ -6,9 +6,9 @@ export declare class EmptyClient { private _client; readonly pipeline: Pipeline; constructor(options?: EmptyClientOptionalParams); - putEmpty(input: EmptyInput, options?: PutEmptyOptionalParams): Promise; - getEmpty(options?: GetEmptyOptionalParams): Promise; postRoundTripEmpty(body: EmptyInputOutput, options?: PostRoundTripEmptyOptionalParams): Promise; + getEmpty(options?: GetEmptyOptionalParams): Promise; + putEmpty(input: EmptyInput, options?: PutEmptyOptionalParams): Promise; } export declare interface EmptyClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/enum-discriminator/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/enum-discriminator/src/index.d.ts index a72b66e321..20a1c6d030 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/enum-discriminator/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/enum-discriminator/src/index.d.ts @@ -19,14 +19,14 @@ export declare class EnumDiscriminatorClient { private _client; readonly pipeline: Pipeline; constructor(options?: EnumDiscriminatorClientOptionalParams); - getExtensibleModel(options?: GetExtensibleModelOptionalParams): Promise; - putExtensibleModel(input: DogUnion, options?: PutExtensibleModelOptionalParams): Promise; - getExtensibleModelMissingDiscriminator(options?: GetExtensibleModelMissingDiscriminatorOptionalParams): Promise; - getExtensibleModelWrongDiscriminator(options?: GetExtensibleModelWrongDiscriminatorOptionalParams): Promise; - getFixedModel(options?: GetFixedModelOptionalParams): Promise; - putFixedModel(input: SnakeUnion, options?: PutFixedModelOptionalParams): Promise; - getFixedModelMissingDiscriminator(options?: GetFixedModelMissingDiscriminatorOptionalParams): Promise; getFixedModelWrongDiscriminator(options?: GetFixedModelWrongDiscriminatorOptionalParams): Promise; + getFixedModelMissingDiscriminator(options?: GetFixedModelMissingDiscriminatorOptionalParams): Promise; + putFixedModel(input: SnakeUnion, options?: PutFixedModelOptionalParams): Promise; + getFixedModel(options?: GetFixedModelOptionalParams): Promise; + getExtensibleModelWrongDiscriminator(options?: GetExtensibleModelWrongDiscriminatorOptionalParams): Promise; + getExtensibleModelMissingDiscriminator(options?: GetExtensibleModelMissingDiscriminatorOptionalParams): Promise; + putExtensibleModel(input: DogUnion, options?: PutExtensibleModelOptionalParams): Promise; + getExtensibleModel(options?: GetExtensibleModelOptionalParams): Promise; } export declare interface EnumDiscriminatorClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts index 32d27f131c..64bf16dfe4 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/nested-discriminator/src/index.d.ts @@ -29,12 +29,12 @@ export declare class NestedDiscriminatorClient { private _client; readonly pipeline: Pipeline; constructor(options?: NestedDiscriminatorClientOptionalParams); - getModel(options?: GetModelOptionalParams): Promise; - putModel(input: FishUnion, options?: PutModelOptionalParams): Promise; - getRecursiveModel(options?: GetRecursiveModelOptionalParams): Promise; - putRecursiveModel(input: FishUnion, options?: PutRecursiveModelOptionalParams): Promise; - getMissingDiscriminator(options?: GetMissingDiscriminatorOptionalParams): Promise; getWrongDiscriminator(options?: GetWrongDiscriminatorOptionalParams): Promise; + getMissingDiscriminator(options?: GetMissingDiscriminatorOptionalParams): Promise; + putRecursiveModel(input: FishUnion, options?: PutRecursiveModelOptionalParams): Promise; + getRecursiveModel(options?: GetRecursiveModelOptionalParams): Promise; + putModel(input: FishUnion, options?: PutModelOptionalParams): Promise; + getModel(options?: GetModelOptionalParams): Promise; } export declare interface NestedDiscriminatorClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/not-discriminated/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/not-discriminated/src/index.d.ts index 0ef0b2039a..b41328d759 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/not-discriminated/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/not-discriminated/src/index.d.ts @@ -13,9 +13,9 @@ export declare class NotDiscriminatedClient { private _client; readonly pipeline: Pipeline; constructor(options?: NotDiscriminatedClientOptionalParams); - postValid(input: Siamese, options?: PostValidOptionalParams): Promise; - getValid(options?: GetValidOptionalParams): Promise; putValid(input: Siamese, options?: PutValidOptionalParams): Promise; + getValid(options?: GetValidOptionalParams): Promise; + postValid(input: Siamese, options?: PostValidOptionalParams): Promise; } export declare interface NotDiscriminatedClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/recursive/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/recursive/src/index.d.ts index 8dd6f69d59..c6777a5ecb 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/recursive/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/recursive/src/index.d.ts @@ -21,8 +21,8 @@ export declare class RecursiveClient { private _client; readonly pipeline: Pipeline; constructor(options?: RecursiveClientOptionalParams); - put(input: Extension, options?: PutOptionalParams): Promise; get(options?: GetOptionalParams): Promise; + put(input: Extension, options?: PutOptionalParams): Promise; } export declare interface RecursiveClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts index a462a79cbc..1af2d7be19 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/inheritance/single-discriminator/src/index.d.ts @@ -56,13 +56,13 @@ export declare class SingleDiscriminatorClient { private _client; readonly pipeline: Pipeline; constructor(options?: SingleDiscriminatorClientOptionalParams); - getModel(options?: GetModelOptionalParams): Promise; - putModel(input: BirdUnion, options?: PutModelOptionalParams): Promise; - getRecursiveModel(options?: GetRecursiveModelOptionalParams): Promise; - putRecursiveModel(input: BirdUnion, options?: PutRecursiveModelOptionalParams): Promise; - getMissingDiscriminator(options?: GetMissingDiscriminatorOptionalParams): Promise; - getWrongDiscriminator(options?: GetWrongDiscriminatorOptionalParams): Promise; getLegacyModel(options?: GetLegacyModelOptionalParams): Promise; + getWrongDiscriminator(options?: GetWrongDiscriminatorOptionalParams): Promise; + getMissingDiscriminator(options?: GetMissingDiscriminatorOptionalParams): Promise; + putRecursiveModel(input: BirdUnion, options?: PutRecursiveModelOptionalParams): Promise; + getRecursiveModel(options?: GetRecursiveModelOptionalParams): Promise; + putModel(input: BirdUnion, options?: PutModelOptionalParams): Promise; + getModel(options?: GetModelOptionalParams): Promise; } export declare interface SingleDiscriminatorClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/model/usage/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/model/usage/src/index.d.ts index 52fba34360..6331da3ee0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/model/usage/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/model/usage/src/index.d.ts @@ -27,9 +27,9 @@ export declare class UsageClient { private _client; readonly pipeline: Pipeline; constructor(options?: UsageClientOptionalParams); - input(inputParameter: InputRecord, options?: InputOptionalParams): Promise; - output(options?: OutputOptionalParams): Promise; inputAndOutput(body: InputOutputRecord, options?: InputAndOutputOptionalParams): Promise; + output(options?: OutputOptionalParams): Promise; + input(inputParameter: InputRecord, options?: InputOptionalParams): Promise; } export declare interface UsageClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/property/additional-properties/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/property/additional-properties/src/index.d.ts index ccc811af85..249d4dd34a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/property/additional-properties/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/property/additional-properties/src/index.d.ts @@ -6,38 +6,38 @@ export declare class AdditionalPropertiesClient { private _client; readonly pipeline: Pipeline; constructor(options?: AdditionalPropertiesClientOptionalParams); - readonly extendsUnknown: ExtendsUnknownOperations; - readonly extendsUnknownDerived: ExtendsUnknownDerivedOperations; - readonly extendsUnknownDiscriminated: ExtendsUnknownDiscriminatedOperations; - readonly isUnknown: IsUnknownOperations; - readonly isUnknownDerived: IsUnknownDerivedOperations; - readonly isUnknownDiscriminated: IsUnknownDiscriminatedOperations; - readonly extendsString: ExtendsStringOperations; - readonly isString: IsStringOperations; - readonly spreadString: SpreadStringOperations; - readonly extendsFloat: ExtendsFloatOperations; - readonly isFloat: IsFloatOperations; - readonly spreadFloat: SpreadFloatOperations; - readonly extendsModel: ExtendsModelOperations; - readonly isModel: IsModelOperations; - readonly spreadModel: SpreadModelOperations; - readonly extendsModelArray: ExtendsModelArrayOperations; - readonly isModelArray: IsModelArrayOperations; - readonly spreadModelArray: SpreadModelArrayOperations; - readonly spreadDifferentString: SpreadDifferentStringOperations; - readonly spreadDifferentFloat: SpreadDifferentFloatOperations; - readonly spreadDifferentModel: SpreadDifferentModelOperations; - readonly spreadDifferentModelArray: SpreadDifferentModelArrayOperations; - readonly extendsDifferentSpreadString: ExtendsDifferentSpreadStringOperations; - readonly extendsDifferentSpreadFloat: ExtendsDifferentSpreadFloatOperations; - readonly extendsDifferentSpreadModel: ExtendsDifferentSpreadModelOperations; - readonly extendsDifferentSpreadModelArray: ExtendsDifferentSpreadModelArrayOperations; - readonly multipleSpread: MultipleSpreadOperations; - readonly spreadRecordUnion: SpreadRecordUnionOperations; - readonly spreadRecordDiscriminatedUnion: SpreadRecordDiscriminatedUnionOperations; - readonly spreadRecordNonDiscriminatedUnion: SpreadRecordNonDiscriminatedUnionOperations; - readonly spreadRecordNonDiscriminatedUnion2: SpreadRecordNonDiscriminatedUnion2Operations; readonly spreadRecordNonDiscriminatedUnion3: SpreadRecordNonDiscriminatedUnion3Operations; + readonly spreadRecordNonDiscriminatedUnion2: SpreadRecordNonDiscriminatedUnion2Operations; + readonly spreadRecordNonDiscriminatedUnion: SpreadRecordNonDiscriminatedUnionOperations; + readonly spreadRecordDiscriminatedUnion: SpreadRecordDiscriminatedUnionOperations; + readonly spreadRecordUnion: SpreadRecordUnionOperations; + readonly multipleSpread: MultipleSpreadOperations; + readonly extendsDifferentSpreadModelArray: ExtendsDifferentSpreadModelArrayOperations; + readonly extendsDifferentSpreadModel: ExtendsDifferentSpreadModelOperations; + readonly extendsDifferentSpreadFloat: ExtendsDifferentSpreadFloatOperations; + readonly extendsDifferentSpreadString: ExtendsDifferentSpreadStringOperations; + readonly spreadDifferentModelArray: SpreadDifferentModelArrayOperations; + readonly spreadDifferentModel: SpreadDifferentModelOperations; + readonly spreadDifferentFloat: SpreadDifferentFloatOperations; + readonly spreadDifferentString: SpreadDifferentStringOperations; + readonly spreadModelArray: SpreadModelArrayOperations; + readonly isModelArray: IsModelArrayOperations; + readonly extendsModelArray: ExtendsModelArrayOperations; + readonly spreadModel: SpreadModelOperations; + readonly isModel: IsModelOperations; + readonly extendsModel: ExtendsModelOperations; + readonly spreadFloat: SpreadFloatOperations; + readonly isFloat: IsFloatOperations; + readonly extendsFloat: ExtendsFloatOperations; + readonly spreadString: SpreadStringOperations; + readonly isString: IsStringOperations; + readonly extendsString: ExtendsStringOperations; + readonly isUnknownDiscriminated: IsUnknownDiscriminatedOperations; + readonly isUnknownDerived: IsUnknownDerivedOperations; + readonly isUnknown: IsUnknownOperations; + readonly extendsUnknownDiscriminated: ExtendsUnknownDiscriminatedOperations; + readonly extendsUnknownDerived: ExtendsUnknownDerivedOperations; + readonly extendsUnknown: ExtendsUnknownOperations; } export declare interface AdditionalPropertiesClientOptionalParams extends ClientOptions { @@ -79,8 +79,8 @@ export declare interface ExtendsDifferentSpreadFloatGetOptionalParams extends Op } export declare interface ExtendsDifferentSpreadFloatOperations { - get: (options?: ExtendsDifferentSpreadFloatGetOptionalParams) => Promise; put: (body: DifferentSpreadFloatDerived, options?: ExtendsDifferentSpreadFloatPutOptionalParams) => Promise; + get: (options?: ExtendsDifferentSpreadFloatGetOptionalParams) => Promise; } export declare interface ExtendsDifferentSpreadFloatPutOptionalParams extends OperationOptions { @@ -90,8 +90,8 @@ export declare interface ExtendsDifferentSpreadModelArrayGetOptionalParams exten } export declare interface ExtendsDifferentSpreadModelArrayOperations { - get: (options?: ExtendsDifferentSpreadModelArrayGetOptionalParams) => Promise; put: (body: DifferentSpreadModelArrayDerived, options?: ExtendsDifferentSpreadModelArrayPutOptionalParams) => Promise; + get: (options?: ExtendsDifferentSpreadModelArrayGetOptionalParams) => Promise; } export declare interface ExtendsDifferentSpreadModelArrayPutOptionalParams extends OperationOptions { @@ -101,8 +101,8 @@ export declare interface ExtendsDifferentSpreadModelGetOptionalParams extends Op } export declare interface ExtendsDifferentSpreadModelOperations { - get: (options?: ExtendsDifferentSpreadModelGetOptionalParams) => Promise; put: (body: DifferentSpreadModelDerived, options?: ExtendsDifferentSpreadModelPutOptionalParams) => Promise; + get: (options?: ExtendsDifferentSpreadModelGetOptionalParams) => Promise; } export declare interface ExtendsDifferentSpreadModelPutOptionalParams extends OperationOptions { @@ -112,8 +112,8 @@ export declare interface ExtendsDifferentSpreadStringGetOptionalParams extends O } export declare interface ExtendsDifferentSpreadStringOperations { - get: (options?: ExtendsDifferentSpreadStringGetOptionalParams) => Promise; put: (body: DifferentSpreadStringDerived, options?: ExtendsDifferentSpreadStringPutOptionalParams) => Promise; + get: (options?: ExtendsDifferentSpreadStringGetOptionalParams) => Promise; } export declare interface ExtendsDifferentSpreadStringPutOptionalParams extends OperationOptions { @@ -127,8 +127,8 @@ export declare interface ExtendsFloatGetOptionalParams extends OperationOptions } export declare interface ExtendsFloatOperations { - get: (options?: ExtendsFloatGetOptionalParams) => Promise; put: (body: ExtendsFloatAdditionalProperties, options?: ExtendsFloatPutOptionalParams) => Promise; + get: (options?: ExtendsFloatGetOptionalParams) => Promise; } export declare interface ExtendsFloatPutOptionalParams extends OperationOptions { @@ -146,8 +146,8 @@ export declare interface ExtendsModelArrayGetOptionalParams extends OperationOpt } export declare interface ExtendsModelArrayOperations { - get: (options?: ExtendsModelArrayGetOptionalParams) => Promise; put: (body: ExtendsModelArrayAdditionalProperties, options?: ExtendsModelArrayPutOptionalParams) => Promise; + get: (options?: ExtendsModelArrayGetOptionalParams) => Promise; } export declare interface ExtendsModelArrayPutOptionalParams extends OperationOptions { @@ -157,8 +157,8 @@ export declare interface ExtendsModelGetOptionalParams extends OperationOptions } export declare interface ExtendsModelOperations { - get: (options?: ExtendsModelGetOptionalParams) => Promise; put: (body: ExtendsModelAdditionalProperties, options?: ExtendsModelPutOptionalParams) => Promise; + get: (options?: ExtendsModelGetOptionalParams) => Promise; } export declare interface ExtendsModelPutOptionalParams extends OperationOptions { @@ -172,8 +172,8 @@ export declare interface ExtendsStringGetOptionalParams extends OperationOptions } export declare interface ExtendsStringOperations { - get: (options?: ExtendsStringGetOptionalParams) => Promise; put: (body: ExtendsStringAdditionalProperties, options?: ExtendsStringPutOptionalParams) => Promise; + get: (options?: ExtendsStringGetOptionalParams) => Promise; } export declare interface ExtendsStringPutOptionalParams extends OperationOptions { @@ -205,8 +205,8 @@ export declare interface ExtendsUnknownDerivedGetOptionalParams extends Operatio } export declare interface ExtendsUnknownDerivedOperations { - get: (options?: ExtendsUnknownDerivedGetOptionalParams) => Promise; put: (body: ExtendsUnknownAdditionalPropertiesDerived, options?: ExtendsUnknownDerivedPutOptionalParams) => Promise; + get: (options?: ExtendsUnknownDerivedGetOptionalParams) => Promise; } export declare interface ExtendsUnknownDerivedPutOptionalParams extends OperationOptions { @@ -216,8 +216,8 @@ export declare interface ExtendsUnknownDiscriminatedGetOptionalParams extends Op } export declare interface ExtendsUnknownDiscriminatedOperations { - get: (options?: ExtendsUnknownDiscriminatedGetOptionalParams) => Promise; put: (body: ExtendsUnknownAdditionalPropertiesDiscriminatedUnion, options?: ExtendsUnknownDiscriminatedPutOptionalParams) => Promise; + get: (options?: ExtendsUnknownDiscriminatedGetOptionalParams) => Promise; } export declare interface ExtendsUnknownDiscriminatedPutOptionalParams extends OperationOptions { @@ -227,8 +227,8 @@ export declare interface ExtendsUnknownGetOptionalParams extends OperationOption } export declare interface ExtendsUnknownOperations { - get: (options?: ExtendsUnknownGetOptionalParams) => Promise; put: (body: ExtendsUnknownAdditionalProperties, options?: ExtendsUnknownPutOptionalParams) => Promise; + get: (options?: ExtendsUnknownGetOptionalParams) => Promise; } export declare interface ExtendsUnknownPutOptionalParams extends OperationOptions { @@ -242,8 +242,8 @@ export declare interface IsFloatGetOptionalParams extends OperationOptions { } export declare interface IsFloatOperations { - get: (options?: IsFloatGetOptionalParams) => Promise; put: (body: IsFloatAdditionalProperties, options?: IsFloatPutOptionalParams) => Promise; + get: (options?: IsFloatGetOptionalParams) => Promise; } export declare interface IsFloatPutOptionalParams extends OperationOptions { @@ -261,8 +261,8 @@ export declare interface IsModelArrayGetOptionalParams extends OperationOptions } export declare interface IsModelArrayOperations { - get: (options?: IsModelArrayGetOptionalParams) => Promise; put: (body: IsModelArrayAdditionalProperties, options?: IsModelArrayPutOptionalParams) => Promise; + get: (options?: IsModelArrayGetOptionalParams) => Promise; } export declare interface IsModelArrayPutOptionalParams extends OperationOptions { @@ -272,8 +272,8 @@ export declare interface IsModelGetOptionalParams extends OperationOptions { } export declare interface IsModelOperations { - get: (options?: IsModelGetOptionalParams) => Promise; put: (body: IsModelAdditionalProperties, options?: IsModelPutOptionalParams) => Promise; + get: (options?: IsModelGetOptionalParams) => Promise; } export declare interface IsModelPutOptionalParams extends OperationOptions { @@ -287,8 +287,8 @@ export declare interface IsStringGetOptionalParams extends OperationOptions { } export declare interface IsStringOperations { - get: (options?: IsStringGetOptionalParams) => Promise; put: (body: IsStringAdditionalProperties, options?: IsStringPutOptionalParams) => Promise; + get: (options?: IsStringGetOptionalParams) => Promise; } export declare interface IsStringPutOptionalParams extends OperationOptions { @@ -320,8 +320,8 @@ export declare interface IsUnknownDerivedGetOptionalParams extends OperationOpti } export declare interface IsUnknownDerivedOperations { - get: (options?: IsUnknownDerivedGetOptionalParams) => Promise; put: (body: IsUnknownAdditionalPropertiesDerived, options?: IsUnknownDerivedPutOptionalParams) => Promise; + get: (options?: IsUnknownDerivedGetOptionalParams) => Promise; } export declare interface IsUnknownDerivedPutOptionalParams extends OperationOptions { @@ -331,8 +331,8 @@ export declare interface IsUnknownDiscriminatedGetOptionalParams extends Operati } export declare interface IsUnknownDiscriminatedOperations { - get: (options?: IsUnknownDiscriminatedGetOptionalParams) => Promise; put: (body: IsUnknownAdditionalPropertiesDiscriminatedUnion, options?: IsUnknownDiscriminatedPutOptionalParams) => Promise; + get: (options?: IsUnknownDiscriminatedGetOptionalParams) => Promise; } export declare interface IsUnknownDiscriminatedPutOptionalParams extends OperationOptions { @@ -342,8 +342,8 @@ export declare interface IsUnknownGetOptionalParams extends OperationOptions { } export declare interface IsUnknownOperations { - get: (options?: IsUnknownGetOptionalParams) => Promise; put: (body: IsUnknownAdditionalProperties, options?: IsUnknownPutOptionalParams) => Promise; + get: (options?: IsUnknownGetOptionalParams) => Promise; } export declare interface IsUnknownPutOptionalParams extends OperationOptions { @@ -357,8 +357,8 @@ export declare interface MultipleSpreadGetOptionalParams extends OperationOption } export declare interface MultipleSpreadOperations { - get: (options?: MultipleSpreadGetOptionalParams) => Promise; put: (body: MultipleSpreadRecord, options?: MultipleSpreadPutOptionalParams) => Promise; + get: (options?: MultipleSpreadGetOptionalParams) => Promise; } export declare interface MultipleSpreadPutOptionalParams extends OperationOptions { @@ -372,8 +372,8 @@ export declare interface SpreadDifferentFloatGetOptionalParams extends Operation } export declare interface SpreadDifferentFloatOperations { - get: (options?: SpreadDifferentFloatGetOptionalParams) => Promise; put: (body: DifferentSpreadFloatRecord, options?: SpreadDifferentFloatPutOptionalParams) => Promise; + get: (options?: SpreadDifferentFloatGetOptionalParams) => Promise; } export declare interface SpreadDifferentFloatPutOptionalParams extends OperationOptions { @@ -383,8 +383,8 @@ export declare interface SpreadDifferentModelArrayGetOptionalParams extends Oper } export declare interface SpreadDifferentModelArrayOperations { - get: (options?: SpreadDifferentModelArrayGetOptionalParams) => Promise; put: (body: DifferentSpreadModelArrayRecord, options?: SpreadDifferentModelArrayPutOptionalParams) => Promise; + get: (options?: SpreadDifferentModelArrayGetOptionalParams) => Promise; } export declare interface SpreadDifferentModelArrayPutOptionalParams extends OperationOptions { @@ -394,8 +394,8 @@ export declare interface SpreadDifferentModelGetOptionalParams extends Operation } export declare interface SpreadDifferentModelOperations { - get: (options?: SpreadDifferentModelGetOptionalParams) => Promise; put: (body: DifferentSpreadModelRecord, options?: SpreadDifferentModelPutOptionalParams) => Promise; + get: (options?: SpreadDifferentModelGetOptionalParams) => Promise; } export declare interface SpreadDifferentModelPutOptionalParams extends OperationOptions { @@ -405,8 +405,8 @@ export declare interface SpreadDifferentStringGetOptionalParams extends Operatio } export declare interface SpreadDifferentStringOperations { - get: (options?: SpreadDifferentStringGetOptionalParams) => Promise; put: (body: DifferentSpreadStringRecord, options?: SpreadDifferentStringPutOptionalParams) => Promise; + get: (options?: SpreadDifferentStringGetOptionalParams) => Promise; } export declare interface SpreadDifferentStringPutOptionalParams extends OperationOptions { @@ -416,8 +416,8 @@ export declare interface SpreadFloatGetOptionalParams extends OperationOptions { } export declare interface SpreadFloatOperations { - get: (options?: SpreadFloatGetOptionalParams) => Promise; put: (body: SpreadFloatRecord, options?: SpreadFloatPutOptionalParams) => Promise; + get: (options?: SpreadFloatGetOptionalParams) => Promise; } export declare interface SpreadFloatPutOptionalParams extends OperationOptions { @@ -431,8 +431,8 @@ export declare interface SpreadModelArrayGetOptionalParams extends OperationOpti } export declare interface SpreadModelArrayOperations { - get: (options?: SpreadModelArrayGetOptionalParams) => Promise; put: (body: SpreadModelArrayRecord, options?: SpreadModelArrayPutOptionalParams) => Promise; + get: (options?: SpreadModelArrayGetOptionalParams) => Promise; } export declare interface SpreadModelArrayPutOptionalParams extends OperationOptions { @@ -446,8 +446,8 @@ export declare interface SpreadModelGetOptionalParams extends OperationOptions { } export declare interface SpreadModelOperations { - get: (options?: SpreadModelGetOptionalParams) => Promise; put: (body: SpreadModelRecord, options?: SpreadModelPutOptionalParams) => Promise; + get: (options?: SpreadModelGetOptionalParams) => Promise; } export declare interface SpreadModelPutOptionalParams extends OperationOptions { @@ -461,8 +461,8 @@ export declare interface SpreadRecordDiscriminatedUnionGetOptionalParams extends } export declare interface SpreadRecordDiscriminatedUnionOperations { - get: (options?: SpreadRecordDiscriminatedUnionGetOptionalParams) => Promise; put: (body: SpreadRecordForDiscriminatedUnion, options?: SpreadRecordDiscriminatedUnionPutOptionalParams) => Promise; + get: (options?: SpreadRecordDiscriminatedUnionGetOptionalParams) => Promise; } export declare interface SpreadRecordDiscriminatedUnionPutOptionalParams extends OperationOptions { @@ -492,8 +492,8 @@ export declare interface SpreadRecordNonDiscriminatedUnion2GetOptionalParams ext } export declare interface SpreadRecordNonDiscriminatedUnion2Operations { - get: (options?: SpreadRecordNonDiscriminatedUnion2GetOptionalParams) => Promise; put: (body: SpreadRecordForNonDiscriminatedUnion2, options?: SpreadRecordNonDiscriminatedUnion2PutOptionalParams) => Promise; + get: (options?: SpreadRecordNonDiscriminatedUnion2GetOptionalParams) => Promise; } export declare interface SpreadRecordNonDiscriminatedUnion2PutOptionalParams extends OperationOptions { @@ -503,8 +503,8 @@ export declare interface SpreadRecordNonDiscriminatedUnion3GetOptionalParams ext } export declare interface SpreadRecordNonDiscriminatedUnion3Operations { - get: (options?: SpreadRecordNonDiscriminatedUnion3GetOptionalParams) => Promise; put: (body: SpreadRecordForNonDiscriminatedUnion3, options?: SpreadRecordNonDiscriminatedUnion3PutOptionalParams) => Promise; + get: (options?: SpreadRecordNonDiscriminatedUnion3GetOptionalParams) => Promise; } export declare interface SpreadRecordNonDiscriminatedUnion3PutOptionalParams extends OperationOptions { @@ -514,8 +514,8 @@ export declare interface SpreadRecordNonDiscriminatedUnionGetOptionalParams exte } export declare interface SpreadRecordNonDiscriminatedUnionOperations { - get: (options?: SpreadRecordNonDiscriminatedUnionGetOptionalParams) => Promise; put: (body: SpreadRecordForNonDiscriminatedUnion, options?: SpreadRecordNonDiscriminatedUnionPutOptionalParams) => Promise; + get: (options?: SpreadRecordNonDiscriminatedUnionGetOptionalParams) => Promise; } export declare interface SpreadRecordNonDiscriminatedUnionPutOptionalParams extends OperationOptions { @@ -525,8 +525,8 @@ export declare interface SpreadRecordUnionGetOptionalParams extends OperationOpt } export declare interface SpreadRecordUnionOperations { - get: (options?: SpreadRecordUnionGetOptionalParams) => Promise; put: (body: SpreadRecordForUnion, options?: SpreadRecordUnionPutOptionalParams) => Promise; + get: (options?: SpreadRecordUnionGetOptionalParams) => Promise; } export declare interface SpreadRecordUnionPutOptionalParams extends OperationOptions { @@ -536,8 +536,8 @@ export declare interface SpreadStringGetOptionalParams extends OperationOptions } export declare interface SpreadStringOperations { - get: (options?: SpreadStringGetOptionalParams) => Promise; put: (body: SpreadStringRecord, options?: SpreadStringPutOptionalParams) => Promise; + get: (options?: SpreadStringGetOptionalParams) => Promise; } export declare interface SpreadStringPutOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/property/nullable/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/property/nullable/src/index.d.ts index c40a92486f..2fdba31b3f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/property/nullable/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/property/nullable/src/index.d.ts @@ -9,18 +9,16 @@ export declare interface BytesGetNullOptionalParams extends OperationOptions { } export declare interface BytesOperations { - getNonNull: (options?: BytesGetNonNullOptionalParams) => Promise; - getNull: (options?: BytesGetNullOptionalParams) => Promise; - patchNonNull: (body: BytesProperty, options?: BytesPatchNonNullOptionalParams) => Promise; patchNull: (body: BytesProperty, options?: BytesPatchNullOptionalParams) => Promise; + patchNonNull: (body: BytesProperty, options?: BytesPatchNonNullOptionalParams) => Promise; + getNull: (options?: BytesGetNullOptionalParams) => Promise; + getNonNull: (options?: BytesGetNonNullOptionalParams) => Promise; } export declare interface BytesPatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface BytesPatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface BytesProperty { @@ -35,18 +33,16 @@ export declare interface CollectionsByteGetNullOptionalParams extends OperationO } export declare interface CollectionsByteOperations { - getNonNull: (options?: CollectionsByteGetNonNullOptionalParams) => Promise; - getNull: (options?: CollectionsByteGetNullOptionalParams) => Promise; - patchNonNull: (body: CollectionsByteProperty, options?: CollectionsBytePatchNonNullOptionalParams) => Promise; patchNull: (body: CollectionsByteProperty, options?: CollectionsBytePatchNullOptionalParams) => Promise; + patchNonNull: (body: CollectionsByteProperty, options?: CollectionsBytePatchNonNullOptionalParams) => Promise; + getNull: (options?: CollectionsByteGetNullOptionalParams) => Promise; + getNonNull: (options?: CollectionsByteGetNonNullOptionalParams) => Promise; } export declare interface CollectionsBytePatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface CollectionsBytePatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface CollectionsByteProperty { @@ -61,18 +57,16 @@ export declare interface CollectionsModelGetNullOptionalParams extends Operation } export declare interface CollectionsModelOperations { - getNonNull: (options?: CollectionsModelGetNonNullOptionalParams) => Promise; - getNull: (options?: CollectionsModelGetNullOptionalParams) => Promise; - patchNonNull: (body: CollectionsModelProperty, options?: CollectionsModelPatchNonNullOptionalParams) => Promise; patchNull: (body: CollectionsModelProperty, options?: CollectionsModelPatchNullOptionalParams) => Promise; + patchNonNull: (body: CollectionsModelProperty, options?: CollectionsModelPatchNonNullOptionalParams) => Promise; + getNull: (options?: CollectionsModelGetNullOptionalParams) => Promise; + getNonNull: (options?: CollectionsModelGetNonNullOptionalParams) => Promise; } export declare interface CollectionsModelPatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface CollectionsModelPatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface CollectionsModelProperty { @@ -87,18 +81,16 @@ export declare interface CollectionsStringGetNullOptionalParams extends Operatio } export declare interface CollectionsStringOperations { - getNonNull: (options?: CollectionsStringGetNonNullOptionalParams) => Promise; - getNull: (options?: CollectionsStringGetNullOptionalParams) => Promise; - patchNonNull: (body: CollectionsStringProperty, options?: CollectionsStringPatchNonNullOptionalParams) => Promise; patchNull: (body: CollectionsStringProperty, options?: CollectionsStringPatchNullOptionalParams) => Promise; + patchNonNull: (body: CollectionsStringProperty, options?: CollectionsStringPatchNonNullOptionalParams) => Promise; + getNull: (options?: CollectionsStringGetNullOptionalParams) => Promise; + getNonNull: (options?: CollectionsStringGetNonNullOptionalParams) => Promise; } export declare interface CollectionsStringPatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface CollectionsStringPatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface CollectionsStringProperty { @@ -113,18 +105,16 @@ export declare interface DatetimeGetNullOptionalParams extends OperationOptions } export declare interface DatetimeOperations { - getNonNull: (options?: DatetimeGetNonNullOptionalParams) => Promise; - getNull: (options?: DatetimeGetNullOptionalParams) => Promise; - patchNonNull: (body: DatetimeProperty, options?: DatetimePatchNonNullOptionalParams) => Promise; patchNull: (body: DatetimeProperty, options?: DatetimePatchNullOptionalParams) => Promise; + patchNonNull: (body: DatetimeProperty, options?: DatetimePatchNonNullOptionalParams) => Promise; + getNull: (options?: DatetimeGetNullOptionalParams) => Promise; + getNonNull: (options?: DatetimeGetNonNullOptionalParams) => Promise; } export declare interface DatetimePatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface DatetimePatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface DatetimeProperty { @@ -139,18 +129,16 @@ export declare interface DurationGetNullOptionalParams extends OperationOptions } export declare interface DurationOperations { - getNonNull: (options?: DurationGetNonNullOptionalParams) => Promise; - getNull: (options?: DurationGetNullOptionalParams) => Promise; - patchNonNull: (body: DurationProperty, options?: DurationPatchNonNullOptionalParams) => Promise; patchNull: (body: DurationProperty, options?: DurationPatchNullOptionalParams) => Promise; + patchNonNull: (body: DurationProperty, options?: DurationPatchNonNullOptionalParams) => Promise; + getNull: (options?: DurationGetNullOptionalParams) => Promise; + getNonNull: (options?: DurationGetNonNullOptionalParams) => Promise; } export declare interface DurationPatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface DurationPatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface DurationProperty { @@ -166,13 +154,13 @@ export declare class NullableClient { private _client; readonly pipeline: Pipeline; constructor(options?: NullableClientOptionalParams); - readonly string: StringOperations; - readonly bytes: BytesOperations; - readonly datetime: DatetimeOperations; - readonly duration: DurationOperations; - readonly collectionsByte: CollectionsByteOperations; - readonly collectionsModel: CollectionsModelOperations; readonly collectionsString: CollectionsStringOperations; + readonly collectionsModel: CollectionsModelOperations; + readonly collectionsByte: CollectionsByteOperations; + readonly duration: DurationOperations; + readonly datetime: DatetimeOperations; + readonly bytes: BytesOperations; + readonly string: StringOperations; } export declare interface NullableClientOptionalParams extends ClientOptions { @@ -185,18 +173,16 @@ export declare interface StringGetNullOptionalParams extends OperationOptions { } export declare interface StringOperations { - getNonNull: (options?: StringGetNonNullOptionalParams) => Promise; - getNull: (options?: StringGetNullOptionalParams) => Promise; - patchNonNull: (body: StringProperty, options?: StringPatchNonNullOptionalParams) => Promise; patchNull: (body: StringProperty, options?: StringPatchNullOptionalParams) => Promise; + patchNonNull: (body: StringProperty, options?: StringPatchNonNullOptionalParams) => Promise; + getNull: (options?: StringGetNullOptionalParams) => Promise; + getNonNull: (options?: StringGetNonNullOptionalParams) => Promise; } export declare interface StringPatchNonNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface StringPatchNullOptionalParams extends OperationOptions { - contentType?: string; } export declare interface StringProperty { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/property/optionality/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/property/optionality/src/index.d.ts index 16419913c0..464c6a85a1 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/property/optionality/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/property/optionality/src/index.d.ts @@ -9,10 +9,10 @@ export declare interface BooleanLiteralGetDefaultOptionalParams extends Operatio } export declare interface BooleanLiteralOperations { - getAll: (options?: BooleanLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: BooleanLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: BooleanLiteralProperty, options?: BooleanLiteralPutAllOptionalParams) => Promise; putDefault: (body: BooleanLiteralProperty, options?: BooleanLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: BooleanLiteralProperty, options?: BooleanLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: BooleanLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: BooleanLiteralGetAllOptionalParams) => Promise; } export declare interface BooleanLiteralProperty { @@ -32,10 +32,10 @@ export declare interface BytesGetDefaultOptionalParams extends OperationOptions } export declare interface BytesOperations { - getAll: (options?: BytesGetAllOptionalParams) => Promise; - getDefault: (options?: BytesGetDefaultOptionalParams) => Promise; - putAll: (body: BytesProperty, options?: BytesPutAllOptionalParams) => Promise; putDefault: (body: BytesProperty, options?: BytesPutDefaultOptionalParams) => Promise; + putAll: (body: BytesProperty, options?: BytesPutAllOptionalParams) => Promise; + getDefault: (options?: BytesGetDefaultOptionalParams) => Promise; + getAll: (options?: BytesGetAllOptionalParams) => Promise; } export declare interface BytesProperty { @@ -55,10 +55,10 @@ export declare interface CollectionsByteGetDefaultOptionalParams extends Operati } export declare interface CollectionsByteOperations { - getAll: (options?: CollectionsByteGetAllOptionalParams) => Promise; - getDefault: (options?: CollectionsByteGetDefaultOptionalParams) => Promise; - putAll: (body: CollectionsByteProperty, options?: CollectionsBytePutAllOptionalParams) => Promise; putDefault: (body: CollectionsByteProperty, options?: CollectionsBytePutDefaultOptionalParams) => Promise; + putAll: (body: CollectionsByteProperty, options?: CollectionsBytePutAllOptionalParams) => Promise; + getDefault: (options?: CollectionsByteGetDefaultOptionalParams) => Promise; + getAll: (options?: CollectionsByteGetAllOptionalParams) => Promise; } export declare interface CollectionsByteProperty { @@ -78,10 +78,10 @@ export declare interface CollectionsModelGetDefaultOptionalParams extends Operat } export declare interface CollectionsModelOperations { - getAll: (options?: CollectionsModelGetAllOptionalParams) => Promise; - getDefault: (options?: CollectionsModelGetDefaultOptionalParams) => Promise; - putAll: (body: CollectionsModelProperty, options?: CollectionsModelPutAllOptionalParams) => Promise; putDefault: (body: CollectionsModelProperty, options?: CollectionsModelPutDefaultOptionalParams) => Promise; + putAll: (body: CollectionsModelProperty, options?: CollectionsModelPutAllOptionalParams) => Promise; + getDefault: (options?: CollectionsModelGetDefaultOptionalParams) => Promise; + getAll: (options?: CollectionsModelGetAllOptionalParams) => Promise; } export declare interface CollectionsModelProperty { @@ -101,10 +101,10 @@ export declare interface DatetimeGetDefaultOptionalParams extends OperationOptio } export declare interface DatetimeOperations { - getAll: (options?: DatetimeGetAllOptionalParams) => Promise; - getDefault: (options?: DatetimeGetDefaultOptionalParams) => Promise; - putAll: (body: DatetimeProperty, options?: DatetimePutAllOptionalParams) => Promise; putDefault: (body: DatetimeProperty, options?: DatetimePutDefaultOptionalParams) => Promise; + putAll: (body: DatetimeProperty, options?: DatetimePutAllOptionalParams) => Promise; + getDefault: (options?: DatetimeGetDefaultOptionalParams) => Promise; + getAll: (options?: DatetimeGetAllOptionalParams) => Promise; } export declare interface DatetimeProperty { @@ -124,10 +124,10 @@ export declare interface DurationGetDefaultOptionalParams extends OperationOptio } export declare interface DurationOperations { - getAll: (options?: DurationGetAllOptionalParams) => Promise; - getDefault: (options?: DurationGetDefaultOptionalParams) => Promise; - putAll: (body: DurationProperty, options?: DurationPutAllOptionalParams) => Promise; putDefault: (body: DurationProperty, options?: DurationPutDefaultOptionalParams) => Promise; + putAll: (body: DurationProperty, options?: DurationPutAllOptionalParams) => Promise; + getDefault: (options?: DurationGetDefaultOptionalParams) => Promise; + getAll: (options?: DurationGetAllOptionalParams) => Promise; } export declare interface DurationProperty { @@ -147,10 +147,10 @@ export declare interface FloatLiteralGetDefaultOptionalParams extends OperationO } export declare interface FloatLiteralOperations { - getAll: (options?: FloatLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: FloatLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: FloatLiteralProperty, options?: FloatLiteralPutAllOptionalParams) => Promise; putDefault: (body: FloatLiteralProperty, options?: FloatLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: FloatLiteralProperty, options?: FloatLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: FloatLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: FloatLiteralGetAllOptionalParams) => Promise; } export declare interface FloatLiteralProperty { @@ -170,10 +170,10 @@ export declare interface IntLiteralGetDefaultOptionalParams extends OperationOpt } export declare interface IntLiteralOperations { - getAll: (options?: IntLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: IntLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: IntLiteralProperty, options?: IntLiteralPutAllOptionalParams) => Promise; putDefault: (body: IntLiteralProperty, options?: IntLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: IntLiteralProperty, options?: IntLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: IntLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: IntLiteralGetAllOptionalParams) => Promise; } export declare interface IntLiteralProperty { @@ -190,22 +190,22 @@ export declare class OptionalClient { private _client; readonly pipeline: Pipeline; constructor(options?: OptionalClientOptionalParams); - readonly string: StringOperations; - readonly bytes: BytesOperations; - readonly datetime: DatetimeOperations; - readonly duration: DurationOperations; - readonly plainDate: PlainDateOperations; - readonly plainTime: PlainTimeOperations; - readonly collectionsByte: CollectionsByteOperations; - readonly collectionsModel: CollectionsModelOperations; - readonly stringLiteral: StringLiteralOperations; - readonly intLiteral: IntLiteralOperations; - readonly floatLiteral: FloatLiteralOperations; - readonly booleanLiteral: BooleanLiteralOperations; - readonly unionStringLiteral: UnionStringLiteralOperations; - readonly unionIntLiteral: UnionIntLiteralOperations; - readonly unionFloatLiteral: UnionFloatLiteralOperations; readonly requiredAndOptional: RequiredAndOptionalOperations; + readonly unionFloatLiteral: UnionFloatLiteralOperations; + readonly unionIntLiteral: UnionIntLiteralOperations; + readonly unionStringLiteral: UnionStringLiteralOperations; + readonly booleanLiteral: BooleanLiteralOperations; + readonly floatLiteral: FloatLiteralOperations; + readonly intLiteral: IntLiteralOperations; + readonly stringLiteral: StringLiteralOperations; + readonly collectionsModel: CollectionsModelOperations; + readonly collectionsByte: CollectionsByteOperations; + readonly plainTime: PlainTimeOperations; + readonly plainDate: PlainDateOperations; + readonly duration: DurationOperations; + readonly datetime: DatetimeOperations; + readonly bytes: BytesOperations; + readonly string: StringOperations; } export declare interface OptionalClientOptionalParams extends ClientOptions { @@ -218,10 +218,10 @@ export declare interface PlainDateGetDefaultOptionalParams extends OperationOpti } export declare interface PlainDateOperations { - getAll: (options?: PlainDateGetAllOptionalParams) => Promise; - getDefault: (options?: PlainDateGetDefaultOptionalParams) => Promise; - putAll: (body: PlainDateProperty, options?: PlainDatePutAllOptionalParams) => Promise; putDefault: (body: PlainDateProperty, options?: PlainDatePutDefaultOptionalParams) => Promise; + putAll: (body: PlainDateProperty, options?: PlainDatePutAllOptionalParams) => Promise; + getDefault: (options?: PlainDateGetDefaultOptionalParams) => Promise; + getAll: (options?: PlainDateGetAllOptionalParams) => Promise; } export declare interface PlainDateProperty { @@ -241,10 +241,10 @@ export declare interface PlainTimeGetDefaultOptionalParams extends OperationOpti } export declare interface PlainTimeOperations { - getAll: (options?: PlainTimeGetAllOptionalParams) => Promise; - getDefault: (options?: PlainTimeGetDefaultOptionalParams) => Promise; - putAll: (body: PlainTimeProperty, options?: PlainTimePutAllOptionalParams) => Promise; putDefault: (body: PlainTimeProperty, options?: PlainTimePutDefaultOptionalParams) => Promise; + putAll: (body: PlainTimeProperty, options?: PlainTimePutAllOptionalParams) => Promise; + getDefault: (options?: PlainTimeGetDefaultOptionalParams) => Promise; + getAll: (options?: PlainTimeGetAllOptionalParams) => Promise; } export declare interface PlainTimeProperty { @@ -264,10 +264,10 @@ export declare interface RequiredAndOptionalGetRequiredOnlyOptionalParams extend } export declare interface RequiredAndOptionalOperations { - getAll: (options?: RequiredAndOptionalGetAllOptionalParams) => Promise; - getRequiredOnly: (options?: RequiredAndOptionalGetRequiredOnlyOptionalParams) => Promise; - putAll: (body: RequiredAndOptionalProperty, options?: RequiredAndOptionalPutAllOptionalParams) => Promise; putRequiredOnly: (body: RequiredAndOptionalProperty, options?: RequiredAndOptionalPutRequiredOnlyOptionalParams) => Promise; + putAll: (body: RequiredAndOptionalProperty, options?: RequiredAndOptionalPutAllOptionalParams) => Promise; + getRequiredOnly: (options?: RequiredAndOptionalGetRequiredOnlyOptionalParams) => Promise; + getAll: (options?: RequiredAndOptionalGetAllOptionalParams) => Promise; } export declare interface RequiredAndOptionalProperty { @@ -294,10 +294,10 @@ export declare interface StringLiteralGetDefaultOptionalParams extends Operation } export declare interface StringLiteralOperations { - getAll: (options?: StringLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: StringLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: StringLiteralProperty, options?: StringLiteralPutAllOptionalParams) => Promise; putDefault: (body: StringLiteralProperty, options?: StringLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: StringLiteralProperty, options?: StringLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: StringLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: StringLiteralGetAllOptionalParams) => Promise; } export declare interface StringLiteralProperty { @@ -311,10 +311,10 @@ export declare interface StringLiteralPutDefaultOptionalParams extends Operation } export declare interface StringOperations { - getAll: (options?: StringGetAllOptionalParams) => Promise; - getDefault: (options?: StringGetDefaultOptionalParams) => Promise; - putAll: (body: StringProperty, options?: StringPutAllOptionalParams) => Promise; putDefault: (body: StringProperty, options?: StringPutDefaultOptionalParams) => Promise; + putAll: (body: StringProperty, options?: StringPutAllOptionalParams) => Promise; + getDefault: (options?: StringGetDefaultOptionalParams) => Promise; + getAll: (options?: StringGetAllOptionalParams) => Promise; } export declare interface StringProperty { @@ -334,10 +334,10 @@ export declare interface UnionFloatLiteralGetDefaultOptionalParams extends Opera } export declare interface UnionFloatLiteralOperations { - getAll: (options?: UnionFloatLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: UnionFloatLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: UnionFloatLiteralProperty, options?: UnionFloatLiteralPutAllOptionalParams) => Promise; putDefault: (body: UnionFloatLiteralProperty, options?: UnionFloatLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: UnionFloatLiteralProperty, options?: UnionFloatLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: UnionFloatLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: UnionFloatLiteralGetAllOptionalParams) => Promise; } export declare interface UnionFloatLiteralProperty { @@ -357,10 +357,10 @@ export declare interface UnionIntLiteralGetDefaultOptionalParams extends Operati } export declare interface UnionIntLiteralOperations { - getAll: (options?: UnionIntLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: UnionIntLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: UnionIntLiteralProperty, options?: UnionIntLiteralPutAllOptionalParams) => Promise; putDefault: (body: UnionIntLiteralProperty, options?: UnionIntLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: UnionIntLiteralProperty, options?: UnionIntLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: UnionIntLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: UnionIntLiteralGetAllOptionalParams) => Promise; } export declare interface UnionIntLiteralProperty { @@ -380,10 +380,10 @@ export declare interface UnionStringLiteralGetDefaultOptionalParams extends Oper } export declare interface UnionStringLiteralOperations { - getAll: (options?: UnionStringLiteralGetAllOptionalParams) => Promise; - getDefault: (options?: UnionStringLiteralGetDefaultOptionalParams) => Promise; - putAll: (body: UnionStringLiteralProperty, options?: UnionStringLiteralPutAllOptionalParams) => Promise; putDefault: (body: UnionStringLiteralProperty, options?: UnionStringLiteralPutDefaultOptionalParams) => Promise; + putAll: (body: UnionStringLiteralProperty, options?: UnionStringLiteralPutAllOptionalParams) => Promise; + getDefault: (options?: UnionStringLiteralGetDefaultOptionalParams) => Promise; + getAll: (options?: UnionStringLiteralGetAllOptionalParams) => Promise; } export declare interface UnionStringLiteralProperty { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/property/value-types/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/property/value-types/src/index.d.ts index aed9fa0dbe..857c4d2a2e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/property/value-types/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/property/value-types/src/index.d.ts @@ -9,8 +9,8 @@ export declare interface BooleanLiteralGetOptionalParams extends OperationOption } export declare interface BooleanLiteralOperations { - get: (options?: BooleanLiteralGetOptionalParams) => Promise; put: (body: BooleanLiteralProperty, options?: BooleanLiteralPutOptionalParams) => Promise; + get: (options?: BooleanLiteralGetOptionalParams) => Promise; } export declare interface BooleanLiteralProperty { @@ -21,8 +21,8 @@ export declare interface BooleanLiteralPutOptionalParams extends OperationOption } export declare interface BooleanOperations { - get: (options?: BooleanGetOptionalParams) => Promise; put: (body: BooleanProperty, options?: BooleanPutOptionalParams) => Promise; + get: (options?: BooleanGetOptionalParams) => Promise; } export declare interface BooleanProperty { @@ -36,8 +36,8 @@ export declare interface BytesGetOptionalParams extends OperationOptions { } export declare interface BytesOperations { - get: (options?: BytesGetOptionalParams) => Promise; put: (body: BytesProperty, options?: BytesPutOptionalParams) => Promise; + get: (options?: BytesGetOptionalParams) => Promise; } export declare interface BytesProperty { @@ -51,8 +51,8 @@ export declare interface CollectionsIntGetOptionalParams extends OperationOption } export declare interface CollectionsIntOperations { - get: (options?: CollectionsIntGetOptionalParams) => Promise; put: (body: CollectionsIntProperty, options?: CollectionsIntPutOptionalParams) => Promise; + get: (options?: CollectionsIntGetOptionalParams) => Promise; } export declare interface CollectionsIntProperty { @@ -66,8 +66,8 @@ export declare interface CollectionsModelGetOptionalParams extends OperationOpti } export declare interface CollectionsModelOperations { - get: (options?: CollectionsModelGetOptionalParams) => Promise; put: (body: CollectionsModelProperty, options?: CollectionsModelPutOptionalParams) => Promise; + get: (options?: CollectionsModelGetOptionalParams) => Promise; } export declare interface CollectionsModelProperty { @@ -81,8 +81,8 @@ export declare interface CollectionsStringGetOptionalParams extends OperationOpt } export declare interface CollectionsStringOperations { - get: (options?: CollectionsStringGetOptionalParams) => Promise; put: (body: CollectionsStringProperty, options?: CollectionsStringPutOptionalParams) => Promise; + get: (options?: CollectionsStringGetOptionalParams) => Promise; } export declare interface CollectionsStringProperty { @@ -96,8 +96,8 @@ export declare interface DatetimeGetOptionalParams extends OperationOptions { } export declare interface DatetimeOperations { - get: (options?: DatetimeGetOptionalParams) => Promise; put: (body: DatetimeProperty, options?: DatetimePutOptionalParams) => Promise; + get: (options?: DatetimeGetOptionalParams) => Promise; } export declare interface DatetimeProperty { @@ -111,8 +111,8 @@ export declare interface Decimal128GetOptionalParams extends OperationOptions { } export declare interface Decimal128Operations { - get: (options?: Decimal128GetOptionalParams) => Promise; put: (body: Decimal128Property, options?: Decimal128PutOptionalParams) => Promise; + get: (options?: Decimal128GetOptionalParams) => Promise; } export declare interface Decimal128Property { @@ -126,8 +126,8 @@ export declare interface DecimalGetOptionalParams extends OperationOptions { } export declare interface DecimalOperations { - get: (options?: DecimalGetOptionalParams) => Promise; put: (body: DecimalProperty, options?: DecimalPutOptionalParams) => Promise; + get: (options?: DecimalGetOptionalParams) => Promise; } export declare interface DecimalProperty { @@ -141,8 +141,8 @@ export declare interface DictionaryStringGetOptionalParams extends OperationOpti } export declare interface DictionaryStringOperations { - get: (options?: DictionaryStringGetOptionalParams) => Promise; put: (body: DictionaryStringProperty, options?: DictionaryStringPutOptionalParams) => Promise; + get: (options?: DictionaryStringGetOptionalParams) => Promise; } export declare interface DictionaryStringProperty { @@ -156,8 +156,8 @@ export declare interface DurationGetOptionalParams extends OperationOptions { } export declare interface DurationOperations { - get: (options?: DurationGetOptionalParams) => Promise; put: (body: DurationProperty, options?: DurationPutOptionalParams) => Promise; + get: (options?: DurationGetOptionalParams) => Promise; } export declare interface DurationProperty { @@ -171,8 +171,8 @@ export declare interface EnumGetOptionalParams extends OperationOptions { } export declare interface EnumOperations { - get: (options?: EnumGetOptionalParams) => Promise; put: (body: EnumProperty, options?: EnumPutOptionalParams) => Promise; + get: (options?: EnumGetOptionalParams) => Promise; } export declare interface EnumProperty { @@ -188,8 +188,8 @@ export declare interface ExtensibleEnumGetOptionalParams extends OperationOption } export declare interface ExtensibleEnumOperations { - get: (options?: ExtensibleEnumGetOptionalParams) => Promise; put: (body: ExtensibleEnumProperty, options?: ExtensibleEnumPutOptionalParams) => Promise; + get: (options?: ExtensibleEnumGetOptionalParams) => Promise; } export declare interface ExtensibleEnumProperty { @@ -208,8 +208,8 @@ export declare interface FloatLiteralGetOptionalParams extends OperationOptions } export declare interface FloatLiteralOperations { - get: (options?: FloatLiteralGetOptionalParams) => Promise; put: (body: FloatLiteralProperty, options?: FloatLiteralPutOptionalParams) => Promise; + get: (options?: FloatLiteralGetOptionalParams) => Promise; } export declare interface FloatLiteralProperty { @@ -220,8 +220,8 @@ export declare interface FloatLiteralPutOptionalParams extends OperationOptions } export declare interface FloatOperations { - get: (options?: FloatGetOptionalParams) => Promise; put: (body: FloatProperty, options?: FloatPutOptionalParams) => Promise; + get: (options?: FloatGetOptionalParams) => Promise; } export declare interface FloatProperty { @@ -244,8 +244,8 @@ export declare interface IntLiteralGetOptionalParams extends OperationOptions { } export declare interface IntLiteralOperations { - get: (options?: IntLiteralGetOptionalParams) => Promise; put: (body: IntLiteralProperty, options?: IntLiteralPutOptionalParams) => Promise; + get: (options?: IntLiteralGetOptionalParams) => Promise; } export declare interface IntLiteralProperty { @@ -256,8 +256,8 @@ export declare interface IntLiteralPutOptionalParams extends OperationOptions { } export declare interface IntOperations { - get: (options?: IntGetOptionalParams) => Promise; put: (body: IntProperty, options?: IntPutOptionalParams) => Promise; + get: (options?: IntGetOptionalParams) => Promise; } export declare interface IntProperty { @@ -271,8 +271,8 @@ export declare interface ModelGetOptionalParams extends OperationOptions { } export declare interface ModelOperations { - get: (options?: ModelGetOptionalParams) => Promise; put: (body: ModelProperty, options?: ModelPutOptionalParams) => Promise; + get: (options?: ModelGetOptionalParams) => Promise; } export declare interface ModelProperty { @@ -286,8 +286,8 @@ export declare interface NeverGetOptionalParams extends OperationOptions { } export declare interface NeverOperations { - get: (options?: NeverGetOptionalParams) => Promise; put: (body: NeverProperty, options?: NeverPutOptionalParams) => Promise; + get: (options?: NeverGetOptionalParams) => Promise; } export declare interface NeverProperty { @@ -303,8 +303,8 @@ export declare interface StringLiteralGetOptionalParams extends OperationOptions } export declare interface StringLiteralOperations { - get: (options?: StringLiteralGetOptionalParams) => Promise; put: (body: StringLiteralProperty, options?: StringLiteralPutOptionalParams) => Promise; + get: (options?: StringLiteralGetOptionalParams) => Promise; } export declare interface StringLiteralProperty { @@ -315,8 +315,8 @@ export declare interface StringLiteralPutOptionalParams extends OperationOptions } export declare interface StringOperations { - get: (options?: StringGetOptionalParams) => Promise; put: (body: StringProperty, options?: StringPutOptionalParams) => Promise; + get: (options?: StringGetOptionalParams) => Promise; } export declare interface StringProperty { @@ -330,8 +330,8 @@ export declare interface UnionEnumValueGetOptionalParams extends OperationOption } export declare interface UnionEnumValueOperations { - get: (options?: UnionEnumValueGetOptionalParams) => Promise; put: (body: UnionEnumValueProperty, options?: UnionEnumValuePutOptionalParams) => Promise; + get: (options?: UnionEnumValueGetOptionalParams) => Promise; } export declare interface UnionEnumValueProperty { @@ -345,8 +345,8 @@ export declare interface UnionFloatLiteralGetOptionalParams extends OperationOpt } export declare interface UnionFloatLiteralOperations { - get: (options?: UnionFloatLiteralGetOptionalParams) => Promise; put: (body: UnionFloatLiteralProperty, options?: UnionFloatLiteralPutOptionalParams) => Promise; + get: (options?: UnionFloatLiteralGetOptionalParams) => Promise; } export declare interface UnionFloatLiteralProperty { @@ -360,8 +360,8 @@ export declare interface UnionIntLiteralGetOptionalParams extends OperationOptio } export declare interface UnionIntLiteralOperations { - get: (options?: UnionIntLiteralGetOptionalParams) => Promise; put: (body: UnionIntLiteralProperty, options?: UnionIntLiteralPutOptionalParams) => Promise; + get: (options?: UnionIntLiteralGetOptionalParams) => Promise; } export declare interface UnionIntLiteralProperty { @@ -375,8 +375,8 @@ export declare interface UnionStringLiteralGetOptionalParams extends OperationOp } export declare interface UnionStringLiteralOperations { - get: (options?: UnionStringLiteralGetOptionalParams) => Promise; put: (body: UnionStringLiteralProperty, options?: UnionStringLiteralPutOptionalParams) => Promise; + get: (options?: UnionStringLiteralGetOptionalParams) => Promise; } export declare interface UnionStringLiteralProperty { @@ -390,8 +390,8 @@ export declare interface UnknownArrayGetOptionalParams extends OperationOptions } export declare interface UnknownArrayOperations { - get: (options?: UnknownArrayGetOptionalParams) => Promise; put: (body: UnknownArrayProperty, options?: UnknownArrayPutOptionalParams) => Promise; + get: (options?: UnknownArrayGetOptionalParams) => Promise; } export declare interface UnknownArrayProperty { @@ -405,8 +405,8 @@ export declare interface UnknownDictGetOptionalParams extends OperationOptions { } export declare interface UnknownDictOperations { - get: (options?: UnknownDictGetOptionalParams) => Promise; put: (body: UnknownDictProperty, options?: UnknownDictPutOptionalParams) => Promise; + get: (options?: UnknownDictGetOptionalParams) => Promise; } export declare interface UnknownDictProperty { @@ -420,8 +420,8 @@ export declare interface UnknownIntGetOptionalParams extends OperationOptions { } export declare interface UnknownIntOperations { - get: (options?: UnknownIntGetOptionalParams) => Promise; put: (body: UnknownIntProperty, options?: UnknownIntPutOptionalParams) => Promise; + get: (options?: UnknownIntGetOptionalParams) => Promise; } export declare interface UnknownIntProperty { @@ -435,8 +435,8 @@ export declare interface UnknownStringGetOptionalParams extends OperationOptions } export declare interface UnknownStringOperations { - get: (options?: UnknownStringGetOptionalParams) => Promise; put: (body: UnknownStringProperty, options?: UnknownStringPutOptionalParams) => Promise; + get: (options?: UnknownStringGetOptionalParams) => Promise; } export declare interface UnknownStringProperty { @@ -450,35 +450,35 @@ export declare class ValueTypesClient { private _client; readonly pipeline: Pipeline; constructor(options?: ValueTypesClientOptionalParams); - readonly boolean: BooleanOperations; - readonly string: StringOperations; - readonly bytes: BytesOperations; - readonly int: IntOperations; - readonly float: FloatOperations; - readonly decimal: DecimalOperations; - readonly decimal128: Decimal128Operations; - readonly datetime: DatetimeOperations; - readonly duration: DurationOperations; - readonly enum: EnumOperations; - readonly extensibleEnum: ExtensibleEnumOperations; - readonly model: ModelOperations; - readonly collectionsString: CollectionsStringOperations; - readonly collectionsInt: CollectionsIntOperations; - readonly collectionsModel: CollectionsModelOperations; - readonly dictionaryString: DictionaryStringOperations; - readonly never: NeverOperations; - readonly unknownString: UnknownStringOperations; - readonly unknownInt: UnknownIntOperations; - readonly unknownDict: UnknownDictOperations; - readonly unknownArray: UnknownArrayOperations; - readonly stringLiteral: StringLiteralOperations; - readonly intLiteral: IntLiteralOperations; - readonly floatLiteral: FloatLiteralOperations; - readonly booleanLiteral: BooleanLiteralOperations; - readonly unionStringLiteral: UnionStringLiteralOperations; - readonly unionIntLiteral: UnionIntLiteralOperations; - readonly unionFloatLiteral: UnionFloatLiteralOperations; readonly unionEnumValue: UnionEnumValueOperations; + readonly unionFloatLiteral: UnionFloatLiteralOperations; + readonly unionIntLiteral: UnionIntLiteralOperations; + readonly unionStringLiteral: UnionStringLiteralOperations; + readonly booleanLiteral: BooleanLiteralOperations; + readonly floatLiteral: FloatLiteralOperations; + readonly intLiteral: IntLiteralOperations; + readonly stringLiteral: StringLiteralOperations; + readonly unknownArray: UnknownArrayOperations; + readonly unknownDict: UnknownDictOperations; + readonly unknownInt: UnknownIntOperations; + readonly unknownString: UnknownStringOperations; + readonly never: NeverOperations; + readonly dictionaryString: DictionaryStringOperations; + readonly collectionsModel: CollectionsModelOperations; + readonly collectionsInt: CollectionsIntOperations; + readonly collectionsString: CollectionsStringOperations; + readonly model: ModelOperations; + readonly extensibleEnum: ExtensibleEnumOperations; + readonly enum: EnumOperations; + readonly duration: DurationOperations; + readonly datetime: DatetimeOperations; + readonly decimal128: Decimal128Operations; + readonly decimal: DecimalOperations; + readonly float: FloatOperations; + readonly int: IntOperations; + readonly bytes: BytesOperations; + readonly string: StringOperations; + readonly boolean: BooleanOperations; } export declare interface ValueTypesClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/scalar/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/scalar/src/index.d.ts index db8733c172..8c32ce0c65 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/scalar/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/scalar/src/index.d.ts @@ -6,17 +6,17 @@ export declare interface BooleanGetOptionalParams extends OperationOptions { } export declare interface BooleanOperations { - get: (options?: BooleanGetOptionalParams) => Promise; put: (body: boolean, options?: BooleanPutOptionalParams) => Promise; + get: (options?: BooleanGetOptionalParams) => Promise; } export declare interface BooleanPutOptionalParams extends OperationOptions { } export declare interface Decimal128TypeOperations { - responseBody: (options?: Decimal128TypeResponseBodyOptionalParams) => Promise; - requestBody: (body: number, options?: Decimal128TypeRequestBodyOptionalParams) => Promise; requestParameter: (value: number, options?: Decimal128TypeRequestParameterOptionalParams) => Promise; + requestBody: (body: number, options?: Decimal128TypeRequestBodyOptionalParams) => Promise; + responseBody: (options?: Decimal128TypeResponseBodyOptionalParams) => Promise; } export declare interface Decimal128TypeRequestBodyOptionalParams extends OperationOptions { @@ -29,8 +29,8 @@ export declare interface Decimal128TypeResponseBodyOptionalParams extends Operat } export declare interface Decimal128VerifyOperations { - prepareVerify: (options?: Decimal128VerifyPrepareVerifyOptionalParams) => Promise; verify: (body: number, options?: Decimal128VerifyVerifyOptionalParams) => Promise; + prepareVerify: (options?: Decimal128VerifyPrepareVerifyOptionalParams) => Promise; } export declare interface Decimal128VerifyPrepareVerifyOptionalParams extends OperationOptions { @@ -40,9 +40,9 @@ export declare interface Decimal128VerifyVerifyOptionalParams extends OperationO } export declare interface DecimalTypeOperations { - responseBody: (options?: DecimalTypeResponseBodyOptionalParams) => Promise; - requestBody: (body: number, options?: DecimalTypeRequestBodyOptionalParams) => Promise; requestParameter: (value: number, options?: DecimalTypeRequestParameterOptionalParams) => Promise; + requestBody: (body: number, options?: DecimalTypeRequestBodyOptionalParams) => Promise; + responseBody: (options?: DecimalTypeResponseBodyOptionalParams) => Promise; } export declare interface DecimalTypeRequestBodyOptionalParams extends OperationOptions { @@ -55,8 +55,8 @@ export declare interface DecimalTypeResponseBodyOptionalParams extends Operation } export declare interface DecimalVerifyOperations { - prepareVerify: (options?: DecimalVerifyPrepareVerifyOptionalParams) => Promise; verify: (body: number, options?: DecimalVerifyVerifyOptionalParams) => Promise; + prepareVerify: (options?: DecimalVerifyPrepareVerifyOptionalParams) => Promise; } export declare interface DecimalVerifyPrepareVerifyOptionalParams extends OperationOptions { @@ -69,13 +69,13 @@ export declare class ScalarClient { private _client; readonly pipeline: Pipeline; constructor(options?: ScalarClientOptionalParams); - readonly string: StringOperations; - readonly boolean: BooleanOperations; - readonly unknown: UnknownOperations; - readonly decimalType: DecimalTypeOperations; - readonly decimal128Type: Decimal128TypeOperations; - readonly decimalVerify: DecimalVerifyOperations; readonly decimal128Verify: Decimal128VerifyOperations; + readonly decimalVerify: DecimalVerifyOperations; + readonly decimal128Type: Decimal128TypeOperations; + readonly decimalType: DecimalTypeOperations; + readonly unknown: UnknownOperations; + readonly boolean: BooleanOperations; + readonly string: StringOperations; } export declare interface ScalarClientOptionalParams extends ClientOptions { @@ -85,8 +85,8 @@ export declare interface StringGetOptionalParams extends OperationOptions { } export declare interface StringOperations { - get: (options?: StringGetOptionalParams) => Promise; put: (body: string, options?: StringPutOptionalParams) => Promise; + get: (options?: StringGetOptionalParams) => Promise; } export declare interface StringPutOptionalParams extends OperationOptions { @@ -96,8 +96,8 @@ export declare interface UnknownGetOptionalParams extends OperationOptions { } export declare interface UnknownOperations { - get: (options?: UnknownGetOptionalParams) => Promise; put: (body: any, options?: UnknownPutOptionalParams) => Promise; + get: (options?: UnknownGetOptionalParams) => Promise; } export declare interface UnknownPutOptionalParams extends OperationOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts index 0d7e3d7b81..92dfc0452b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/type/union/src/index.d.ts @@ -19,10 +19,10 @@ export declare interface EnumsOnlyGetOptionalParams extends OperationOptions { } export declare interface EnumsOnlyOperations { + send: (prop: EnumsOnlyCases, options?: EnumsOnlySendOptionalParams) => Promise; get: (options?: EnumsOnlyGetOptionalParams) => Promise<{ prop: EnumsOnlyCases; }>; - send: (prop: EnumsOnlyCases, options?: EnumsOnlySendOptionalParams) => Promise; } export declare interface EnumsOnlySendOptionalParams extends OperationOptions { @@ -32,10 +32,10 @@ export declare interface FloatsOnlyGetOptionalParams extends OperationOptions { } export declare interface FloatsOnlyOperations { + send: (prop: 1.1 | 2.2 | 3.3, options?: FloatsOnlySendOptionalParams) => Promise; get: (options?: FloatsOnlyGetOptionalParams) => Promise<{ prop: 1.1 | 2.2 | 3.3; }>; - send: (prop: 1.1 | 2.2 | 3.3, options?: FloatsOnlySendOptionalParams) => Promise; } export declare interface FloatsOnlySendOptionalParams extends OperationOptions { @@ -45,10 +45,10 @@ export declare interface IntsOnlyGetOptionalParams extends OperationOptions { } export declare interface IntsOnlyOperations { + send: (prop: 1 | 2 | 3, options?: IntsOnlySendOptionalParams) => Promise; get: (options?: IntsOnlyGetOptionalParams) => Promise<{ prop: 1 | 2 | 3; }>; - send: (prop: 1 | 2 | 3, options?: IntsOnlySendOptionalParams) => Promise; } export declare interface IntsOnlySendOptionalParams extends OperationOptions { @@ -70,10 +70,10 @@ export declare interface MixedLiteralsGetOptionalParams extends OperationOptions } export declare interface MixedLiteralsOperations { + send: (prop: MixedLiteralsCases, options?: MixedLiteralsSendOptionalParams) => Promise; get: (options?: MixedLiteralsGetOptionalParams) => Promise<{ prop: MixedLiteralsCases; }>; - send: (prop: MixedLiteralsCases, options?: MixedLiteralsSendOptionalParams) => Promise; } export declare interface MixedLiteralsSendOptionalParams extends OperationOptions { @@ -91,10 +91,10 @@ export declare interface MixedTypesGetOptionalParams extends OperationOptions { } export declare interface MixedTypesOperations { + send: (prop: MixedTypesCases, options?: MixedTypesSendOptionalParams) => Promise; get: (options?: MixedTypesGetOptionalParams) => Promise<{ prop: MixedTypesCases; }>; - send: (prop: MixedTypesCases, options?: MixedTypesSendOptionalParams) => Promise; } export declare interface MixedTypesSendOptionalParams extends OperationOptions { @@ -104,10 +104,10 @@ export declare interface ModelsOnlyGetOptionalParams extends OperationOptions { } export declare interface ModelsOnlyOperations { + send: (prop: Cat | Dog, options?: ModelsOnlySendOptionalParams) => Promise; get: (options?: ModelsOnlyGetOptionalParams) => Promise<{ prop: Cat | Dog; }>; - send: (prop: Cat | Dog, options?: ModelsOnlySendOptionalParams) => Promise; } export declare interface ModelsOnlySendOptionalParams extends OperationOptions { @@ -122,10 +122,10 @@ export declare interface StringAndArrayGetOptionalParams extends OperationOption } export declare interface StringAndArrayOperations { + send: (prop: StringAndArrayCases, options?: StringAndArraySendOptionalParams) => Promise; get: (options?: StringAndArrayGetOptionalParams) => Promise<{ prop: StringAndArrayCases; }>; - send: (prop: StringAndArrayCases, options?: StringAndArraySendOptionalParams) => Promise; } export declare interface StringAndArraySendOptionalParams extends OperationOptions { @@ -138,10 +138,10 @@ export declare interface StringExtensibleNamedGetOptionalParams extends Operatio } export declare interface StringExtensibleNamedOperations { + send: (prop: StringExtensibleNamedUnion, options?: StringExtensibleNamedSendOptionalParams) => Promise; get: (options?: StringExtensibleNamedGetOptionalParams) => Promise<{ prop: StringExtensibleNamedUnion; }>; - send: (prop: StringExtensibleNamedUnion, options?: StringExtensibleNamedSendOptionalParams) => Promise; } export declare interface StringExtensibleNamedSendOptionalParams extends OperationOptions { @@ -150,10 +150,10 @@ export declare interface StringExtensibleNamedSendOptionalParams extends Operati export declare type StringExtensibleNamedUnion = string; export declare interface StringExtensibleOperations { + send: (prop: string, options?: StringExtensibleSendOptionalParams) => Promise; get: (options?: StringExtensibleGetOptionalParams) => Promise<{ prop: string; }>; - send: (prop: string, options?: StringExtensibleSendOptionalParams) => Promise; } export declare interface StringExtensibleSendOptionalParams extends OperationOptions { @@ -163,10 +163,10 @@ export declare interface StringsOnlyGetOptionalParams extends OperationOptions { } export declare interface StringsOnlyOperations { + send: (prop: "a" | "b" | "c", options?: StringsOnlySendOptionalParams) => Promise; get: (options?: StringsOnlyGetOptionalParams) => Promise<{ prop: "a" | "b" | "c"; }>; - send: (prop: "a" | "b" | "c", options?: StringsOnlySendOptionalParams) => Promise; } export declare interface StringsOnlySendOptionalParams extends OperationOptions { @@ -176,16 +176,16 @@ export declare class UnionClient { private _client; readonly pipeline: Pipeline; constructor(options?: UnionClientOptionalParams); - readonly stringsOnly: StringsOnlyOperations; - readonly stringExtensible: StringExtensibleOperations; - readonly stringExtensibleNamed: StringExtensibleNamedOperations; - readonly intsOnly: IntsOnlyOperations; - readonly floatsOnly: FloatsOnlyOperations; - readonly modelsOnly: ModelsOnlyOperations; - readonly enumsOnly: EnumsOnlyOperations; - readonly stringAndArray: StringAndArrayOperations; - readonly mixedLiterals: MixedLiteralsOperations; readonly mixedTypes: MixedTypesOperations; + readonly mixedLiterals: MixedLiteralsOperations; + readonly stringAndArray: StringAndArrayOperations; + readonly enumsOnly: EnumsOnlyOperations; + readonly modelsOnly: ModelsOnlyOperations; + readonly floatsOnly: FloatsOnlyOperations; + readonly intsOnly: IntsOnlyOperations; + readonly stringExtensibleNamed: StringExtensibleNamedOperations; + readonly stringExtensible: StringExtensibleOperations; + readonly stringsOnly: StringsOnlyOperations; } export declare interface UnionClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/versioning/added/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/versioning/added/src/index.d.ts index b7dd92e177..94789a31a6 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/versioning/added/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/versioning/added/src/index.d.ts @@ -6,9 +6,9 @@ export declare class AddedClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, version: Versions, options?: AddedClientOptionalParams); - v1(headerV2: string, body: ModelV1, options?: V1OptionalParams): Promise; - v2(body: ModelV2, options?: V2OptionalParams): Promise; v2InInterface(body: ModelV2, options?: V2InInterfaceOptionalParams): Promise; + v2(body: ModelV2, options?: V2OptionalParams): Promise; + v1(body: ModelV1, headerV2: string, options?: V1OptionalParams): Promise; } export declare interface AddedClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/versioning/removed/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/versioning/removed/src/index.d.ts index 5e3981385f..03b965f7ce 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/versioning/removed/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/versioning/removed/src/index.d.ts @@ -24,8 +24,8 @@ export declare class RemovedClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, version: Versions, options?: RemovedClientOptionalParams); - v2(body: ModelV2, options?: V2OptionalParams): Promise; modelV3(body: ModelV3, options?: ModelV3OptionalParams): Promise; + v2(body: ModelV2, options?: V2OptionalParams): Promise; } export declare interface RemovedClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/versioning/renamedFrom/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/versioning/renamedFrom/src/index.d.ts index da7627b632..f1ed550f89 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/versioning/renamedFrom/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/versioning/renamedFrom/src/index.d.ts @@ -22,8 +22,8 @@ export declare class RenamedFromClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, version: Versions, options?: RenamedFromClientOptionalParams); - newOp(newQuery: string, body: NewModel, options?: NewOpOptionalParams): Promise; newOpInNewInterface(body: NewModel, options?: NewOpInNewInterfaceOptionalParams): Promise; + newOp(body: NewModel, newQuery: string, options?: NewOpOptionalParams): Promise; } export declare interface RenamedFromClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/generated/versioning/typeChangedFrom/src/index.d.ts b/packages/typespec-ts/test/modularIntegration/generated/versioning/typeChangedFrom/src/index.d.ts index 088cb12636..59c28ab532 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/versioning/typeChangedFrom/src/index.d.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/versioning/typeChangedFrom/src/index.d.ts @@ -14,7 +14,7 @@ export declare class TypeChangedFromClient { private _client; readonly pipeline: Pipeline; constructor(endpointParam: string, version: Versions, options?: TypeChangedFromClientOptionalParams); - test(param: string, body: TestModel, options?: TestOptionalParams): Promise; + test(body: TestModel, param: string, options?: TestOptionalParams): Promise; } export declare interface TypeChangedFromClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/modularIntegration/payloadContentNegotiation.spec.ts b/packages/typespec-ts/test/modularIntegration/payloadContentNegotiation.spec.ts index 9e9c240814..ab702afc04 100644 --- a/packages/typespec-ts/test/modularIntegration/payloadContentNegotiation.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/payloadContentNegotiation.spec.ts @@ -21,16 +21,12 @@ describe("Payload Content Negotiation Client", () => { }); it("should get image/png for same body in content negotiation", async () => { - const result = await client.sameBody.getAvatarAsPng({ - accept: "image/png" - }); + const result = await client.sameBody.getAvatarAsPng(); assert.strictEqual(uint8ArrayToString(result, "utf-8"), pngFile.toString()); }); it("should get image/jpeg for same body in content negotiation", async () => { - const result = await client.sameBody.getAvatarAsJpeg({ - accept: "image/jpeg" - }); + const result = await client.sameBody.getAvatarAsJpeg(); assert.strictEqual( uint8ArrayToString(result, "utf-8"), jpegImage.toString() @@ -38,16 +34,12 @@ describe("Payload Content Negotiation Client", () => { }); it("should get image/png for different body in content negotiation", async () => { - const result = await client.differentBody.getAvatarAsPng({ - accept: "image/png" - }); + const result = await client.differentBody.getAvatarAsPng(); assert.strictEqual(uint8ArrayToString(result, "utf-8"), pngFile.toString()); }); it("should get application/json for different body in content negotiation", async () => { - const result = await client.differentBody.getAvatarAsJson({ - accept: "application/json" - }); + const result = await client.differentBody.getAvatarAsJson(); assert.strictEqual( uint8ArrayToString(result.content, "utf-8"), pngFile.toString() diff --git a/packages/typespec-ts/test/modularIntegration/server.spec.ts b/packages/typespec-ts/test/modularIntegration/server.spec.ts index a7bda7798f..57b31d1ac6 100644 --- a/packages/typespec-ts/test/modularIntegration/server.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/server.spec.ts @@ -95,21 +95,38 @@ describe("Versioned Server Version Client", () => { }); it("should work with param with explicit value", async () => { - const result = await client.withQueryApiVersion({ + const client = new VersionedClient("http://localhost:3002", { + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + }, apiVersion: "2022-12-01-preview" }); + const result = await client.withQueryApiVersion(); assert.isUndefined(result); }); it("should work with path param", async () => { - const result = await client.withPathApiVersion("2022-12-01-preview"); + const client = new VersionedClient("http://localhost:3002", { + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + }, + apiVersion: "2022-12-01-preview" + }); + const result = await client.withPathApiVersion(); assert.isUndefined(result); }); it("should work with param with old value", async () => { - const result = await client.withQueryOldApiVersion({ + const client = new VersionedClient("http://localhost:3002", { + allowInsecureConnection: true, + retryOptions: { + maxRetries: 0 + }, apiVersion: "2021-01-01-preview" }); + const result = await client.withQueryOldApiVersion(); assert.isUndefined(result); }); }); diff --git a/packages/typespec-ts/test/modularIntegration/spreadParameters.spec.ts b/packages/typespec-ts/test/modularIntegration/spreadParameters.spec.ts index fd25140233..4621185dce 100644 --- a/packages/typespec-ts/test/modularIntegration/spreadParameters.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/spreadParameters.spec.ts @@ -74,8 +74,8 @@ describe("SpreadClient Client", () => { it("should spread alias with inner-model-parameter", async () => { const result = await client.alias.spreadParameterWithInnerModel( "1", + "foo", "bar", - "foo" ); assert.isUndefined(result); }); @@ -83,9 +83,9 @@ describe("SpreadClient Client", () => { it("should spread alias with inner-alias-parameter", async () => { const result = await client.alias.spreadParameterWithInnerAlias( "1", - "bar", "foo", - 1 + 1, + "bar" ); assert.isUndefined(result); }); diff --git a/packages/typespec-ts/test/modularIntegration/versioningAdded.spec.ts b/packages/typespec-ts/test/modularIntegration/versioningAdded.spec.ts index 2b8f8bf1c9..544095d1fc 100644 --- a/packages/typespec-ts/test/modularIntegration/versioningAdded.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/versioningAdded.spec.ts @@ -11,11 +11,11 @@ describe("VersioningAdded Rest Client", () => { }); it("versioning added v1", async () => { - const result = await client.v1("bar", { + const result = await client.v1({ prop: "foo", enumProp: "enumMemberV2", unionProp: 10 - }); + }, "bar"); assert.strictEqual(result.prop, "foo"); assert.strictEqual(result.enumProp, "enumMemberV2"); assert.strictEqual(result.unionProp, 10); diff --git a/packages/typespec-ts/test/modularIntegration/versioningRenamedFrom.spec.ts b/packages/typespec-ts/test/modularIntegration/versioningRenamedFrom.spec.ts index c6f11b9ed2..6a269a7814 100644 --- a/packages/typespec-ts/test/modularIntegration/versioningRenamedFrom.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/versioningRenamedFrom.spec.ts @@ -11,11 +11,11 @@ describe("VersioningRenamedFrom Rest Client", () => { }); it("versioning RenamedFrom ewOp test", async () => { - const result = await client.newOp("bar", { + const result = await client.newOp({ newProp: "foo", enumProp: "newEnumMember", unionProp: 10 - }); + }, "bar"); assert.strictEqual(result.newProp, "foo"); assert.strictEqual(result.enumProp, "newEnumMember"); assert.strictEqual(result.unionProp, 10); diff --git a/packages/typespec-ts/test/modularIntegration/versioningTypeChangedFrom.spec.ts b/packages/typespec-ts/test/modularIntegration/versioningTypeChangedFrom.spec.ts index 8ab11150f5..0531078f39 100644 --- a/packages/typespec-ts/test/modularIntegration/versioningTypeChangedFrom.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/versioningTypeChangedFrom.spec.ts @@ -11,10 +11,10 @@ describe("VersioningTypeChangedFrom Rest Client", () => { }); it("versioning typeChangedFrom test", async () => { - const result = await client.test("baz", { + const result = await client.test({ prop: "foo", changedProp: "bar" - }); + }, "baz"); assert.strictEqual(result.prop, "foo"); assert.strictEqual(result.changedProp, "bar"); }); diff --git a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts index f15ff261e9..445e97ee9f 100644 --- a/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts +++ b/packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts @@ -109,7 +109,7 @@ describe("spread record", () => { model Vegetables { ...Record; carrots: int64; - beans: int64; + beans: boolean; } op post(@body body: Vegetables): { @body body: Vegetables }; ` diff --git a/packages/typespec-ts/test/modularUnit/scenarios/anonymous/anonymous.md b/packages/typespec-ts/test/modularUnit/scenarios/anonymous/anonymous.md index 9db8741995..8356b3d5b1 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/anonymous/anonymous.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/anonymous/anonymous.md @@ -41,12 +41,12 @@ export function barSerializer(item: Bar): any { ```ts operations import { TestingContext as Client } from "./index.js"; -import { Bar } from "../models/models.js"; +import { Bar, barSerializer } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -58,23 +58,26 @@ export function _readSend( prop3: Date, prop4: string, prop5: Bar, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/{pathParam}", pathParam).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { queryParam: queryParam }, - body: { - prop1: prop1, - prop2: prop2, - prop3: prop3.toISOString(), - prop4: prop4, - prop5: { prop1: prop5["prop1"], prop2: prop5["prop2"] } - } - }); + return context + .path("/{pathParam}", pathParam) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + queryParameters: { queryParam: queryParam }, + body: { + prop1: prop1, + prop2: prop2, + prop3: prop3.toISOString(), + prop4: prop4, + prop5: barSerializer(prop5), + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -93,7 +96,7 @@ export async function read( prop3: Date, prop4: string, prop5: Bar, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend( context, @@ -104,7 +107,7 @@ export async function read( prop3, prop4, prop5, - options + options, ); return _readDeserialize(result); } @@ -150,8 +153,8 @@ export function barSerializer(item: Bar): any { ## Models withOptions ```ts models:withOptions -import { OperationOptions } from "@azure-rest/core-client"; import { Bar } from "../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ export interface ReadOptionalParams extends OperationOptions { @@ -164,11 +167,12 @@ export interface ReadOptionalParams extends OperationOptions { ```ts operations import { TestingContext as Client } from "./index.js"; +import { barSerializer } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -178,26 +182,26 @@ export function _readSend( prop1: string, prop2: number, prop4: string, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/{pathParam}", pathParam).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { queryParam: queryParam }, - body: { - prop1: prop1, - prop2: prop2, - prop3: options?.prop3?.toISOString(), - prop4: prop4, - prop5: { - prop1: options?.prop5?.["prop1"], - prop2: options?.prop5?.["prop2"] - } - } - }); + return context + .path("/{pathParam}", pathParam) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + queryParameters: { queryParam: queryParam }, + body: { + prop1: prop1, + prop2: prop2, + prop3: !options?.prop3 ? options?.prop3 : options?.prop3.toISOString(), + prop4: prop4, + prop5: !options?.prop5 ? options?.prop5 : barSerializer(options?.prop5), + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -214,7 +218,7 @@ export async function read( prop1: string, prop2: number, prop4: string, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend( context, @@ -223,7 +227,7 @@ export async function read( prop1, prop2, prop4, - options + options, ); return _readDeserialize(result); } @@ -271,8 +275,8 @@ export function barSerializer(item: Bar): any { ## Bar Model withOptions ```ts models:withOptions -import { OperationOptions } from "@azure-rest/core-client"; import { Bar } from "../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ export interface ReadOptionalParams extends OperationOptions { @@ -285,38 +289,39 @@ export interface ReadOptionalParams extends OperationOptions { ```ts operations import { TestingContext as Client } from "./index.js"; +import { barSerializer } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, pathParam: string, prop1: string, + prop2: number, prop4: string, queryParam: string, - prop2: number, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/{pathParam}/{prop1}", pathParam, prop1).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { prop4: prop4, queryParam: queryParam }, - body: { - prop2: prop2, - prop3: options?.prop3?.toISOString(), - prop5: { - prop1: options?.prop5?.["prop1"], - prop2: options?.prop5?.["prop2"] - } - } - }); + return context + .path("/{pathParam}/{prop1}", pathParam, prop1) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + queryParameters: { prop4: prop4, queryParam: queryParam }, + body: { + prop2: prop2, + prop3: !options?.prop3 ? options?.prop3 : options?.prop3.toISOString(), + prop5: !options?.prop5 ? options?.prop5 : barSerializer(options?.prop5), + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -330,19 +335,19 @@ export async function read( context: Client, pathParam: string, prop1: string, + prop2: number, prop4: string, queryParam: string, - prop2: number, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend( context, pathParam, prop1, + prop2, prop4, queryParam, - prop2, - options + options, ); return _readDeserialize(result); } @@ -407,7 +412,7 @@ export function fooSerializer(item: Foo): any { prop2: item["prop2"], prop3: item["prop3"].toISOString(), prop4: item["prop4"], - prop5: barSerializer(item["prop5"]) + prop5: barSerializer(item["prop5"]), }; } ``` @@ -421,7 +426,7 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -429,17 +434,20 @@ export function _readSend( pathParam: string, queryParam: string, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/{pathParam}", pathParam).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { queryParam: queryParam }, - body: fooSerializer(body) - }); + return context + .path("/{pathParam}", pathParam) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + queryParameters: { queryParam: queryParam }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -454,7 +462,7 @@ export async function read( pathParam: string, queryParam: string, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, pathParam, queryParam, body, options); return _readDeserialize(result); @@ -489,7 +497,7 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -497,17 +505,20 @@ export function _readSend( pathParam: string, queryParam: string, body: Record, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/{pathParam}", pathParam).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { queryParam: queryParam }, - body: _readRequestSerializer(body) - }); + return context + .path("/{pathParam}", pathParam) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + queryParameters: { queryParam: queryParam }, + body: _readRequestSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -522,7 +533,7 @@ export async function read( pathParam: string, queryParam: string, body: Record, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, pathParam, queryParam, body, options); return _readDeserialize(result); @@ -571,7 +582,7 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( @@ -582,17 +593,20 @@ export function _readSend( prop1: string; prop2: Bar; }, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/{pathParam}", pathParam).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { queryParam: queryParam }, - body: _readRequestSerializer(test) - }); + return context + .path("/{pathParam}", pathParam) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + queryParameters: { queryParam: queryParam }, + body: _readRequestSerializer(test), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -610,7 +624,7 @@ export async function read( prop1: string; prop2: Bar; }, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, pathParam, queryParam, test, options); return _readDeserialize(result); @@ -654,22 +668,25 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Test, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: testSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + body: testSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -682,7 +699,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Test, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -730,22 +747,25 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Test, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: testSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + body: testSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -758,7 +778,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Test, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -793,20 +813,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -818,7 +844,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise> { const result = await _readSend(context, options); return _readDeserialize(result); @@ -855,20 +881,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -880,7 +912,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -909,7 +941,7 @@ export interface _ReadResponse { export function _readResponseDeserializer(item: any): _ReadResponse { return { - foo: !item["foo"] ? item["foo"] : _readResponseFooDeserializer(item["foo"]) + foo: !item["foo"] ? item["foo"] : _readResponseFooDeserializer(item["foo"]), }; } @@ -920,7 +952,7 @@ export interface _ReadResponseFoo { export function _readResponseFooDeserializer(item: any): _ReadResponseFoo { return { - bar: item["bar"] + bar: item["bar"], }; } ``` @@ -934,16 +966,22 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise<{ @@ -961,7 +999,7 @@ export async function _readDeserialize(result: PathUncheckedResponse): Promise<{ export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise<{ foo?: { bar: string | null; @@ -1007,14 +1045,14 @@ export function returnBodyDeserializer(item: any): ReturnBody { return { emptyAnomyous: _returnBodyEmptyAnomyousDeserializer(item["emptyAnomyous"]), emptyAnomyousArray: returnBodyEmptyAnomyousArrayArrayDeserializer( - item["emptyAnomyousArray"] + item["emptyAnomyousArray"], ), emptyAnomyousDict: returnBodyEmptyAnomyousDictRecordDeserializer( - item["emptyAnomyousDict"] + item["emptyAnomyousDict"], ), emptyModel: emptyModelDeserializer(item["emptyModel"]), emptyModelArray: emptyModelArrayDeserializer(item["emptyModelArray"]), - emptyModelDict: emptyModelRecordDeserializer(item["emptyModelDict"]) + emptyModelDict: emptyModelRecordDeserializer(item["emptyModelDict"]), }; } @@ -1022,13 +1060,13 @@ export function returnBodyDeserializer(item: any): ReturnBody { export interface _ReturnBodyEmptyAnomyous {} export function _returnBodyEmptyAnomyousDeserializer( - item: any + item: any, ): _ReturnBodyEmptyAnomyous { return item; } export function returnBodyEmptyAnomyousArrayArrayDeserializer( - result: Array<_ReturnBodyEmptyAnomyousArray> + result: Array<_ReturnBodyEmptyAnomyousArray>, ): any[] { return result.map((item) => { return _returnBodyEmptyAnomyousArrayDeserializer(item); @@ -1039,13 +1077,13 @@ export function returnBodyEmptyAnomyousArrayArrayDeserializer( export interface _ReturnBodyEmptyAnomyousArray {} export function _returnBodyEmptyAnomyousArrayDeserializer( - item: any + item: any, ): _ReturnBodyEmptyAnomyousArray { return item; } export function returnBodyEmptyAnomyousDictRecordDeserializer( - item: Record + item: Record, ): Record { const result: Record = {}; Object.keys(item).map((key) => { @@ -1060,7 +1098,7 @@ export function returnBodyEmptyAnomyousDictRecordDeserializer( export interface _ReturnBodyEmptyAnomyousDict {} export function _returnBodyEmptyAnomyousDictDeserializer( - item: any + item: any, ): _ReturnBodyEmptyAnomyousDict { return item; } @@ -1079,7 +1117,7 @@ export function emptyModelArrayDeserializer(result: Array): any[] { } export function emptyModelRecordDeserializer( - item: Record + item: Record, ): Record { const result: Record = {}; Object.keys(item).map((key) => { @@ -1098,20 +1136,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1123,7 +1167,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1178,7 +1222,7 @@ export interface Foz { export function fozDeserializer(item: any): Foz { return { - baz: _fozBazDeserializer(item["baz"]) + baz: _fozBazDeserializer(item["baz"]), }; } @@ -1211,19 +1255,19 @@ export function _fozBazDeserializer(item: any): _FozBaz { ? item["test"] : simpleModelArrayDeserializer(item["test"]), nonemptyAnomyous: _fozBazNonemptyAnomyousDeserializer( - item["nonemptyAnomyous"] + item["nonemptyAnomyous"], ), nonemptyAnomyousArray: fozBazNonemptyAnomyousArrayArrayDeserializer( - item["nonemptyAnomyousArray"] + item["nonemptyAnomyousArray"], ), nonemptyAnomyousDict: fozBazNonemptyAnomyousDictRecordDeserializer( - item["nonemptyAnomyousDict"] - ) + item["nonemptyAnomyousDict"], + ), }; } export function simpleModelArrayDeserializer( - result: Array + result: Array, ): any[] { return result.map((item) => { return simpleModelDeserializer(item); @@ -1237,7 +1281,7 @@ export interface SimpleModel { export function simpleModelDeserializer(item: any): SimpleModel { return { - test: item["test"] + test: item["test"], }; } @@ -1247,15 +1291,15 @@ export interface _FozBazNonemptyAnomyous { } export function _fozBazNonemptyAnomyousDeserializer( - item: any + item: any, ): _FozBazNonemptyAnomyous { return { - a: item["a"] + a: item["a"], }; } export function fozBazNonemptyAnomyousArrayArrayDeserializer( - result: Array<_FozBazNonemptyAnomyousArray> + result: Array<_FozBazNonemptyAnomyousArray>, ): any[] { return result.map((item) => { return _fozBazNonemptyAnomyousArrayDeserializer(item); @@ -1268,15 +1312,15 @@ export interface _FozBazNonemptyAnomyousArray { } export function _fozBazNonemptyAnomyousArrayDeserializer( - item: any + item: any, ): _FozBazNonemptyAnomyousArray { return { - b: item["b"] + b: item["b"], }; } export function fozBazNonemptyAnomyousDictRecordDeserializer( - item: Record + item: Record, ): Record { const result: Record = {}; Object.keys(item).map((key) => { @@ -1293,12 +1337,12 @@ export interface _FozBazNonemptyAnomyousDict { } export function _fozBazNonemptyAnomyousDictDeserializer( - item: any + item: any, ): _FozBazNonemptyAnomyousDict { return { c: item["c"].map((p: any) => { return p; - }) + }), }; } ``` @@ -1312,20 +1356,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1337,7 +1387,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); diff --git a/packages/typespec-ts/test/modularUnit/scenarios/apiOperations/apiOperations.md b/packages/typespec-ts/test/modularUnit/scenarios/apiOperations/apiOperations.md index 679d86f05f..d90f9ba28b 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/apiOperations/apiOperations.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/apiOperations/apiOperations.md @@ -20,23 +20,25 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _uploadFileViaBodySend( context: Client, body: Uint8Array, - options: UploadFileViaBodyOptionalParams = { requestOptions: {} } + options: UploadFileViaBodyOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/uploadFileViaBody").post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "application/octet-stream", - body: body - }); + return context + .path("/uploadFileViaBody") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/octet-stream", + body: body, + }); } export async function _uploadFileViaBodyDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -49,7 +51,7 @@ export async function _uploadFileViaBodyDeserialize( export async function uploadFileViaBody( context: Client, body: Uint8Array, - options: UploadFileViaBodyOptionalParams = { requestOptions: {} } + options: UploadFileViaBodyOptionalParams = { requestOptions: {} }, ): Promise { const result = await _uploadFileViaBodySend(context, body, options); return _uploadFileViaBodyDeserialize(result); @@ -79,23 +81,25 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _uploadFileViaBodySend( context: Client, body: Uint8Array, - options: UploadFileViaBodyOptionalParams = { requestOptions: {} } + options: UploadFileViaBodyOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/uploadFileViaBody").post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "application/octet-stream", - body: body - }); + return context + .path("/uploadFileViaBody") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/octet-stream", + body: body, + }); } export async function _uploadFileViaBodyDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -108,7 +112,7 @@ export async function _uploadFileViaBodyDeserialize( export async function uploadFileViaBody( context: Client, body: Uint8Array, - options: UploadFileViaBodyOptionalParams = { requestOptions: {} } + options: UploadFileViaBodyOptionalParams = { requestOptions: {} }, ): Promise { const result = await _uploadFileViaBodySend(context, body, options); return _uploadFileViaBodyDeserialize(result); @@ -146,7 +150,7 @@ export interface _UploadFileRequest { export function _uploadFileRequestSerializer(item: _UploadFileRequest): any { return { name: item["name"], - file: uint8ArrayToString(item["file"], "base64") + file: uint8ArrayToString(item["file"], "base64"), }; } ``` @@ -160,7 +164,7 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _uploadFileSend( @@ -169,17 +173,19 @@ export function _uploadFileSend( name: string; file: Uint8Array; }, - options: UploadFileOptionalParams = { requestOptions: {} } + options: UploadFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/uploadFile").post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: _uploadFileRequestSerializer(body) - }); + return context + .path("/uploadFile") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "multipart/form-data", + body: _uploadFileRequestSerializer(body), + }); } export async function _uploadFileDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -195,7 +201,7 @@ export async function uploadFile( name: string; file: Uint8Array; }, - options: UploadFileOptionalParams = { requestOptions: {} } + options: UploadFileOptionalParams = { requestOptions: {} }, ): Promise { const result = await _uploadFileSend(context, body, options); return _uploadFileDeserialize(result); @@ -232,7 +238,7 @@ export function _uploadFilesRequestSerializer(item: _UploadFilesRequest): any { return { files: item["files"].map((p: any) => { return uint8ArrayToString(p, "base64"); - }) + }), }; } ``` @@ -246,7 +252,7 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _uploadFilesSend( @@ -254,17 +260,19 @@ export function _uploadFilesSend( body: { files: Uint8Array[]; }, - options: UploadFilesOptionalParams = { requestOptions: {} } + options: UploadFilesOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/uploadFiles").post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: _uploadFilesRequestSerializer(body) - }); + return context + .path("/uploadFiles") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "multipart/form-data", + body: _uploadFilesRequestSerializer(body), + }); } export async function _uploadFilesDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -279,7 +287,7 @@ export async function uploadFiles( body: { files: Uint8Array[]; }, - options: UploadFilesOptionalParams = { requestOptions: {} } + options: UploadFilesOptionalParams = { requestOptions: {} }, ): Promise { const result = await _uploadFilesSend(context, body, options); return _uploadFilesDeserialize(result); @@ -307,20 +315,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _downloadFileSend( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/downloadFile") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/octet-stream", + ...options.requestOptions?.headers, + }, + }); } export async function _downloadFileDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -332,7 +346,7 @@ export async function _downloadFileDeserialize( export async function downloadFile( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): Promise { const result = await _downloadFileSend(context, options); return _downloadFileDeserialize(result); @@ -363,20 +377,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _downloadFileSend( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/downloadFile") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/octet-stream", + ...options.requestOptions?.headers, + }, + }); } export async function _downloadFileDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -388,7 +408,7 @@ export async function _downloadFileDeserialize( export async function downloadFile( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): Promise { const result = await _downloadFileSend(context, options); return _downloadFileDeserialize(result); @@ -423,14 +443,14 @@ export interface _DownloadFileResponse { } export function _downloadFileResponseDeserializer( - item: any + item: any, ): _DownloadFileResponse { return { name: item["name"], file: typeof item["file"] === "string" ? stringToUint8Array(item["file"], "base64") - : item["file"] + : item["file"], }; } ``` @@ -444,20 +464,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _downloadFileSend( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/downloadFile") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "multipart/form-data", + ...options.requestOptions?.headers, + }, + }); } export async function _downloadFileDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise<{ name: string; file: Uint8Array; @@ -472,7 +498,7 @@ export async function _downloadFileDeserialize( export async function downloadFile( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): Promise<{ name: string; file: Uint8Array; @@ -512,13 +538,13 @@ export interface _DownloadFileResponse { } export function _downloadFileResponseDeserializer( - item: any + item: any, ): _DownloadFileResponse { return { name: item["name"], file: item["file"].map((p: any) => { return typeof p === "string" ? stringToUint8Array(p, "base64") : p; - }) + }), }; } ``` @@ -532,20 +558,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _downloadFileSend( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/downloadFile") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "multipart/form-data", + ...options.requestOptions?.headers, + }, + }); } export async function _downloadFileDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise<{ name: string; file: Uint8Array[]; @@ -560,7 +592,7 @@ export async function _downloadFileDeserialize( export async function downloadFile( context: Client, - options: DownloadFileOptionalParams = { requestOptions: {} } + options: DownloadFileOptionalParams = { requestOptions: {} }, ): Promise<{ name: string; file: Uint8Array[]; @@ -570,6 +602,73 @@ export async function downloadFile( } ``` +# should handle contentTypes with default value in parameters + +Api operations should handle contentTypes has default value + +## TypeSpec + +```tsp +@route("/uploadFileViaBody") +@post op uploadFileViaBody( + @header contentType: string = "application/octet-stream", + @body body: bytes +): void; +``` + +## Operations + +```ts operations +import { TestingContext as Client } from "./index.js"; +import { + StreamableMethod, + PathUncheckedResponse, + createRestError, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; + +export function _uploadFileViaBodySend( + context: Client, + contentType: string, + body: Uint8Array, + options: UploadFileViaBodyOptionalParams = { requestOptions: {} }, +): StreamableMethod { + return context + .path("/uploadFileViaBody") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: contentType, + body: body, + }); +} + +export async function _uploadFileViaBodyDeserialize( + result: PathUncheckedResponse, +): Promise { + const expectedStatuses = ["204"]; + if (!expectedStatuses.includes(result.status)) { + throw createRestError(result); + } + + return; +} + +export async function uploadFileViaBody( + context: Client, + contentType: string, + body: Uint8Array, + options: UploadFileViaBodyOptionalParams = { requestOptions: {} }, +): Promise { + const result = await _uploadFileViaBodySend( + context, + contentType, + body, + options, + ); + return _uploadFileViaBodyDeserialize(result); +} +``` + # should generate apiVersion if there's a client level apiVersion but without default value ## TypeSpec @@ -590,20 +689,28 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( context: Client, - options: TestOptionalParams = { requestOptions: {} } + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": apiVersion }, + }); } export async function _testDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -615,9 +722,10 @@ export async function _testDeserialize( export async function test( context: Client, - options: TestOptionalParams = { requestOptions: {} } + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _testSend(context, options); + const result = await _testSend(context, apiVersion, options); return _testDeserialize(result); } ``` @@ -635,8 +743,10 @@ export interface TestingClientOptionalParams extends ClientOptions {} export function createTesting( endpointParam: string, - options: TestingClientOptionalParams = {} + options: TestingClientOptionalParams = {}, ): TestingContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` @@ -644,14 +754,15 @@ export function createTesting( const { apiVersion: _, ...updatedOptions } = { ...options, userAgentOptions: { userAgentPrefix }, - loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info } + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; - const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? String(endpointParam), - undefined, - updatedOptions - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); + if (options.apiVersion) { + logger.warning( + "This client does not support client api-version, please change it at the operation level", + ); + } return clientContext; } ``` @@ -670,7 +781,7 @@ export class TestingClient { constructor( endpointParam: string, - options: TestingClientOptionalParams = {} + options: TestingClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions @@ -678,13 +789,16 @@ export class TestingClient { : `azsdk-js-client`; this._client = createTesting(endpointParam, { ...options, - userAgentOptions: { userAgentPrefix } + userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; } - test(options: TestOptionalParams = { requestOptions: {} }): Promise { - return test(this._client, options); + test( + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, + ): Promise { + return test(this._client, apiVersion, options); } } ``` @@ -706,8 +820,6 @@ mustEmptyDiagnostic: false needNamespaces: true needAzureCore: false withRawContent: false -withVersionedApiVersion: true -ignoreWeirdLine: false ``` ## Operations @@ -718,20 +830,28 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( context: Client, - options: TestOptionalParams = { requestOptions: {} } + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": apiVersion }, + }); } export async function _testDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -743,9 +863,10 @@ export async function _testDeserialize( export async function test( context: Client, - options: TestOptionalParams = { requestOptions: {} } + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _testSend(context, options); + const result = await _testSend(context, apiVersion, options); return _testDeserialize(result); } ``` @@ -759,14 +880,14 @@ import { Client, ClientOptions, getClient } from "@azure-rest/core-client"; export interface TestingContext extends Client {} /** Optional parameters for the client. */ -export interface TestingClientOptionalParams extends ClientOptions { - apiVersion?: string; -} +export interface TestingClientOptionalParams extends ClientOptions {} export function createTesting( endpointParam: string, - options: TestingClientOptionalParams = {} + options: TestingClientOptionalParams = {}, ): TestingContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` @@ -774,30 +895,15 @@ export function createTesting( const { apiVersion: _, ...updatedOptions } = { ...options, userAgentOptions: { userAgentPrefix }, - loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info } + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; - const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? String(endpointParam), - undefined, - updatedOptions - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); - const apiVersion = options.apiVersion ?? "2022-05-15-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); - } - }); + if (options.apiVersion) { + logger.warning( + "This client does not support client api-version, please change it at the operation level", + ); + } return clientContext; } ``` @@ -816,7 +922,7 @@ export class TestingClient { constructor( endpointParam: string, - options: TestingClientOptionalParams = {} + options: TestingClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions @@ -824,13 +930,16 @@ export class TestingClient { : `azsdk-js-client`; this._client = createTesting(endpointParam, { ...options, - userAgentOptions: { userAgentPrefix } + userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; } - test(options: TestOptionalParams = { requestOptions: {} }): Promise { - return test(this._client, options); + test( + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, + ): Promise { + return test(this._client, apiVersion, options); } } ``` @@ -858,22 +967,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -export function _testSend( +export function _test1Send( context: Client, - apiVersion: string, - options: TestOptionalParams = { requestOptions: {} } + options: Test1OptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/test").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { "api-version": apiVersion } - }); + return context + .path("/test1") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } -export async function _testDeserialize( - result: PathUncheckedResponse +export async function _test1Deserialize( + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -883,26 +996,33 @@ export async function _testDeserialize( return result.body; } -export async function test( +export async function test1( context: Client, - apiVersion: string, - options: TestOptionalParams = { requestOptions: {} } + options: Test1OptionalParams = { requestOptions: {} }, ): Promise { - const result = await _testSend(context, apiVersion, options); - return _testDeserialize(result); + const result = await _test1Send(context, options); + return _test1Deserialize(result); } -export function _test1Send( +export function _testSend( context: Client, - options: Test1OptionalParams = { requestOptions: {} } + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path("/test1") - .get({ ...operationOptionsToRequestParameters(options) }); + .path("/test") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + queryParameters: { "api-version": apiVersion }, + }); } -export async function _test1Deserialize( - result: PathUncheckedResponse +export async function _testDeserialize( + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -912,12 +1032,13 @@ export async function _test1Deserialize( return result.body; } -export async function test1( +export async function test( context: Client, - options: Test1OptionalParams = { requestOptions: {} } + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _test1Send(context, options); - return _test1Deserialize(result); + const result = await _testSend(context, apiVersion, options); + return _testDeserialize(result); } ``` @@ -934,8 +1055,10 @@ export interface TestingClientOptionalParams extends ClientOptions {} export function createTesting( endpointParam: string, - options: TestingClientOptionalParams = {} + options: TestingClientOptionalParams = {}, ): TestingContext { + const endpointUrl = + options.endpoint ?? options.baseUrl ?? String(endpointParam); const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions ? `${prefixFromOptions} azsdk-js-api` @@ -943,17 +1066,13 @@ export function createTesting( const { apiVersion: _, ...updatedOptions } = { ...options, userAgentOptions: { userAgentPrefix }, - loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info } + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; - const clientContext = getClient( - options.endpoint ?? options.baseUrl ?? String(endpointParam), - undefined, - updatedOptions - ); + const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); if (options.apiVersion) { logger.warning( - "This client does not support client api-version, please change it at the operation level" + "This client does not support client api-version, please change it at the operation level", ); } return clientContext; @@ -974,7 +1093,7 @@ export class TestingClient { constructor( endpointParam: string, - options: TestingClientOptionalParams = {} + options: TestingClientOptionalParams = {}, ) { const prefixFromOptions = options?.userAgentOptions?.userAgentPrefix; const userAgentPrefix = prefixFromOptions @@ -982,22 +1101,22 @@ export class TestingClient { : `azsdk-js-client`; this._client = createTesting(endpointParam, { ...options, - userAgentOptions: { userAgentPrefix } + userAgentOptions: { userAgentPrefix }, }); this.pipeline = this._client.pipeline; } - test( - apiVersion: string, - options: TestOptionalParams = { requestOptions: {} } + test1( + options: Test1OptionalParams = { requestOptions: {} }, ): Promise { - return test(this._client, apiVersion, options); + return test1(this._client, options); } - test1( - options: Test1OptionalParams = { requestOptions: {} } + test( + apiVersion: string, + options: TestOptionalParams = { requestOptions: {} }, ): Promise { - return test1(this._client, options); + return test(this._client, apiVersion, options); } } ``` diff --git a/packages/typespec-ts/test/modularUnit/scenarios/clientContext/clientContext.md b/packages/typespec-ts/test/modularUnit/scenarios/clientContext/clientContext.md index 2574fe3c34..4b05d6c25e 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/clientContext/clientContext.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/clientContext/clientContext.md @@ -66,12 +66,12 @@ export interface ServiceContext extends Client {} /** Optional parameters for the client. */ export interface ServiceClientOptionalParams extends ClientOptions { /** Need to be set as 'default', 'multi-client', 'renamed-operation', 'two-operation-group' in client. */ - client?: ClientType; + clientParam?: ClientType; } export function createService( endpointParam: string, - options: ServiceClientOptionalParams = {} + options: ServiceClientOptionalParams = {}, ): ServiceContext { const clientParam = options.clientParam ?? "default"; const endpointUrl = @@ -85,13 +85,13 @@ export function createService( const { apiVersion: _, ...updatedOptions } = { ...options, userAgentOptions: { userAgentPrefix }, - loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info } + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); if (options.apiVersion) { logger.warning( - "This client does not support client api-version, please change it at the operation level" + "This client does not support client api-version, please change it at the operation level", ); } return clientContext; @@ -166,11 +166,11 @@ export interface ServiceContext extends Client {} /** Optional parameters for the client. */ export interface ServiceClientOptionalParams extends ClientOptions { /** Need to be set as 'default', 'multi-client', 'renamed-operation', 'two-operation-group' in client. */ - client?: ClientType; + clientParam?: ClientType; } export function createService( - options: ServiceClientOptionalParams = {} + options: ServiceClientOptionalParams = {}, ): ServiceContext { const endpointParam = options.endpointParam ?? "http://localhost:3000"; const clientParam = options.clientParam ?? "default"; @@ -185,13 +185,13 @@ export function createService( const { apiVersion: _, ...updatedOptions } = { ...options, userAgentOptions: { userAgentPrefix }, - loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info } + loggingOptions: { logger: options.loggingOptions?.logger ?? logger.info }, }; const clientContext = getClient(endpointUrl, undefined, updatedOptions); clientContext.pipeline.removePolicy({ name: "ApiVersionPolicy" }); if (options.apiVersion) { logger.warning( - "This client does not support client api-version, please change it at the operation level" + "This client does not support client api-version, please change it at the operation level", ); } return clientContext; diff --git a/packages/typespec-ts/test/modularUnit/scenarios/enumUnion/enumUnion.md b/packages/typespec-ts/test/modularUnit/scenarios/enumUnion/enumUnion.md index 9f1e6d58eb..e2cb86ea40 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/enumUnion/enumUnion.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/enumUnion/enumUnion.md @@ -53,24 +53,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, contentType: SchemaContentTypeValues, body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - contentType: contentType, - body: body - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: contentType, + body: body, + }); } export async function _getDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -84,7 +86,7 @@ export async function get( context: Client, contentType: SchemaContentTypeValues, body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): Promise { const result = await _getSend(context, contentType, body, options); return _getDeserialize(result); @@ -225,7 +227,7 @@ export type SchemaContentTypeValues = | string; export function schemaContentTypeValuesSerializer( - item: SchemaContentTypeValues + item: SchemaContentTypeValues, ): any { return item; } @@ -285,7 +287,7 @@ export type SchemaContentTypeValues = | string; export function schemaContentTypeValuesSerializer( - item: SchemaContentTypeValues + item: SchemaContentTypeValues, ): any { return item; } @@ -386,7 +388,7 @@ export type SchemaContentTypeValues = | string; export function schemaContentTypeValuesSerializer( - item: SchemaContentTypeValues + item: SchemaContentTypeValues, ): any { return item; } @@ -446,7 +448,7 @@ export type SchemaContentTypeValues = | string; export function schemaContentTypeValuesSerializer( - item: SchemaContentTypeValues + item: SchemaContentTypeValues, ): any { return item; } @@ -500,24 +502,30 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, testHeader: "A" | "B", body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - headers: { "test-header": testHeader }, - body: body - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + "test-header": testHeader, + ...options.requestOptions?.headers, + }, + body: body, + }); } export async function _getDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -531,7 +539,7 @@ export async function get( context: Client, testHeader: "A" | "B", body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): Promise { const result = await _getSend(context, testHeader, body, options); return _getDeserialize(result); @@ -582,24 +590,30 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, testHeader: string, body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - headers: { "test-header": testHeader }, - body: body - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + "test-header": testHeader, + ...options.requestOptions?.headers, + }, + body: body, + }); } export async function _getDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -613,7 +627,7 @@ export async function get( context: Client, testHeader: string, body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): Promise { const result = await _getSend(context, testHeader, body, options); return _getDeserialize(result); @@ -1154,7 +1168,7 @@ export enum KnownImageSize { * A taller image size of 1792x1024 pixels. * Only supported with dall-e-3 models. */ - size1024x1792 = "1024x1792" + size1024x1792 = "1024x1792", } ``` diff --git a/packages/typespec-ts/test/modularUnit/scenarios/example/example.md b/packages/typespec-ts/test/modularUnit/scenarios/example/example.md index 7042622afc..80d54437fc 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/example/example.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/example/example.md @@ -95,7 +95,13 @@ export function _readSend( ): StreamableMethod { return context .path("/{id}", id) - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/apiVersion/apiVersionAsFixedEnum.md b/packages/typespec-ts/test/modularUnit/scenarios/models/apiVersion/apiVersionAsFixedEnum.md index 309ff5e3f8..a25f45fa19 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/models/apiVersion/apiVersionAsFixedEnum.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/apiVersion/apiVersionAsFixedEnum.md @@ -49,7 +49,6 @@ Should normal operation with enum parameter: ```ts operations import { ContosoContext as Client } from "./index.js"; -import { Versions } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, @@ -59,14 +58,17 @@ import { export function _fooSend( context: Client, - apiVersion: Versions, options: FooOptionalParams = { requestOptions: {} }, ): StreamableMethod { + context.pipeline.removePolicy({ name: "ClientApiVersionPolicy" }); return context .path("/") .get({ ...operationOptionsToRequestParameters(options), - headers: { "api-version": apiVersion }, + headers: { + "api-version": context.apiVersion, + ...options.requestOptions?.headers, + }, }); } @@ -83,10 +85,9 @@ export async function _fooDeserialize( export async function foo( context: Client, - apiVersion: Versions, options: FooOptionalParams = { requestOptions: {} }, ): Promise { - const result = await _fooSend(context, apiVersion, options); + const result = await _fooSend(context, options); return _fooDeserialize(result); } ``` diff --git a/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/errorModels.md b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/errorModels.md index 2de9734445..8b180e5c0e 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/errorModels.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/models/serialization/errorModels.md @@ -33,7 +33,7 @@ export interface Foo { export function fooDeserializer(item: any): Foo { return { - name: item["name"] + name: item["name"], }; } ``` @@ -76,7 +76,7 @@ export interface Foo { export function fooDeserializer(item: any): Foo { return { name: item["name"], - options: errorDetailDeserializer(item["options"]) + options: errorDetailDeserializer(item["options"]), }; } @@ -88,7 +88,7 @@ export interface ErrorDetail { export function errorDetailDeserializer(item: any): ErrorDetail { return { - message: item["message"] + message: item["message"], }; } ``` diff --git a/packages/typespec-ts/test/modularUnit/scenarios/modelsGenerator/modelsGenerator.md b/packages/typespec-ts/test/modularUnit/scenarios/modelsGenerator/modelsGenerator.md index af52aff61a..039b0b0e73 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/modelsGenerator/modelsGenerator.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/modelsGenerator/modelsGenerator.md @@ -64,7 +64,7 @@ export function inputOutputModelSerializer(item: InputOutputModel): any { export function inputOutputModelDeserializer(item: any): InputOutputModel { return { - prop: item["prop"] + prop: item["prop"], }; } ``` @@ -120,7 +120,7 @@ export function inputOutputModelSerializer(item: InputOutputModel): any { export function inputOutputModelDeserializer(item: any): InputOutputModel { return { - prop: item["prop"] + prop: item["prop"], }; } ``` @@ -175,7 +175,7 @@ export function inputOutputModelSerializer(item: InputOutputModel): any { export function inputOutputModelDeserializer(item: any): InputOutputModel { return { - prop: item["prop"] + prop: item["prop"], }; } ``` @@ -237,7 +237,7 @@ export function inputOutputModelSerializer(item: InputOutputModel): any { export function inputOutputModelDeserializer(item: any): InputOutputModel { return { - prop: item["prop"] + prop: item["prop"], }; } @@ -269,21 +269,24 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _createStreamingSend( context: Client, - options: CreateStreamingOptionalParams = { requestOptions: {} } + options: CreateStreamingOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/createStreaming").post({ - ...operationOptionsToRequestParameters(options), - body: { stream: true } - }); + return context + .path("/createStreaming") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + body: { stream: stream }, + }); } export async function _createStreamingDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -295,7 +298,7 @@ export async function _createStreamingDeserialize( export async function createStreaming( context: Client, - options: CreateStreamingOptionalParams = { requestOptions: {} } + options: CreateStreamingOptionalParams = { requestOptions: {} }, ): Promise { const result = await _createStreamingSend(context, options); return _createStreamingDeserialize(result); @@ -336,7 +339,7 @@ export function fooSerializer(item: Foo): any { prop1: item["prop1"], prop2: item["prop2"], prop3: item["prop3"].toISOString(), - prop4: item["prop4"] + prop4: item["prop4"], }; } ``` @@ -349,7 +352,7 @@ export function fooDeserializer(item: any): Foo { prop1: item["prop1"], prop2: item["prop2"], prop3: new Date(item["prop3"]), - prop4: item["prop4"] + prop4: item["prop4"], }; } ``` @@ -363,22 +366,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -391,7 +401,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -414,22 +424,24 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, prop: Date, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").get({ - ...operationOptionsToRequestParameters(options), - headers: { prop: prop.toUTCString() } - }); + return context + .path("/") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { prop: prop.toUTCString(), ...options.requestOptions?.headers }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -442,7 +454,7 @@ export async function _readDeserialize( export async function read( context: Client, prop: Date, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, prop, options); return _readDeserialize(result); @@ -490,22 +502,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -518,7 +537,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -566,22 +585,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -594,7 +620,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -639,22 +665,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -667,7 +700,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -703,22 +736,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -731,7 +771,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -768,22 +808,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -796,7 +843,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -836,22 +883,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -864,7 +918,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -907,7 +961,7 @@ export function fooDeserializer(item: any): Foo { prop1: typeof item["prop1"] === "string" ? stringToUint8Array(item["prop1"], "base64") - : item["prop1"] + : item["prop1"], }; } ``` @@ -921,22 +975,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -949,7 +1010,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -993,7 +1054,7 @@ export function fooDeserializer(item: any): Foo { prop1: typeof item["prop1"] === "string" ? stringToUint8Array(item["prop1"], "base64") - : item["prop1"] + : item["prop1"], }; } ``` @@ -1007,22 +1068,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1035,7 +1103,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -1079,7 +1147,7 @@ export function fooDeserializer(item: any): Foo { prop1: typeof item["prop1"] === "string" ? stringToUint8Array(item["prop1"], "base64url") - : item["prop1"] + : item["prop1"], }; } ``` @@ -1093,22 +1161,29 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1121,7 +1196,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -1162,7 +1237,7 @@ export function catDeserializer(item: any): Cat { name: item["name"], weight: item["weight"], kind: item["kind"], - meow: item["meow"] + meow: item["meow"], }; } @@ -1175,7 +1250,7 @@ export interface Pet { export function petDeserializer(item: any): Pet { return { name: item["name"], - weight: item["weight"] + weight: item["weight"], }; } @@ -1190,7 +1265,7 @@ export function dogDeserializer(item: any): Dog { name: item["name"], weight: item["weight"], kind: item["kind"], - bark: item["bark"] + bark: item["bark"], }; } @@ -1236,7 +1311,7 @@ export function catDeserializer(item: any): Cat { name: item["name"], weight: item["weight"], kind: item["kind"], - meow: item["meow"] + meow: item["meow"], }; } @@ -1249,7 +1324,7 @@ export interface Pet { export function petDeserializer(item: any): Pet { return { name: item["name"], - weight: item["weight"] + weight: item["weight"], }; } ``` @@ -1263,20 +1338,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1288,7 +1369,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1327,7 +1408,7 @@ export function catDeserializer(item: any): Cat { weight: item["weight"], name: item["name"], kind: item["kind"], - meow: item["meow"] + meow: item["meow"], }; } @@ -1339,7 +1420,7 @@ export interface Pet extends Animal { export function petDeserializer(item: any): Pet { return { name: item["name"], - weight: item["weight"] + weight: item["weight"], }; } @@ -1350,7 +1431,7 @@ export interface Animal { export function animalDeserializer(item: any): Animal { return { - name: item["name"] + name: item["name"], }; } ``` @@ -1364,20 +1445,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1389,7 +1476,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1432,7 +1519,7 @@ export function catDeserializer(item: any): Cat { kind: item["kind"], name: item["name"], weight: item["weight"], - meow: item["meow"] + meow: item["meow"], }; } @@ -1447,7 +1534,7 @@ export function petDeserializer(item: any): Pet { return { kind: item["kind"], name: item["name"], - weight: item["weight"] + weight: item["weight"], }; } @@ -1474,20 +1561,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1499,7 +1592,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1542,7 +1635,7 @@ export function petDeserializer(item: any): Pet { return { kind: item["kind"], name: item["name"], - weight: item["weight"] + weight: item["weight"], }; } @@ -1573,7 +1666,7 @@ export function catDeserializer(item: any): Cat { kind: item["kind"], name: item["name"], weight: item["weight"], - meow: item["meow"] + meow: item["meow"], }; } @@ -1588,7 +1681,7 @@ export function dogDeserializer(item: any): Dog { kind: item["kind"], name: item["name"], weight: item["weight"], - bark: item["bark"] + bark: item["bark"], }; } ``` @@ -1602,20 +1695,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1627,7 +1726,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1676,7 +1775,7 @@ export function petDeserializer(item: any): Pet { return { kind: item["kind"], name: item["name"], - weight: item["weight"] + weight: item["weight"], }; } @@ -1707,7 +1806,7 @@ export function catDeserializer(item: any): Cat { kind: item["kind"], name: item["name"], weight: item["weight"], - meow: item["meow"] + meow: item["meow"], }; } @@ -1724,7 +1823,7 @@ export function dogDeserializer(item: any): Dog { name: item["name"], weight: item["weight"], type: item["type"], - bark: item["bark"] + bark: item["bark"], }; } @@ -1754,7 +1853,7 @@ export function goldDeserializer(item: any): Gold { bark: item["bark"], name: item["name"], weight: item["weight"], - friends: petUnionArrayDeserializer(item["friends"]) + friends: petUnionArrayDeserializer(item["friends"]), }; } @@ -1774,20 +1873,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1799,7 +1904,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1836,7 +1941,7 @@ export function fooDeserializer(item: any): Foo { return { name: item["name"], weight: item["weight"], - bar: barDeserializer(item["bar"]) + bar: barDeserializer(item["bar"]), }; } @@ -1847,7 +1952,7 @@ export interface Bar { export function barDeserializer(item: any): Bar { return { - foo: fooDeserializer(item["foo"]) + foo: fooDeserializer(item["foo"]), }; } ``` @@ -1861,20 +1966,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -1886,7 +1997,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -1950,24 +2061,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, contentType: SchemaContentTypeValues, body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - contentType: contentType, - body: body - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: contentType, + body: body, + }); } export async function _getDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -1981,7 +2094,7 @@ export async function get( context: Client, contentType: SchemaContentTypeValues, body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): Promise { const result = await _getSend(context, contentType, body, options); return _getDeserialize(result); @@ -2077,24 +2190,30 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _getSend( context: Client, testHeader: "A" | "B", body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - headers: { "test-header": testHeader }, - body: body - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + "test-header": testHeader, + ...options.requestOptions?.headers, + }, + body: body, + }); } export async function _getDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -2108,7 +2227,7 @@ export async function get( context: Client, testHeader: "A" | "B", body: string, - options: GetOptionalParams = { requestOptions: {} } + options: GetOptionalParams = { requestOptions: {} }, ): Promise { const result = await _getSend(context, testHeader, body, options); return _getDeserialize(result); @@ -2323,7 +2442,7 @@ export function vegetablesDeserializer(item: any): Vegetables { return { ...item, carrots: item["carrots"], - beans: item["beans"] + beans: item["beans"], }; } @@ -2331,13 +2450,13 @@ export function vegetablesDeserializer(item: any): Vegetables { export type _VegetablesAdditionalProperty = number | string; export function _vegetablesAdditionalPropertySerializer( - item: _VegetablesAdditionalProperty + item: _VegetablesAdditionalProperty, ): any { return item; } export function _vegetablesAdditionalPropertyDeserializer( - item: any + item: any, ): _VegetablesAdditionalProperty { return item; } diff --git a/packages/typespec-ts/test/modularUnit/scenarios/operations/cookieParam/ignoreCookieParam.md b/packages/typespec-ts/test/modularUnit/scenarios/operations/cookieParam/ignoreCookieParam.md index 51f2987604..aeab54332d 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/operations/cookieParam/ignoreCookieParam.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/operations/cookieParam/ignoreCookieParam.md @@ -28,20 +28,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _testDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -53,7 +59,7 @@ export async function _testDeserialize( export async function test( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): Promise { const result = await _testSend(context, options); return _testDeserialize(result); diff --git a/packages/typespec-ts/test/modularUnit/scenarios/operations/operations.md b/packages/typespec-ts/test/modularUnit/scenarios/operations/operations.md index 5ec44d01a5..1b9f5ff864 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/operations/operations.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/operations/operations.md @@ -16,12 +16,12 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") @@ -29,7 +29,7 @@ export function _readSend( } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["204"]; if (!expectedStatuses.includes(result.status)) { @@ -41,7 +41,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -64,12 +64,12 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") @@ -77,7 +77,7 @@ export function _readSend( } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -89,7 +89,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -138,7 +138,7 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; @@ -151,10 +151,11 @@ export function _readSend( utcDateHeader: Date, prop1: string, prop2: number, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context.path("/").post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", headers: { "required-header": requiredHeader, ...(options?.optionalHeader !== undefined @@ -169,14 +170,14 @@ export function _readSend( "csv-array-header": buildCsvCollection( csvArrayHeader.map((p: any) => { return uint8ArrayToString(p, "base64url"); - }) + }), ), "utc-date-header": utcDateHeader.toUTCString(), ...(options?.optionalDateHeader !== undefined ? { "optional-date-header": !options?.optionalDateHeader ? options?.optionalDateHeader - : options?.optionalDateHeader.toUTCString() + : options?.optionalDateHeader.toUTCString(), } : {}), ...(options?.nullableDateHeader !== undefined && @@ -184,16 +185,17 @@ export function _readSend( ? { "nullable-date-header": !options?.nullableDateHeader ? options?.nullableDateHeader - : options?.nullableDateHeader.toUTCString() + : options?.nullableDateHeader.toUTCString(), } - : {}) + : {}), + ...options.requestOptions?.headers, }, - body: { prop1: prop1, prop2: prop2 } + body: { prop1: prop1, prop2: prop2 }, }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -212,7 +214,7 @@ export async function read( utcDateHeader: Date, prop1: string, prop2: number, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend( context, @@ -223,7 +225,7 @@ export async function read( utcDateHeader, prop1, prop2, - options + options, ); return _readDeserialize(result); } @@ -251,22 +253,27 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, nullableRequiredHeader: string | null, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").get({ - ...operationOptionsToRequestParameters(options), - headers: { "nullable-required-header": nullableRequiredHeader } - }); + return context + .path("/") + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + "nullable-required-header": nullableRequiredHeader, + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -279,7 +286,7 @@ export async function _readDeserialize( export async function read( context: Client, nullableRequiredHeader: string | null, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, nullableRequiredHeader, options); return _readDeserialize(result); @@ -302,28 +309,31 @@ op read(@body bars?: Bar[]): OkResponse; ```ts operations import { TestingContext as Client } from "./index.js"; -import { barArraySerializer } from "../models/models.js"; +import { barSerializer } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context.path("/").post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", body: !options["bars"] ? options["bars"] - : barArraySerializer(options["bars"]) + : options["bars"].map((p: any) => { + return barSerializer(p); + }), }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -335,7 +345,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -358,27 +368,30 @@ op read(@body bars: Bar[]): OkResponse; ```ts operations import { TestingContext as Client } from "./index.js"; -import { Bar, barArraySerializer } from "../models/models.js"; +import { Bar, barSerializer } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, bars: Bar[], - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context.path("/").post({ ...operationOptionsToRequestParameters(options), - body: barArraySerializer(bars) + contentType: "application/json", + body: bars.map((p: any) => { + return barSerializer(p); + }), }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -391,7 +404,7 @@ export async function _readDeserialize( export async function read( context: Client, bars: Bar[], - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, bars, options); return _readDeserialize(result); @@ -419,16 +432,22 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize(result: PathUncheckedResponse): Promise< @@ -446,7 +465,7 @@ export async function _readDeserialize(result: PathUncheckedResponse): Promise< export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise< { a: Bar; @@ -473,32 +492,32 @@ op read(@body bars?: Bar[]): Bar[] | null; ```ts operations import { TestingContext as Client } from "./index.js"; -import { - Bar, - barArraySerializer, - barArrayDeserializer -} from "../models/models.js"; +import { Bar, barSerializer, barArrayDeserializer } from "../models/models.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context.path("/").post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { accept: "application/json", ...options.requestOptions?.headers }, body: !options["bars"] ? options["bars"] - : barArraySerializer(options["bars"]) + : options["bars"].map((p: any) => { + return barSerializer(p); + }), }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -510,7 +529,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -544,22 +563,25 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { - return context.path("/").post({ - ...operationOptionsToRequestParameters(options), - body: fooSerializer(body) - }); + return context + .path("/") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: "application/json", + body: fooSerializer(body), + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -572,7 +594,7 @@ export async function _readDeserialize( export async function read( context: Client, body: Foo, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, body, options); return _readDeserialize(result); @@ -606,20 +628,26 @@ import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _readSend( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .get({ ...operationOptionsToRequestParameters(options) }); + .get({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _readDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -631,7 +659,7 @@ export async function _readDeserialize( export async function read( context: Client, - options: ReadOptionalParams = { requestOptions: {} } + options: ReadOptionalParams = { requestOptions: {} }, ): Promise { const result = await _readSend(context, options); return _readDeserialize(result); @@ -669,26 +697,32 @@ import { TestingContext as Client } from "./index.js"; import { _Bar, _barDeserializer } from "../models/models.js"; import { PagedAsyncIterableIterator, - buildPagedAsyncIterator + buildPagedAsyncIterator, } from "../static-helpers/pagingHelpers.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _testDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise<_Bar> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -700,14 +734,14 @@ export async function _testDeserialize( export function test( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _testSend(context, options), _testDeserialize, ["200"], - { itemName: "lists" } + { itemName: "lists" }, ); } ``` @@ -741,24 +775,34 @@ mustEmptyDiagnostic: false ```ts operations import { TestingContext as Client } from "./index.js"; import { Bar, barDeserializer } from "../models/models.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../static-helpers/pagingHelpers.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _testDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -768,12 +812,16 @@ export async function _testDeserialize( return barDeserializer(result.body); } -export async function test( +export function test( context: Client, - options: TestOptionalParams = { requestOptions: {} } -): Promise { - const result = await _testSend(context, options); - return _testDeserialize(result); + options: TestOptionalParams = { requestOptions: {} }, +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _testSend(context, options), + _testDeserialize, + ["200"], + ); } ``` @@ -815,26 +863,32 @@ import { TestingContext as Client } from "./index.js"; import { _Child, _childDeserializer } from "../models/models.js"; import { PagedAsyncIterableIterator, - buildPagedAsyncIterator + buildPagedAsyncIterator, } from "../static-helpers/pagingHelpers.js"; import { StreamableMethod, PathUncheckedResponse, createRestError, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; export function _testSend( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context .path("/") - .post({ ...operationOptionsToRequestParameters(options) }); + .post({ + ...operationOptionsToRequestParameters(options), + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, + }); } export async function _testDeserialize( - result: PathUncheckedResponse + result: PathUncheckedResponse, ): Promise<_Child> { const expectedStatuses = ["200"]; if (!expectedStatuses.includes(result.status)) { @@ -846,14 +900,14 @@ export async function _testDeserialize( export function test( context: Client, - options: TestOptionalParams = { requestOptions: {} } + options: TestOptionalParams = { requestOptions: {} }, ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, () => _testSend(context, options), _testDeserialize, ["200"], - { itemName: "lists", nextLinkName: "nextLink" } + { itemName: "lists", nextLinkName: "nextLink" }, ); } ``` diff --git a/packages/typespec-ts/test/modularUnit/scenarios/operations/pathParam/requiredPathWithDefault.md b/packages/typespec-ts/test/modularUnit/scenarios/operations/pathParam/requiredPathWithDefault.md index 88ea7ef68f..09daa873ae 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/operations/pathParam/requiredPathWithDefault.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/operations/pathParam/requiredPathWithDefault.md @@ -1,4 +1,4 @@ -# Should generate required constant path parameter in option parameter +# Should not generate required constant path parameter Should generate required constant path parameter in option parameter. @@ -20,10 +20,7 @@ Generated operation options. import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ -export interface ReadOptionalParams extends OperationOptions { - strDefault?: "foobar"; - numberDefault?: 1; -} +export interface ReadOptionalParams extends OperationOptions {} ``` ## Provide generated operations to call rest-level methods @@ -46,11 +43,7 @@ export function _readSend( options: ReadOptionalParams = { requestOptions: {} }, ): StreamableMethod { return context - .path( - "/{strDefault}/{numberDefault}", - options[strDefault] ?? "foobar", - options[numberDefault] ?? 1, - ) + .path("/{strDefault}/{numberDefault}", "foobar", 1) .get({ ...operationOptionsToRequestParameters(options) }); } diff --git a/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/bodyOptionalCheck.md b/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/bodyOptionalCheck.md index 2d5b191fa7..e704cfd637 100644 --- a/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/bodyOptionalCheck.md +++ b/packages/typespec-ts/test/modularUnit/scenarios/samples/parameters/bodyOptionalCheck.md @@ -57,8 +57,8 @@ Raw json files. Generated operation options. ```ts models:withOptions -import { OperationOptions } from "@azure-rest/core-client"; import { BodyParameter } from "../models/models.js"; +import { OperationOptions } from "@azure-rest/core-client"; /** Optional parameters. */ export interface ReadOptionalParams extends OperationOptions { @@ -96,6 +96,11 @@ export function _readSend( .path("/{name}", name) .post({ ...operationOptionsToRequestParameters(options), + contentType: "application/json", + headers: { + accept: "application/json", + ...options.requestOptions?.headers, + }, queryParameters: { requiredQuery: requiredQuery, optionalQuery: options?.optionalQuery, diff --git a/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts b/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts deleted file mode 100644 index 186bd3a129..0000000000 --- a/packages/typespec-ts/test/modularUnit/typeHelpers.spec.ts +++ /dev/null @@ -1,762 +0,0 @@ -import { expect } from "chai"; -import { Type } from "../../src/modular/modularCodeModel.js"; -import { getType, buildType } from "../../src/modular/helpers/typeHelpers.js"; - -describe("typeHelpers", () => { - describe("getType", () => { - describe("integer type", () => { - it("should handle basic any", () => { - const type: Type = { - type: "any" - }; - const result = getType(type); - expect(result.name).to.equal("Record"); - expect(Boolean(result.nullable)).to.be.false; - }); - it("should handle basic integer", () => { - const type: Type = { - type: "integer" - }; - const result = getType(type); - expect(result.name).to.equal("number"); - expect(Boolean(result.nullable)).to.be.false; - }); - - it("should handle nullable integer", () => { - const type: Type = { - type: "integer", - tcgcType: { kind: "nullable" } as any - }; - const result = getType(type); - expect(result.name).to.equal("(number | null)"); - }); - }); - - describe("byte-array type", () => { - it("should handle basic byte-array", () => { - const type: Type = { - type: "byte-array" - }; - const result = getType(type); - expect(result.name).to.equal("Uint8Array"); - expect(Boolean(result.nullable)).to.be.false; - }); - }); - - describe("list type", () => { - it("should handle basic list", () => { - const type: Type = { - type: "list", - elementType: { - type: "integer" - } - }; - const result = getType(type); - expect(result.name).to.equal("number[]"); - expect(Boolean(result.nullable)).to.be.false; - }); - }); - - describe("model type", () => { - it("should handle model with name", () => { - const type: Type = { - type: "model", - name: "SomeModel" - }; - const result = getType(type); - expect(result.name).to.equal("SomeModel"); - expect(result.originModule).to.equal("models.js"); - expect(Boolean(result.nullable)).to.be.false; - }); - - describe("anonymous model", () => { - it("should handle empty anonymous model", () => { - const type: Type = { - type: "model", - name: "" - }; - const result = getType(type); - expect(result.name).to.equal("{}"); - }); - - it("should handle anonymous model with properties", () => { - const type: Type = { - type: "model", - name: "", - - properties: [ - { - clientName: `foo/bar`, - type: { - type: "string" - } - }, - { - clientName: "bar", - type: { - type: "integer" - } - } - ] as any - }; - const result = getType(type); - expect(result.name).to.equal(`{"foo/bar": string;"bar": number;}`); - }); - }); - }); - - describe("datetime types", () => { - it("should handle basic datetime", () => { - const type: Type = { - type: "datetime" - }; - const result = getType(type); - expect(result.name).to.equal("Date"); - expect(Boolean(result.nullable)).to.be.false; - }); - - it("should handle nullable datetime", () => { - const type: Type = { - type: "datetime", - tcgcType: { kind: "nullable" } as any - }; - const result = getType(type); - expect(result.name).to.equal("(Date | null)"); - }); - - it("should handle string type with default format", () => { - const type: Type = { - type: "string" - }; - const result = getType(type); - expect(result.name).to.equal("string"); - expect(Boolean(result.nullable)).to.be.false; - }); - - it("should handle duration type with default format", () => { - const type: Type = { - type: "duration" - }; - const result = getType(type); - expect(result.name).to.equal("string"); - expect(Boolean(result.nullable)).to.be.false; - }); - - it("should handle duration type formatted as seconds", () => { - const type: Type = { - type: "duration" - }; - const result = getType(type, "seconds"); - expect(result.name).to.equal("number"); - expect(Boolean(result.nullable)).to.be.false; - }); - - // Let's consider an edge case where the format doesn't match any predefined formats. - it("should handle unknown format for string type", () => { - const type: Type = { - type: "string" - }; - const result = getType(type, "unknownFormat"); - expect(result.name).to.equal("string"); // It defaults to string if the format is not recognized. - expect(Boolean(result.nullable)).to.be.false; - }); - }); - - describe("list within a list type", () => { - it("should handle a nested list", () => { - const type: Type = { - type: "list", - - elementType: { - type: "list", - elementType: { - type: "integer" - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("number[][]"); - }); - - it("should handle a nested list of nullable elements", () => { - const type: Type = { - type: "list", - - elementType: { - type: "list", - elementType: { - type: "integer", - tcgcType: { kind: "nullable" } as any - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("(number | null)[][]"); - }); - - it("should handle a nested list of nullable list of elements", () => { - const type: Type = { - type: "list", - - elementType: { - type: "list", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "integer" - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("(number[] | null)[]"); - }); - - it("should handle a nested nullable list of nullable list of non-nullable elements", () => { - const type: Type = { - type: "list", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "list", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "integer" - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("((number[] | null)[] | null)"); - }); - - it("should handle a nullable list of floats", () => { - const type: Type = { - type: "list", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "float" - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("(number[] | null)"); - }); - - it("should handle a nested nullable list of nullable list of nullable elements", () => { - const type: Type = { - type: "list", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "list", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "integer", - tcgcType: { kind: "nullable" } as any - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("(((number | null)[] | null)[] | null)"); - }); - }); - - describe("dict with list values type", () => { - it("should handle dictionary type with list values", () => { - const type: Type = { - type: "dict", - elementType: { - type: "list", - elementType: { - type: "integer" - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("Record"); - }); - - it("should handle dictionary type with list nullable values", () => { - const type: Type = { - type: "dict", - elementType: { - type: "list", - elementType: { - type: "integer", - tcgcType: { kind: "nullable" } as any - } - } - }; - const result = buildType("foo", type); - expect(result.type).to.equal("Record"); - }); - }); - - describe("list of dictionaries type", () => { - it("should handle a list of dictionaries", () => { - const type: Type = { - type: "list", - - elementType: { - type: "dict", - elementType: { - type: "string" - } - } - }; - const result = getType(type); - expect(result.name).to.equal("Record[]"); - }); - }); - - describe("string type", () => { - it("should handle basic string", () => { - const type: Type = { - type: "string" - }; - const result = getType(type); - expect(result.name).to.equal("string"); - expect(Boolean(result.nullable)).to.be.false; - }); - - it("should handle nullable string", () => { - const type: Type = { - type: "string", - tcgcType: { kind: "nullable" } as any - }; - const result = getType(type); - expect(result.name).to.equal("(string | null)"); - }); - }); - - describe("combined type", () => { - it("should handle combined types", () => { - const type: Type = { - type: "combined", - types: [ - { - type: "string" - }, - { - type: "integer" - } - ] - }; - const result = getType(type); - expect(result.name).to.equal("(string | number)"); - expect(Boolean(result.nullable)).to.be.false; - }); - }); - - describe("dict type", () => { - it("should handle dictionary type with integer values", () => { - const type: Type = { - type: "dict", - elementType: { - type: "integer" - } - }; - const result = getType(type); - expect(result.name).to.equal("Record"); - }); - - it("should handle dictionary type with string values", () => { - const type: Type = { - type: "dict", - elementType: { - type: "string" - } - }; - const result = getType(type); - expect(result.name).to.equal("Record"); - }); - }); - - it("should handle Key type", () => { - const type: Type = { type: "Key" }; - const result = getType(type); - expect(result.name).to.equal("KeyCredential"); - }); - - it("should handle OAuth2 type", () => { - const type: Type = { type: "OAuth2" }; - const result = getType(type); - expect(result.name).to.equal("TokenCredential"); - }); - - it("should handle nullable boolean type", () => { - const type: Type = { - type: "boolean", - tcgcType: { kind: "nullable" } as any - }; - const result = getType(type); - expect(result.name).to.equal("(boolean | null)"); - }); - - it("should handle constant type", () => { - const type: Type = { - type: "constant", - value: "TEST", - valueType: { type: "string" } - }; - const result = getType(type); - expect(result.name).to.equal('"TEST"'); - }); - - it("should handle nullable constant type", () => { - const type: Type = { - type: "constant", - value: "TEST", - valueType: { type: "string" }, - tcgcType: { kind: "nullable" } as any - }; - const result = getType(type); - expect(result.name).to.equal('("TEST" | null)'); - }); - - it("should handle constant type", () => { - const type: Type = { - type: "constant", - value: "true", - valueType: { type: "boolean" } - }; - const result = getType(type); - expect(result.name).to.equal("true"); - }); - - it("should handle datetime type", () => { - const type: Type = { - type: "datetime", - tcgcType: { kind: "nullable" } as any - }; - const result = getType(type); - expect(result.name).to.equal("(Date | null)"); - }); - - it("should handle named enum type", () => { - const type: Type = { - type: "enum", - name: "TestEnum", - valueType: { type: "string" }, - values: [ - { name: "A", value: "A_VAL", description: "Value A" }, - { name: "B", value: "B_VAL", description: "Value B" } - ] - }; - const result = getType(type); - expect(result.name).to.equal("TestEnum"); - expect(result.originModule).to.equal("models.js"); - }); - - it("should handle enum member type as string literal", () => { - const type: Type = { - type: "constant", - name: "A_VAL", - valueType: { type: "string" }, - value: "A_VAL" - }; - const result = getType(type); - expect(result.name).to.equal('"A_VAL"'); - }); - - it("should handle enum member type as number literal", () => { - const type: Type = { - type: "constant", - name: "1", - valueType: { type: "integer" }, - value: "1" - }; - const result = getType(type); - expect(result.name).to.equal("1"); - }); - - it("should handle enum member type as number literal", () => { - const type: Type = { - type: "constant", - name: "true", - valueType: { type: "boolean" }, - value: "true" - }; - const result = getType(type); - expect(result.name).to.equal("true"); - }); - - it("should handle float type", () => { - const type: Type = { type: "float" }; - const result = getType(type); - expect(result.name).to.equal("number"); - }); - - it("should return `any` for unknown types", () => { - const type: Type = { type: "unknown" as any }; // Forcing an unknown type. - const result = getType(type); - expect(result.name).to.equal("any"); - }); - }); - - describe("buildType", () => { - describe("integer type", () => { - it("should build type for integer", () => { - const type: Type = { - type: "integer" - }; - const result = buildType("SomeClient", type); - expect(result.type).to.equal("number"); - }); - - it("should build type for nullable integer", () => { - const type: Type = { - type: "integer", - tcgcType: { kind: "nullable" } as any - }; - const result = buildType("SomeClient", type); - expect(result.type).to.equal("(number | null)"); - }); - }); - - describe("byte-array type", () => { - it("should build type for byte-array", () => { - const type: Type = { - type: "byte-array" - }; - const result = buildType("ClientByteArray", type); - expect(result.type).to.equal("Uint8Array"); - }); - - it("should build type for nullable byte-array", () => { - const type: Type = { - type: "byte-array", - tcgcType: { kind: "nullable" } as any - }; - const result = buildType("ClientByteArray", type); - expect(result.type).to.equal("(Uint8Array | null)"); - }); - }); - - describe("list type", () => { - it("should build type for list", () => { - const type: Type = { - type: "list", - elementType: { - type: "integer" - } - }; - const result = buildType("ClientList", type); - expect(result.type).to.equal("number[]"); - }); - - it("should build type for nullable list", () => { - const type: Type = { - type: "list", - elementType: { - type: "integer" - }, - tcgcType: { kind: "nullable" } as any - }; - const result = buildType("ClientList", type); - expect(result.type).to.equal("(number[] | null)"); - }); - - it("should build type for non-nullable list with nullable element", () => { - const type: Type = { - type: "list", - elementType: { - type: "integer", - tcgcType: { kind: "nullable" } as any - } - }; - const result = buildType("ClientList", type); - expect(result.type).to.equal("(number | null)[]"); - }); - - it("should build type for nullable list and nullable element", () => { - const type: Type = { - type: "list", - elementType: { - type: "integer", - tcgcType: { kind: "nullable" } as any - }, - tcgcType: { kind: "nullable" } as any - }; - const result = buildType("ClientList", type); - expect(result.type).to.equal("((number | null)[] | null)"); - }); - }); - - describe("model type", () => { - it("should build type for model with name", () => { - const type: Type = { - type: "model", - name: "SomeModel" - }; - const result = buildType("ClientModel", type); - expect(result.type).to.equal("SomeModel"); - }); - - it("should build type for nullable model with name", () => { - const type: Type = { - type: "model", - name: "SomeModel", - tcgcType: { kind: "nullable" } as any - }; - const result = buildType("ClientModel", type); - expect(result.type).to.equal("(SomeModel | null)"); - }); - }); - - describe("string type", () => { - it("should build type for string", () => { - const type: Type = { - type: "string" - }; - const result = buildType("ClientString", type); - expect(result.type).to.equal("string"); - }); - - it("should build type for nullable string", () => { - const type: Type = { - type: "string", - tcgcType: { kind: "nullable" } as any - }; - const result = buildType("ClientString", type); - expect(result.type).to.equal("(string | null)"); - }); - }); - - describe("combined type", () => { - it("should build type for combined types", () => { - const type: Type = { - type: "combined", - types: [ - { - type: "string" - }, - { - type: "integer" - } - ] - }; - const result = buildType("ClientCombined", type); - expect(result.name).to.equal("ClientCombined"); - expect(result.type).to.equal("(string | number)"); - }); - - it("should build type for list of combined types", () => { - const type: Type = { - type: "list", - elementType: { - type: "combined", - types: [ - { - type: "constant", - value: `1`, - valueType: { type: "integer" } - }, - { - type: "constant", - value: `false`, - valueType: { type: "boolean" } - }, - { - type: "constant", - value: "t", - valueType: { type: "string" } - } - ] - } - }; - const result = buildType("ClientCombined", type); - expect(result.name).to.equal("ClientCombined"); - expect(result.type).to.equal('(1 | false | "t")[]'); - }); - - it("should build type for combined types, string literals", () => { - const type: Type = { - type: "combined", - types: [ - { - type: "constant", - value: `"str1"` - }, - { - type: "constant", - value: `"str2"` - } - ] - }; - const result = buildType("ClientCombined", type); - expect(result.name).to.equal("ClientCombined"); - expect(result.type).to.equal(`("str1" | "str2")`); - }); - - it("should build type for combined types, one nullable", () => { - const type: Type = { - type: "combined", - types: [ - { - type: "string", - tcgcType: { kind: "nullable" } as any - }, - { - type: "integer" - } - ] - }; - const result = buildType("ClientCombined", type); - expect(result.name).to.equal("ClientCombined"); - expect(result.type).to.equal("((string | null) | number)"); - }); - - it("should build type for combined types, both nullable", () => { - const type: Type = { - type: "combined", - types: [ - { - type: "string", - tcgcType: { kind: "nullable" } as any - }, - { - type: "integer", - tcgcType: { kind: "nullable" } as any - } - ] - }; - const result = buildType("ClientCombined", type); - expect(result.name).to.equal("ClientCombined"); - expect(result.type).to.equal("((string | null) | (number | null))"); - }); - }); - - describe("dict type", () => { - it("should build type for dictionary type with integer values", () => { - const type: Type = { - type: "dict", - elementType: { - type: "integer" - } - }; - const result = buildType("ClientDictInt", type); - expect(result.type).to.equal("Record"); - }); - - it("should build type for nullable dictionary type", () => { - const type: Type = { - type: "dict", - tcgcType: { kind: "nullable" } as any, - elementType: { - type: "integer" - } - }; - const result = buildType("ClientDictInt", type); - expect(result.type).to.equal("(Record | null)"); - }); - - it("should build type for dictionary type with nullable integer values", () => { - const type: Type = { - type: "dict", - elementType: { - type: "integer", - tcgcType: { kind: "nullable" } as any - } - }; - const result = buildType("ClientDictInt", type); - expect(result.type).to.equal("Record"); - }); - }); - }); -}); diff --git a/packages/typespec-ts/test/nonBrandedIntegration/modular/generated/models/usage/src/index.d.ts b/packages/typespec-ts/test/nonBrandedIntegration/modular/generated/models/usage/src/index.d.ts index de2b445ad4..dd6ad6fec4 100644 --- a/packages/typespec-ts/test/nonBrandedIntegration/modular/generated/models/usage/src/index.d.ts +++ b/packages/typespec-ts/test/nonBrandedIntegration/modular/generated/models/usage/src/index.d.ts @@ -27,9 +27,9 @@ export declare class UsageClient { private _client; readonly pipeline: Pipeline; constructor(options?: UsageClientOptionalParams); - input(inputParameter: InputRecord, options?: InputOptionalParams): Promise; - output(options?: OutputOptionalParams): Promise; inputAndOutput(body: InputOutputRecord, options?: InputAndOutputOptionalParams): Promise; + output(options?: OutputOptionalParams): Promise; + input(inputParameter: InputRecord, options?: InputOptionalParams): Promise; } export declare interface UsageClientOptionalParams extends ClientOptions { diff --git a/packages/typespec-ts/test/util/emitUtil.ts b/packages/typespec-ts/test/util/emitUtil.ts index 467c2a5c66..eb8b234060 100644 --- a/packages/typespec-ts/test/util/emitUtil.ts +++ b/packages/typespec-ts/test/util/emitUtil.ts @@ -1,6 +1,5 @@ import { OperationParameter, - RLCModel, Schema, buildClient, buildClientDefinitions, @@ -19,14 +18,13 @@ import { } from "../../src/modular/emitModelsOptions.js"; import { compileTypeSpecFor, createDpgContextTestHelper, ExampleJson, rlcEmitterFor } from "./testUtil.js"; import { - transformRLCModel, transformUrlInfo } from "../../src/transform/transform.js"; import { buildClassicalClient } from "../../src/modular/buildClassicalClient.js"; import { buildClientContext } from "../../src/modular/buildClientContext.js"; import { buildOperationFiles } from "../../src/modular/buildOperations.js"; -import { emitCodeModel } from "../../src/modular/buildCodeModel.js"; +import { transformModularEmitterOptions } from "../../src/modular/buildModularOptions.js"; import { expectDiagnosticEmpty } from "@typespec/compiler/testing"; import { getCredentialInfo } from "../../src/transform/transfromRLCOptions.js"; import { getRLCClients } from "../../src/utils/clientUtils.js"; @@ -415,50 +413,39 @@ export async function emitModularModelsFromTypeSpec( } ); const dpgContext = await createDpgContextTestHelper(context.program, false, options); - const serviceNameToRlcModelsMap: Map = new Map< - string, - RLCModel - >(); const project = useContext("outputProject"); const binder = useBinder(); - const clients = getRLCClients(dpgContext); let modelFile = undefined; - if (clients && clients[0]) { - dpgContext.rlcOptions!.isModularLibrary = true; - dpgContext.rlcOptions!.compatibilityMode = compatibilityMode; - dpgContext.rlcOptions!.experimentalExtensibleEnums = - experimentalExtensibleEnums; - const rlcModels = await transformRLCModel(clients[0], dpgContext); - serviceNameToRlcModelsMap.set(clients[0].service.name, rlcModels); - const modularCodeModel = emitCodeModel( - dpgContext, - serviceNameToRlcModelsMap, - "", - project, - { - casing: "camel" - } - ); - if ( - modularCodeModel && - modularCodeModel.clients && - modularCodeModel.clients.length > 0 && - modularCodeModel.clients[0] - ) { - if (needOptions) { - emitTypes(dpgContext, { sourceRoot: "" }); - modelFile = buildApiOptions( - dpgContext, - modularCodeModel.clients[0], - modularCodeModel - ); - binder.resolveAllReferences("/"); - removeUnusedImports(modelFile); - modelFile.fixUnusedIdentifiers(); - } else { - modelFile = emitTypes(dpgContext, { sourceRoot: "" }); - binder.resolveAllReferences("/"); - } + dpgContext.rlcOptions!.isModularLibrary = true; + dpgContext.rlcOptions!.compatibilityMode = compatibilityMode; + dpgContext.rlcOptions!.experimentalExtensibleEnums = + experimentalExtensibleEnums; + const modularEmitterOptions = transformModularEmitterOptions( + dpgContext, + "", + project, + { + casing: "camel" + } + ); + if ( + dpgContext.sdkPackage.clients && + dpgContext.sdkPackage.clients.length > 0 && + dpgContext.sdkPackage.clients[0] + ) { + if (needOptions) { + emitTypes(dpgContext, { sourceRoot: "" }); + modelFile = buildApiOptions( + dpgContext, + dpgContext.sdkPackage.clients[0], + modularEmitterOptions + ); + binder.resolveAllReferences("/modularPackageFolder/src"); + removeUnusedImports(modelFile); + modelFile.fixUnusedIdentifiers(); + } else { + modelFile = emitTypes(dpgContext, { sourceRoot: "" }); + binder.resolveAllReferences("/modularPackageFolder/src"); } } if (mustEmptyDiagnostic && dpgContext.program.diagnostics.length > 0) { @@ -510,49 +497,38 @@ export async function emitModularOperationsFromTypeSpec( } ); const dpgContext = await createDpgContextTestHelper(context.program); - const serviceNameToRlcModelsMap: Map = new Map< - string, - RLCModel - >(); const project = useContext("outputProject"); const binder = useBinder(); - const clients = getRLCClients(dpgContext); - if (clients && clients[0]) { - dpgContext.rlcOptions!.isModularLibrary = true; - dpgContext.rlcOptions!.experimentalExtensibleEnums = experimentalExtensibleEnums; - const rlcModels = await transformRLCModel(clients[0], dpgContext); - serviceNameToRlcModelsMap.set(clients[0].service.name, rlcModels); - const modularCodeModel = emitCodeModel( + dpgContext.rlcOptions!.isModularLibrary = true; + dpgContext.rlcOptions!.experimentalExtensibleEnums = experimentalExtensibleEnums; + const modularEmitterOptions = transformModularEmitterOptions( + dpgContext, + "", + project, + { + casing: "camel" + } + ); + if ( + dpgContext.sdkPackage.clients && + dpgContext.sdkPackage.clients.length > 0 && + dpgContext.sdkPackage.clients[0] + ) { + emitTypes(dpgContext, { sourceRoot: "" }); + const res = buildOperationFiles( dpgContext, - serviceNameToRlcModelsMap, - "", - project, - { - casing: "camel" - } + dpgContext.sdkPackage.clients[0], + modularEmitterOptions ); - if ( - modularCodeModel && - modularCodeModel.clients && - modularCodeModel.clients.length > 0 && - modularCodeModel.clients[0] - ) { - emitTypes(dpgContext, { sourceRoot: "" }); - const res = buildOperationFiles( - modularCodeModel.clients[0], - dpgContext, - modularCodeModel - ); - if (mustEmptyDiagnostic && dpgContext.program.diagnostics.length > 0) { - throw dpgContext.program.diagnostics; - } - binder.resolveAllReferences("/"); - for (const file of res) { - removeUnusedImports(file); - file.fixUnusedIdentifiers(); - } - return res; + if (mustEmptyDiagnostic && dpgContext.program.diagnostics.length > 0) { + throw dpgContext.program.diagnostics; } + binder.resolveAllReferences("/"); + for (const file of res) { + removeUnusedImports(file); + file.fixUnusedIdentifiers(); + } + return res; } return undefined; } @@ -578,43 +554,32 @@ export async function emitModularClientContextFromTypeSpec( } ); const dpgContext = await createDpgContextTestHelper(context.program); - const serviceNameToRlcModelsMap: Map = new Map< - string, - RLCModel - >(); const project = useContext("outputProject"); const binder = useBinder(); - const clients = getRLCClients(dpgContext); - if (clients && clients[0]) { - dpgContext.rlcOptions!.isModularLibrary = true; - const rlcModels = await transformRLCModel(clients[0], dpgContext); - serviceNameToRlcModelsMap.set(clients[0].service.name, rlcModels); - const modularCodeModel = emitCodeModel( + dpgContext.rlcOptions!.isModularLibrary = true; + const modularEmitterOptions = transformModularEmitterOptions( + dpgContext, + "", + project, + { + casing: "camel" + } + ); + if ( + dpgContext.sdkPackage.clients && + dpgContext.sdkPackage.clients.length > 0 && + dpgContext.sdkPackage.clients[0] + ) { + emitTypes(dpgContext, { sourceRoot: "" }); + const res = buildClientContext( dpgContext, - serviceNameToRlcModelsMap, - "", - project, - { - casing: "camel" - } + dpgContext.sdkPackage.clients[0], + modularEmitterOptions ); - if ( - modularCodeModel && - modularCodeModel.clients && - modularCodeModel.clients.length > 0 && - modularCodeModel.clients[0] - ) { - emitTypes(dpgContext, { sourceRoot: "" }); - const res = buildClientContext( - modularCodeModel.clients[0], - dpgContext, - modularCodeModel - ); - binder.resolveAllReferences("/"); - removeUnusedImports(res); - res.fixUnusedIdentifiers(); - return res; - } + binder.resolveAllReferences("modularPackageFolder/src"); + removeUnusedImports(res); + res.fixUnusedIdentifiers(); + return res; } expectDiagnosticEmpty(dpgContext.program.diagnostics); return undefined; @@ -641,40 +606,29 @@ export async function emitModularClientFromTypeSpec( } ); const dpgContext = await createDpgContextTestHelper(context.program); - const serviceNameToRlcModelsMap: Map = new Map< - string, - RLCModel - >(); const project = useContext("outputProject"); const binder = useBinder(); - const clients = getRLCClients(dpgContext); - if (clients && clients[0]) { - dpgContext.rlcOptions!.isModularLibrary = true; - const rlcModels = await transformRLCModel(clients[0], dpgContext); - serviceNameToRlcModelsMap.set(clients[0].service.name, rlcModels); - const modularCodeModel = emitCodeModel( + dpgContext.rlcOptions!.isModularLibrary = true; + const modularEmitterOptions = transformModularEmitterOptions( + dpgContext, + "", + project, + { + casing: "camel" + } + ); + if ( + dpgContext.sdkPackage.clients && + dpgContext.sdkPackage.clients.length > 0 && + dpgContext.sdkPackage.clients[0] + ) { + const res = buildClassicalClient( dpgContext, - serviceNameToRlcModelsMap, - "", - project, - { - casing: "camel" - } + dpgContext.sdkPackage.clients[0], + modularEmitterOptions ); - if ( - modularCodeModel && - modularCodeModel.clients && - modularCodeModel.clients.length > 0 && - modularCodeModel.clients[0] - ) { - const res = buildClassicalClient( - modularCodeModel.clients[0], - dpgContext, - modularCodeModel - ); - binder.resolveAllReferences("/modularPackageFolder/src"); - return res; - } + binder.resolveAllReferences("/modularPackageFolder/src"); + return res; } expectDiagnosticEmpty(dpgContext.program.diagnostics); return undefined; diff --git a/packages/typespec-ts/test/util/testUtil.ts b/packages/typespec-ts/test/util/testUtil.ts index 671bde3f35..ebb4e02888 100644 --- a/packages/typespec-ts/test/util/testUtil.ts +++ b/packages/typespec-ts/test/util/testUtil.ts @@ -188,7 +188,6 @@ export async function createDpgContextTestHelper( ): Promise { const outputProject = new Project({ useInMemoryFileSystem: true }); provideContext("rlcMetaTree", new Map()); - provideContext("modularMetaTree", new Map()); provideContext("symbolMap", new Map()); provideContext("outputProject", outputProject);