From df26e3916c037f001e410fdb0bed9f362aebda36 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 16:42:53 +0800 Subject: [PATCH 01/60] Re-generate to support the paging feature --- packages/typespec-ts/src/index.ts | 3 + .../src/modular/buildPagingUtils.ts | 43 ++++ .../typespec-ts/src/modular/buildRootIndex.ts | 24 ++ .../src/modular/helpers/operationHelpers.ts | 30 ++- .../src/modular/static/pagingUtil.ts | 216 +++++++++++++++++ .../test/modularIntegration/azureCore.spec.ts | 98 +++++++- .../generated/azure/core/src/BasicClient.ts | 11 +- .../azure/core/src/api/operations.ts | 36 ++- .../generated/azure/core/src/index.ts | 4 + .../azure/core/src/util/pagingUtil.ts | 219 ++++++++++++++++++ 10 files changed, 657 insertions(+), 27 deletions(-) create mode 100644 packages/typespec-ts/src/modular/buildPagingUtils.ts create mode 100644 packages/typespec-ts/src/modular/static/pagingUtil.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 184da08647..453e240bbd 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -52,6 +52,7 @@ import { GenerationDirDetail, SdkContext } from "./utils/interfaces.js"; import { transformRLCOptions } from "./transform/transfromRLCOptions.js"; import { ModularCodeModel } from "./modular/modularCodeModel.js"; import { getClientName } from "@azure-tools/rlc-common"; +import { buildPagingUtils } from "./modular/buildPagingUtils.js"; export * from "./lib.js"; @@ -162,6 +163,8 @@ export async function $onEmit(context: EmitContext) { overwrite: true } ); + // Build the shared paging utils + await buildPagingUtils(modularCodeModel, rlcCodeModels); for (const subClient of modularCodeModel.clients) { buildModels(modularCodeModel, subClient); buildModelsOptions(modularCodeModel, subClient); diff --git a/packages/typespec-ts/src/modular/buildPagingUtils.ts b/packages/typespec-ts/src/modular/buildPagingUtils.ts new file mode 100644 index 0000000000..53a8eb6d22 --- /dev/null +++ b/packages/typespec-ts/src/modular/buildPagingUtils.ts @@ -0,0 +1,43 @@ +import { RLCModel } from "@azure-tools/rlc-common"; +import { dirname, join as joinPath } from "path"; +import { promises } from "fs"; +import { ModularCodeModel } from "./modularCodeModel.js"; +import { fileURLToPath } from "url"; + +export async function buildPagingUtils( + modularCodeModel: ModularCodeModel, + rlcCodeModels: RLCModel[] +) { + const hasPaging = rlcCodeModels.some( + (codeModel) => codeModel.helperDetails?.hasPaging + ); + if (!hasPaging) { + return; + } + const project = modularCodeModel.project; + const helperFile = "pagingUtil.ts"; + const baseTargetPath = modularCodeModel.modularOptions.sourceRoot; + const __filename = fileURLToPath(import.meta.url); + const __dirname = dirname(__filename); + const srcDir = joinPath( + __dirname, + "..", + "..", + "..", + "src", + "modular", + "static" + ); + const fileContent = await promises.readFile( + joinPath(srcDir, helperFile), + "utf-8" + ); + // TODO: Here to replace the itemNames and pageLink info + project.createSourceFile( + joinPath(baseTargetPath, "util", helperFile), + fileContent, + { + overwrite: true + } + ); +} diff --git a/packages/typespec-ts/src/modular/buildRootIndex.ts b/packages/typespec-ts/src/modular/buildRootIndex.ts index b412403eb3..cc45480183 100644 --- a/packages/typespec-ts/src/modular/buildRootIndex.ts +++ b/packages/typespec-ts/src/modular/buildRootIndex.ts @@ -21,6 +21,7 @@ export function buildRootIndex( exportClassicalClient(client, rootIndexFile, subfolder); exportModels(rootIndexFile, project, srcPath, clientName, subfolder, true); + exportPagingUtil(codeModel, rootIndexFile, client); } function exportClassicalClient( @@ -71,6 +72,29 @@ function exportModels( }); } +function exportPagingUtil( + codeModel: ModularCodeModel, + indexFile: SourceFile, + client: Client +) { + // Only import the paging helper once + if (client !== codeModel.clients[0]) { + return; + } + const hasPaging = codeModel.clients.some((client) => + client.operationGroups.some((group) => + group.operations.some((op) => op.discriminator === "paging") + ) + ); + if (!hasPaging) { + return; + } + indexFile.addExportDeclaration({ + moduleSpecifier: `./util/pagingUtil.js`, + namedExports: ["getContinuationToken", "setContinuationToken"] // Only export the getContinuationToken and setContinuationToken to public + }); +} + export function buildSubClientIndexFile( codeModel: ModularCodeModel, client: Client diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index e67b3d548e..aa9d8fcc83 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -241,12 +241,17 @@ export function getOperationFunction( // Extract required parameters const parameters: OptionalKind[] = getOperationSignatureParameters(operation, clientType); + const isPaging = operation.discriminator === "paging"; // TODO: Support operation overloads const response = operation.responses[0]!; const returnType = response?.type?.type ? buildType(response.type.name, response.type) : { name: "", type: "void" }; + // TODO: calculate the page return + const operationReturnType = isPaging + ? `PagedAsyncIterableIterator` + : `Promise<${returnType.type}>`; const { name, fixme = [] } = getOperationName(operation); const functionStatement: OptionalKind = { @@ -254,20 +259,29 @@ export function getOperationFunction( ...getDocsFromDescription(operation.description), ...getFixmeForMultilineDocs(fixme) ], - isAsync: true, + isAsync: !isPaging, isExported: true, name: normalizeName(operation.name, NameType.Operation, true), parameters, - returnType: `Promise<${returnType.type}>` + returnType: operationReturnType }; const statements: string[] = []; - statements.push( - `const result = await _${name}Send(${parameters - .map((p) => p.name) - .join(", ")});` - ); - statements.push(`return _${name}Deserialize(result);`); + if (isPaging) { + statements.push( + `return buildPagedAsyncIterator(context, _${name}Send, _${name}Deserialize, [${parameters + .map((p) => p.name) + .join(", ")}]) ;` + ); + } else { + statements.push( + `const result = await _${name}Send(${parameters + .map((p) => p.name) + .join(", ")});` + ); + statements.push(`return _${name}Deserialize(result);`); + } + return { ...functionStatement, statements diff --git a/packages/typespec-ts/src/modular/static/pagingUtil.ts b/packages/typespec-ts/src/modular/static/pagingUtil.ts new file mode 100644 index 0000000000..4e1f1304c9 --- /dev/null +++ b/packages/typespec-ts/src/modular/static/pagingUtil.ts @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse +} from "@azure-rest/core-client"; + +export interface PageInfo { + continuationToken?: string; +} + +const pageMap = new WeakMap(); + +/** + * Given the last `.value` produced by the `byPage` iterator, + * returns a continuation token that can be used to begin paging from + * that point later. + * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. + * @returns The continuation token that can be passed into byPage() during future calls. + */ +export function getContinuationToken(page: unknown): string | undefined { + if (typeof page !== "object" || page === null) { + return undefined; + } + return pageMap.get(page)?.continuationToken; +} + +export function setContinuationToken( + page: unknown, + continuationToken: string | undefined +): void { + if (typeof page !== "object" || page === null || !continuationToken) { + return; + } + const pageInfo = pageMap.get(page) ?? {}; + pageInfo.continuationToken = continuationToken; + pageMap.set(page, pageInfo); +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: ( + resp: TResponse | PathUncheckedResponse + ) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string, maxPageSize?: number) => { + if (maxPageSize) { + throw new Error("maxPageSize is not supported by this operation."); + } + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + return { + page: values, + nextPageLink: nextLink + }; + } + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226" + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} diff --git a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts index 631e5f0fe7..7d68403cdb 100644 --- a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts @@ -1,4 +1,4 @@ -import { BasicClient } from "./generated/azure/core/src/index.js"; +import { BasicClient, User } from "./generated/azure/core/src/index.js"; import { assert } from "chai"; describe("BasicClient Classical Client", () => { @@ -10,7 +10,99 @@ describe("BasicClient Classical Client", () => { }); }); - it("should create the client", async () => { - assert.isNotNull(client); + describe("list", () => { + describe("next", () => { + it("should list all users", async () => { + const iter = client.list({ + top: 5, + skip: 10, + orderby: ["id"], + filter: "id lt 10", + select: ["id", "orders", "etag"], + expand: ["orders"], + requestOptions: { skipUrlEncoding: true } + }); + const items = []; + for await (const user of iter) { + items.push(user); + } + assert.strictEqual(items.length, 2); + assert.strictEqual(items[0]?.name, "Madge"); + assert.strictEqual( + items[1]?.etag, + "11bdc430-65e8-45ad-81d9-8ffa60d55b5a" + ); + }); + }); + + describe("byPage", () => { + it("should get all users by page without any settings", async () => { + const iter = client.list({ + top: 5, + skip: 10, + orderby: ["id"], + filter: "id lt 10", + select: ["id", "orders", "etag"], + expand: ["orders"], + requestOptions: { skipUrlEncoding: true } + }); + const pagedItems = iter.byPage(); + const items: User[] = []; + for await (const page of pagedItems) { + items.push(...page); + } + assert.strictEqual(items.length, 2); + assert.strictEqual(items[0]?.name, "Madge"); + assert.strictEqual( + items[1]?.etag, + "11bdc430-65e8-45ad-81d9-8ffa60d55b5a" + ); + }); + + it("maxPageSize is not allowed and should throw exceptions", async () => { + const iter = client.list({ + top: 5, + skip: 10, + orderby: ["id"], + filter: "id lt 10", + select: ["id", "orders", "etag"], + expand: ["orders"], + requestOptions: { skipUrlEncoding: true } + }); + const pagedItems = iter.byPage({ maxPageSize: 10 }); + try { + const items: User[] = []; + for await (const user of pagedItems) { + items.push(...user); + } + assert.fail( + "`maxPageSize` is not allowed to customize and should throw exceptions" + ); + } catch (err: any) { + assert.strictEqual( + err.message, + "maxPageSize is not supported by this operation." + ); + } + }); + + it("should get users by continuationToken", async () => { + const iter = client.list(); + const pagedItems = iter.byPage({ + continuationToken: + "/azure/core/basic/users?top=5&skip=10&orderby=id&filter=id%20lt%2010&select=id&select=orders&select=etag&expand=orders&api-version=2022-12-01-preview" + }); + const items: User[] = []; + for await (const user of pagedItems) { + items.push(...user); + } + assert.strictEqual(items.length, 2); + assert.strictEqual(items[0]?.name, "Madge"); + assert.strictEqual( + items[1]?.etag, + "11bdc430-65e8-45ad-81d9-8ffa60d55b5a" + ); + }); + }); }); }); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts index b687b2ed80..29e2825514 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { User, UserListResults, PagedUser } from "./models/models.js"; +import { User } from "./models/models.js"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, @@ -25,6 +25,7 @@ import { deleteOperation, exportOperation, } from "./api/index.js"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; export { BasicClientOptions } from "./api/BasicContext.js"; @@ -60,21 +61,23 @@ export class BasicClient { } /** Lists all Users */ - list(options: ListOptions = { requestOptions: {} }): Promise { + list( + options: ListOptions = { requestOptions: {} } + ): PagedAsyncIterableIterator { return list(this._client, options); } /** List with Azure.Core.Page<>. */ listWithPage( options: ListWithPageOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listWithPage(this._client, options); } /** List with custom page model. */ listWithCustomPageModel( options: ListWithCustomPageModelOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listWithCustomPageModel(this._client, options); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 492cd4f9a9..c8321b8687 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -29,6 +29,7 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, @@ -39,6 +40,7 @@ import { DeleteOptions, ExportOptions, } from "../models/options.js"; +import { buildPagedAsyncIterator } from "../util/pagingUtil.js"; export function _createOrUpdateSend( context: Client, @@ -235,12 +237,14 @@ export async function _listDeserialize( } /** Lists all Users */ -export async function list( +export function list( context: Client, options: ListOptions = { requestOptions: {} } -): Promise { - const result = await _listSend(context, options); - return _listDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator(context, _listSend, _listDeserialize, [ + context, + options, + ]); } export function _listWithPageSend( @@ -275,12 +279,16 @@ export async function _listWithPageDeserialize( } /** List with Azure.Core.Page<>. */ -export async function listWithPage( +export function listWithPage( context: Client, options: ListWithPageOptions = { requestOptions: {} } -): Promise { - const result = await _listWithPageSend(context, options); - return _listWithPageDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listWithPageSend, + _listWithPageDeserialize, + [context, options] + ); } export function _listWithCustomPageModelSend( @@ -319,12 +327,16 @@ export async function _listWithCustomPageModelDeserialize( } /** List with custom page model. */ -export async function listWithCustomPageModel( +export function listWithCustomPageModel( context: Client, options: ListWithCustomPageModelOptions = { requestOptions: {} } -): Promise { - const result = await _listWithCustomPageModelSend(context, options); - return _listWithCustomPageModelDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listWithCustomPageModelSend, + _listWithCustomPageModelDeserialize, + [context, options] + ); } export function _deleteOperationSend( diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts index 6521a8e214..bee953a15b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts @@ -16,3 +16,7 @@ export { DeleteOptions, ExportOptions, } from "./models/index.js"; +export { + getContinuationToken, + setContinuationToken, +} from "./util/pagingUtil.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts new file mode 100644 index 0000000000..73201a2e7b --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +export interface PageInfo { + continuationToken?: string; +} + +const pageMap = new WeakMap(); + +/** + * Given the last `.value` produced by the `byPage` iterator, + * returns a continuation token that can be used to begin paging from + * that point later. + * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. + * @returns The continuation token that can be passed into byPage() during future calls. + */ +export function getContinuationToken(page: unknown): string | undefined { + if (typeof page !== "object" || page === null) { + return undefined; + } + return pageMap.get(page)?.continuationToken; +} + +export function setContinuationToken( + page: unknown, + continuationToken: string | undefined +): void { + if (typeof page !== "object" || page === null || !continuationToken) { + return; + } + const pageInfo = pageMap.get(page) ?? {}; + pageInfo.continuationToken = continuationToken; + pageMap.set(page, pageInfo); +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: ( + resp: TResponse | PathUncheckedResponse + ) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string, maxPageSize?: number) => { + if (maxPageSize) { + throw new Error("maxPageSize is not supported by this operation."); + } + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} From 46a92cd07c83525fc4620c084b7450538b9f4022 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 17:17:18 +0800 Subject: [PATCH 02/60] Update the page return type --- .../src/modular/helpers/operationHelpers.ts | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index aa9d8fcc83..388fe7fa7f 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -245,12 +245,17 @@ export function getOperationFunction( // TODO: Support operation overloads const response = operation.responses[0]!; - const returnType = response?.type?.type - ? buildType(response.type.name, response.type) - : { name: "", type: "void" }; + let returnType = { name: "", type: "void" }; + if (response.type?.type) { + let type = response.type; + if (isPaging) { + type = extractPagingType(type, operation.itemName) ?? type; + } + returnType = buildType(type.name, type); + } // TODO: calculate the page return const operationReturnType = isPaging - ? `PagedAsyncIterableIterator` + ? `PagedAsyncIterableIterator<${returnType.type}>` : `Promise<${returnType.type}>`; const { name, fixme = [] } = getOperationName(operation); @@ -288,6 +293,21 @@ export function getOperationFunction( }; } +function extractPagingType(type: Type, itemName?: string): Type | undefined { + if (!itemName) { + return undefined; + } + const prop = (type.properties ?? []) + ?.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, includeGroupName = false From b9873b023404d2a0a0322465f7fc9a68ac40c8b7 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 17:21:28 +0800 Subject: [PATCH 03/60] Refactor code --- .../typespec-ts/src/modular/helpers/operationHelpers.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 388fe7fa7f..eca18166f5 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -253,11 +253,6 @@ export function getOperationFunction( } returnType = buildType(type.name, type); } - // TODO: calculate the page return - const operationReturnType = isPaging - ? `PagedAsyncIterableIterator<${returnType.type}>` - : `Promise<${returnType.type}>`; - const { name, fixme = [] } = getOperationName(operation); const functionStatement: OptionalKind = { docs: [ @@ -268,7 +263,9 @@ export function getOperationFunction( isExported: true, name: normalizeName(operation.name, NameType.Operation, true), parameters, - returnType: operationReturnType + returnType: isPaging + ? `PagedAsyncIterableIterator<${returnType.type}>` + : `Promise<${returnType.type}>` }; const statements: string[] = []; From ea2c7bcac64543922ae1a0d84aa734fffc76a6ec Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 17:24:06 +0800 Subject: [PATCH 04/60] Update the comments --- packages/typespec-ts/src/modular/static/pagingUtil.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/typespec-ts/src/modular/static/pagingUtil.ts b/packages/typespec-ts/src/modular/static/pagingUtil.ts index 4e1f1304c9..21cc7f797f 100644 --- a/packages/typespec-ts/src/modular/static/pagingUtil.ts +++ b/packages/typespec-ts/src/modular/static/pagingUtil.ts @@ -1,6 +1,3 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - import { getPagedAsyncIterator, PagedAsyncIterableIterator, From 9fcd40a0d5c166a9c9d049faa850b664b36e26ce Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 17:33:32 +0800 Subject: [PATCH 05/60] Update the cadl-ranch version --- common/config/rush/pnpm-lock.yaml | 8 +- packages/typespec-ts/package.json | 2 +- .../test/commands/cadl-ranch-list.ts | 5 + .../azure/core/src/util/pagingUtil.ts | 3 - .../payload/pageable/src/PageableClient.ts | 30 +++ .../pageable/src/api/PageableContext.ts | 18 ++ .../payload/pageable/src/api/index.ts | 9 + .../payload/pageable/src/api/operations.ts | 48 ++++ .../generated/payload/pageable/src/index.ts | 9 + .../generated/payload/pageable/src/logger.ts | 5 + .../payload/pageable/src/models/index.ts | 5 + .../payload/pageable/src/models/models.ts | 16 ++ .../payload/pageable/src/models/options.ts | 9 + .../pageable/src/rest/clientDefinitions.ts | 20 ++ .../payload/pageable/src/rest/index.ts | 13 ++ .../payload/pageable/src/rest/outputModels.ts | 13 ++ .../pageable/src/rest/pageableClient.ts | 35 +++ .../pageable/src/rest/paginateHelper.ts | 154 +++++++++++++ .../payload/pageable/src/rest/parameters.ts | 15 ++ .../payload/pageable/src/rest/responses.ts | 11 + .../payload/pageable/src/util/pagingUtil.ts | 216 ++++++++++++++++++ .../generated/payload/pageable/tspconfig.yaml | 14 ++ 22 files changed, 650 insertions(+), 8 deletions(-) create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/PageableContext.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/logger.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/models.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/options.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/clientDefinitions.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/index.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/outputModels.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/pageableClient.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/paginateHelper.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/parameters.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/responses.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/tspconfig.yaml diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 4256774ee6..c67eb0f705 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -217,7 +217,7 @@ importers: '@azure-rest/core-client': ^1.1.4 '@azure-tools/cadl-ranch': ^0.7.0 '@azure-tools/cadl-ranch-expect': ^0.6.0 - '@azure-tools/cadl-ranch-specs': ^0.18.0 + '@azure-tools/cadl-ranch-specs': ^0.20.0 '@azure-tools/rlc-common': workspace:^0.15.0 '@azure-tools/typespec-azure-core': '>=0.33.0 <1.0.0' '@azure-tools/typespec-client-generator-core': '>=0.33.0 <1.0.0' @@ -267,7 +267,7 @@ importers: '@azure-rest/core-client': 1.1.4 '@azure-tools/cadl-ranch': 0.7.0_d7m5nitpni5mqp3y5w3y4aqymu '@azure-tools/cadl-ranch-expect': 0.6.0_ccoaydaumvpjzq7pj6wod3i6ou - '@azure-tools/cadl-ranch-specs': 0.18.0_i6m56vm2373g7aupg6kc6ttsfe + '@azure-tools/cadl-ranch-specs': 0.20.0_i6m56vm2373g7aupg6kc6ttsfe '@azure/core-auth': 1.5.0 '@azure/core-lro': 2.5.4 '@azure/core-paging': 1.5.0 @@ -384,8 +384,8 @@ packages: '@typespec/versioning': 0.47.0_@typespec+compiler@0.47.1 dev: true - /@azure-tools/cadl-ranch-specs/0.18.0_i6m56vm2373g7aupg6kc6ttsfe: - resolution: {integrity: sha512-9BGsOzH+dZZo65vMmxa+faMvAbhFDRJueD4UxC0adgvCWFhloQipQtYcbDPsDqXOBM4PD7i3lzt5pI5/Qkfg0A==} + /@azure-tools/cadl-ranch-specs/0.20.0_i6m56vm2373g7aupg6kc6ttsfe: + resolution: {integrity: sha512-eCCZjuPXd3hy6psqh3Es9l9R6GQ7gqe/uPL56h1pUaOXcnvAAJGeny6N/USdqztYjcTx6JkX0V13/KnzGUdz/Q==} engines: {node: '>=16.0.0'} peerDependencies: '@azure-tools/cadl-ranch-expect': ~0.6.0 diff --git a/packages/typespec-ts/package.json b/packages/typespec-ts/package.json index 8e9abf6052..a56756cc6d 100644 --- a/packages/typespec-ts/package.json +++ b/packages/typespec-ts/package.json @@ -50,7 +50,7 @@ "ts-node": "^10.9.1", "typescript": "~5.0.0", "prettier": "~2.7.1", - "@azure-tools/cadl-ranch-specs": "^0.18.0", + "@azure-tools/cadl-ranch-specs": "^0.20.0", "@azure-tools/cadl-ranch-expect": "^0.6.0", "@azure-tools/cadl-ranch": "^0.7.0", "chalk": "^4.0.0", diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index 4ea4f28312..a200e788e6 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -207,5 +207,10 @@ export const modularTsps: TypeSpecRanchConfig[] = [ { outputPath: "azure/core", inputPath: "azure/core/basic" + }, + { + outputPath: "payload/pageable", + inputPath: "payload/pageable", + debug: true } ]; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts index 73201a2e7b..16a5b8b15a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - import { getPagedAsyncIterator, PagedAsyncIterableIterator, diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts new file mode 100644 index 0000000000..9628266714 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { User } from "./models/models.js"; +import { ListOptions } from "./models/options.js"; +import { + list, + createPageable, + PageableClientOptions, + PageableContext, +} from "./api/index.js"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; + +export { PageableClientOptions } from "./api/PageableContext.js"; + +export class PageableClient { + private _client: PageableContext; + + /** Test describing pageable. */ + constructor(options: PageableClientOptions = {}) { + this._client = createPageable(options); + } + + /** List users */ + list( + options: ListOptions = { requestOptions: {} } + ): PagedAsyncIterableIterator { + return list(this._client, options); + } +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/PageableContext.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/PageableContext.ts new file mode 100644 index 0000000000..83bd9b8fc0 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/PageableContext.ts @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ClientOptions } from "@azure-rest/core-client"; +import { PageableContext } from "../rest/index.js"; +import getClient from "../rest/index.js"; + +export interface PageableClientOptions extends ClientOptions {} + +export { PageableContext } from "../rest/index.js"; + +/** Test describing pageable. */ +export function createPageable( + options: PageableClientOptions = {} +): PageableContext { + const clientContext = getClient(options); + return clientContext; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/index.ts new file mode 100644 index 0000000000..7c45798210 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/index.ts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { list } from "./operations.js"; +export { + createPageable, + PageableClientOptions, + PageableContext, +} from "./PageableContext.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts new file mode 100644 index 0000000000..7e082ec1ca --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { PagedUser, User } from "../models/models.js"; +import { List200Response, PageableContext as Client } from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, +} from "@azure-rest/core-client"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { ListOptions } from "../models/options.js"; +import { buildPagedAsyncIterator } from "../util/pagingUtil.js"; + +export function _listSend( + context: Client, + options: ListOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/payload/pageable") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { maxpagesize: options?.maxpagesize }, + }); +} + +export async function _listDeserialize( + result: List200Response +): Promise { + if (result.status !== "200") { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ name: p["name"] })), + nextLink: result.body["nextLink"], + }; +} + +/** List users */ +export function list( + context: Client, + options: ListOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator(context, _listSend, _listDeserialize, [ + context, + options, + ]); +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts new file mode 100644 index 0000000000..c48416f4d3 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { PageableClient, PageableClientOptions } from "./PageableClient.js"; +export { PagedUser, User, ListOptions } from "./models/index.js"; +export { + getContinuationToken, + setContinuationToken, +} from "./util/pagingUtil.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/logger.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/logger.ts new file mode 100644 index 0000000000..174a3a425d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/logger.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { createClientLogger } from "@azure/logger"; +export const logger = createClientLogger("payload-pageable"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts new file mode 100644 index 0000000000..ade0de25f2 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts @@ -0,0 +1,5 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { PagedUser, User } from "./models.js"; +export { ListOptions } from "./options.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/models.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/models.ts new file mode 100644 index 0000000000..3daeac79db --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/models.ts @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** Paged collection of User items */ +export interface PagedUser { + /** The User items on this page */ + value: User[]; + /** The link to the next page of items */ + nextLink?: string; +} + +/** User model */ +export interface User { + /** User name */ + name: string; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/options.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/options.ts new file mode 100644 index 0000000000..e644e0ef53 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/options.ts @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface ListOptions extends OperationOptions { + /** The maximum number of result items per page. */ + maxpagesize?: number; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/clientDefinitions.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/clientDefinitions.ts new file mode 100644 index 0000000000..0fad321cba --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/clientDefinitions.ts @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { ListParameters } from "./parameters.js"; +import { List200Response } from "./responses.js"; +import { Client, StreamableMethod } from "@azure-rest/core-client"; + +export interface List { + /** List users */ + get(options?: ListParameters): StreamableMethod; +} + +export interface Routes { + /** Resource for '/payload/pageable' has methods for the following verbs: get */ + (path: "/payload/pageable"): List; +} + +export type PageableContext = Client & { + path: Routes; +}; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/index.ts new file mode 100644 index 0000000000..5a40467423 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/index.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import PageableClient from "./pageableClient.js"; + +export * from "./pageableClient.js"; +export * from "./parameters.js"; +export * from "./responses.js"; +export * from "./clientDefinitions.js"; +export * from "./outputModels.js"; +export * from "./paginateHelper.js"; + +export default PageableClient; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/outputModels.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/outputModels.ts new file mode 100644 index 0000000000..606feaf02f --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/outputModels.ts @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Paged } from "@azure/core-paging"; + +/** User model */ +export interface UserOutput { + /** User name */ + name: string; +} + +/** Paged collection of User items */ +export type PagedUserOutput = Paged; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/pageableClient.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/pageableClient.ts new file mode 100644 index 0000000000..a5b47a1d7a --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/pageableClient.ts @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { getClient, ClientOptions } from "@azure-rest/core-client"; +import { logger } from "../logger.js"; +import { PageableContext } from "./clientDefinitions.js"; + +/** + * Initialize a new instance of `PageableContext` + * @param options - the parameter for all optional parameters + */ +export default function createClient( + options: ClientOptions = {} +): PageableContext { + const baseUrl = options.baseUrl ?? `http://localhost:3000`; + options.apiVersion = options.apiVersion ?? "1.0.0"; + const userAgentInfo = `azsdk-js-payload-pageable-rest/1.0.0-beta.1`; + const userAgentPrefix = + options.userAgentOptions && options.userAgentOptions.userAgentPrefix + ? `${options.userAgentOptions.userAgentPrefix} ${userAgentInfo}` + : `${userAgentInfo}`; + options = { + ...options, + userAgentOptions: { + userAgentPrefix, + }, + loggingOptions: { + logger: options.loggingOptions?.logger ?? logger.info, + }, + }; + + const client = getClient(baseUrl, options) as PageableContext; + + return client; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/paginateHelper.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/paginateHelper.ts new file mode 100644 index 0000000000..1c9af35b1e --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/paginateHelper.ts @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = ( + pageLink: string, + maxPageSize?: number +) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends { + body: { value?: infer TPage }; +} + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {} +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + const itemName = "value"; + const nextLinkName = "nextLink"; + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/parameters.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/parameters.ts new file mode 100644 index 0000000000..612f76120d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/parameters.ts @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { RequestParameters } from "@azure-rest/core-client"; + +export interface ListQueryParamProperties { + /** The maximum number of result items per page. */ + maxpagesize?: number; +} + +export interface ListQueryParam { + queryParameters?: ListQueryParamProperties; +} + +export type ListParameters = ListQueryParam & RequestParameters; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/responses.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/responses.ts new file mode 100644 index 0000000000..d615eae74b --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/rest/responses.ts @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { HttpResponse } from "@azure-rest/core-client"; +import { PagedUserOutput } from "./outputModels.js"; + +/** The request has succeeded. */ +export interface List200Response extends HttpResponse { + status: "200"; + body: PagedUserOutput; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts new file mode 100644 index 0000000000..16a5b8b15a --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +export interface PageInfo { + continuationToken?: string; +} + +const pageMap = new WeakMap(); + +/** + * Given the last `.value` produced by the `byPage` iterator, + * returns a continuation token that can be used to begin paging from + * that point later. + * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. + * @returns The continuation token that can be passed into byPage() during future calls. + */ +export function getContinuationToken(page: unknown): string | undefined { + if (typeof page !== "object" || page === null) { + return undefined; + } + return pageMap.get(page)?.continuationToken; +} + +export function setContinuationToken( + page: unknown, + continuationToken: string | undefined +): void { + if (typeof page !== "object" || page === null || !continuationToken) { + return; + } + const pageInfo = pageMap.get(page) ?? {}; + pageInfo.continuationToken = continuationToken; + pageMap.set(page, pageInfo); +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: ( + resp: TResponse | PathUncheckedResponse + ) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string, maxPageSize?: number) => { + if (maxPageSize) { + throw new Error("maxPageSize is not supported by this operation."); + } + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/tspconfig.yaml b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/tspconfig.yaml new file mode 100644 index 0000000000..c11fdc1769 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/tspconfig.yaml @@ -0,0 +1,14 @@ +emit: + - "@azure-tools/typespec-ts" +options: + "@azure-tools/typespec-ts": + "emitter-output-dir": "{project-root}" + generateMetadata: false + generateTest: false + addCredentials: false + azureSdkForJs: false + isTypeSpecTest: true + isModularLibrary: true + packageDetails: + name: "@msinternal/payload-pageable" + description: "Payload Pageable Test Service" From 9642e55f45349bb18b20fc2b026b62c1069b6663 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 22:00:26 +0800 Subject: [PATCH 06/60] Update the test cases and re-gen smoke testing --- .../review/ai-content-safety.api.md | 11 +- .../typespec-ts/src/ContentSafetyClient.ts | 7 +- .../typespec-ts/src/api/operations.ts | 26 ++- .../generated/typespec-ts/src/index.ts | 4 + .../typespec-ts/src/util/pagingUtil.ts | 215 ++++++++++++++++++ .../typespec-ts/review/load-testing.api.md | 20 +- .../generated/typespec-ts/src/index.ts | 4 + .../LoadTestAdministrationClient.ts | 7 +- .../loadTestAdministration/api/operations.ts | 26 ++- .../src/loadTestRun/LoadTestRunClient.ts | 12 +- .../src/loadTestRun/api/operations.ts | 42 ++-- .../typespec-ts/src/util/pagingUtil.ts | 215 ++++++++++++++++++ .../src/modular/buildClassicalClient.ts | 13 +- .../src/modular/buildOperations.ts | 11 +- .../typespec-ts/src/modular/buildRootIndex.ts | 7 +- .../src/modular/static/pagingUtil.ts | 7 +- .../azure/core/src/util/pagingUtil.ts | 7 +- .../payload/pageable/src/util/pagingUtil.ts | 7 +- .../test/modularIntegration/pageable.spec.ts | 98 ++++++++ 19 files changed, 662 insertions(+), 77 deletions(-) create mode 100644 packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts create mode 100644 packages/typespec-ts/test/modularIntegration/pageable.spec.ts 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 3949faeb43..dbc1f63e35 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 @@ -7,6 +7,7 @@ import { ClientOptions } from '@azure-rest/core-client'; import { KeyCredential } from '@azure/core-auth'; import { OperationOptions } from '@azure-rest/core-client'; +import { PagedAsyncIterableIterator } from '@azure/core-paging'; import { TokenCredential } from '@azure/core-auth'; // @public (undocumented) @@ -59,8 +60,8 @@ export class ContentSafetyClient { deleteTextBlocklist(blocklistName: string, options?: DeleteTextBlocklistOptions): Promise; getTextBlocklist(blocklistName: string, options?: GetTextBlocklistOptions): Promise; getTextBlocklistItem(blocklistName: string, blockItemId: string, options?: GetTextBlocklistItemOptions): Promise; - listTextBlocklistItems(blocklistName: string, options?: ListTextBlocklistItemsOptions): Promise; - listTextBlocklists(options?: ListTextBlocklistsOptions): Promise; + listTextBlocklistItems(blocklistName: string, options?: ListTextBlocklistItemsOptions): PagedAsyncIterableIterator; + listTextBlocklists(options?: ListTextBlocklistsOptions): PagedAsyncIterableIterator; removeBlockItems(blockItemIds: string[], blocklistName: string, options?: RemoveBlockItemsRequestOptions): Promise; } @@ -78,6 +79,9 @@ export interface CreateOrUpdateTextBlocklistOptions extends OperationOptions { export interface DeleteTextBlocklistOptions extends OperationOptions { } +// @public +export function getContinuationToken(page: unknown): string | undefined; + // @public (undocumented) export interface GetTextBlocklistItemOptions extends OperationOptions { } @@ -129,6 +133,9 @@ export interface PagedTextBlocklist { export interface RemoveBlockItemsRequestOptions extends OperationOptions { } +// @public (undocumented) +export function setContinuationToken(page: unknown, continuationToken: string | undefined): void; + // @public export interface TextAnalyzeSeverityResult { category: TextCategory; 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 87a787dc58..36cecddc0c 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 @@ -10,8 +10,6 @@ import { TextBlockItemInfo, AddOrUpdateBlockItemsResult, TextBlockItem, - PagedTextBlocklist, - PagedTextBlockItem, } from "./models/models.js"; import { AnalyzeTextRequestOptions, @@ -40,6 +38,7 @@ import { getTextBlocklistItem, listTextBlocklistItems, } from "./api/index.js"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; export { ContentSafetyClientOptions } from "./api/ContentSafetyContext.js"; @@ -98,7 +97,7 @@ export class ContentSafetyClient { /** Get all text blocklists details. */ listTextBlocklists( options: ListTextBlocklistsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTextBlocklists(this._client, options); } @@ -143,7 +142,7 @@ export class ContentSafetyClient { listTextBlocklistItems( blocklistName: string, options: ListTextBlocklistItemsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTextBlocklistItems(this._client, blocklistName, options); } } 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 a4cd1514cf..b042017d61 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 @@ -42,6 +42,7 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { AnalyzeTextRequestOptions, AnalyzeImageRequestOptions, @@ -54,6 +55,7 @@ import { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "../models/options.js"; +import { buildPagedAsyncIterator } from "../util/pagingUtil.js"; export function _analyzeTextSend( context: Client, @@ -302,12 +304,16 @@ export async function _listTextBlocklistsDeserialize( } /** Get all text blocklists details. */ -export async function listTextBlocklists( +export function listTextBlocklists( context: Client, options: ListTextBlocklistsOptions = { requestOptions: {} } -): Promise { - const result = await _listTextBlocklistsSend(context, options); - return _listTextBlocklistsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listTextBlocklistsSend, + _listTextBlocklistsDeserialize, + [context, options] + ); } export function _addOrUpdateBlockItemsSend( @@ -491,15 +497,15 @@ export async function _listTextBlocklistItemsDeserialize( } /** Get all blockItems in a text blocklist */ -export async function listTextBlocklistItems( +export function listTextBlocklistItems( context: Client, blocklistName: string, options: ListTextBlocklistItemsOptions = { requestOptions: {} } -): Promise { - const result = await _listTextBlocklistItemsSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - blocklistName, - options + _listTextBlocklistItemsSend, + _listTextBlocklistItemsDeserialize, + [context, blocklistName, options] ); - return _listTextBlocklistItemsDeserialize(result); } 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 b88674e51a..8c51c481b1 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 @@ -33,3 +33,7 @@ export { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "./models/index.js"; +export { + getContinuationToken, + setContinuationToken, +} from "./util/pagingUtil.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts new file mode 100644 index 0000000000..163afff75d --- /dev/null +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +export interface PageInfo { + continuationToken?: string; +} + +const pageMap = new WeakMap(); + +/** + * Given the last `.value` produced by the `byPage` iterator, + * returns a continuation token that can be used to begin paging from + * that point later. + * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. + * @returns The continuation token that can be passed into byPage() during future calls. + */ +export function getContinuationToken(page: unknown): string | undefined { + if (typeof page !== "object" || page === null) { + return undefined; + } + return pageMap.get(page)?.continuationToken; +} + +export function setContinuationToken( + page: unknown, + continuationToken: string | undefined +): void { + if (typeof page !== "object" || page === null || !continuationToken) { + return; + } + const pageInfo = pageMap.get(page) ?? {}; + pageInfo.continuationToken = continuationToken; + pageMap.set(page, pageInfo); +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: (result: TResponse) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string, maxPageSize?: number) => { + if (maxPageSize) { + throw new Error("maxPageSize is not supported by this operation."); + } + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + setContinuationToken(values, nextLink); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} 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 082189e673..454dec26a5 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 @@ -6,6 +6,7 @@ import { ClientOptions } from '@azure-rest/core-client'; import { OperationOptions } from '@azure-rest/core-client'; +import { PagedAsyncIterableIterator } from '@azure/core-paging'; import { TokenCredential } from '@azure/core-auth'; // @public @@ -132,6 +133,9 @@ export type FileType = string; export interface GetAppComponentsOptions extends OperationOptions { } +// @public +export function getContinuationToken(page: unknown): string | undefined; + // @public (undocumented) export interface GetServerMetricsConfigOptions extends OperationOptions { } @@ -217,8 +221,8 @@ export class LoadTestAdministrationClient { getServerMetricsConfig(testId: string, options?: GetServerMetricsConfigOptions): Promise; getTest(testId: string, options?: GetTestOptions): Promise; getTestFile(testId: string, fileName: string, options?: GetTestFileOptions): Promise; - listTestFiles(testId: string, options?: ListTestFilesOptions): Promise; - listTests(options?: ListTestsOptions): Promise; + listTestFiles(testId: string, options?: ListTestFilesOptions): PagedAsyncIterableIterator; + listTests(options?: ListTestsOptions): PagedAsyncIterableIterator; uploadTestFile(body: Uint8Array, testId: string, fileName: string, options?: UploadTestFileOptions): Promise; } @@ -248,14 +252,11 @@ export class LoadTestRunClient { getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptions): Promise; // Warning: (ae-forgotten-export) The symbol "MetricDefinitionCollection" needs to be exported by the entry point index.d.ts listMetricDefinitions(testRunId: string, options?: ListMetricDefinitionsOptions): Promise; - // Warning: (ae-forgotten-export) The symbol "PagedDimensionValueList" needs to be exported by the entry point index.d.ts - listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptions): Promise; + listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptions): PagedAsyncIterableIterator; // Warning: (ae-forgotten-export) The symbol "MetricNamespaceCollection" needs to be exported by the entry point index.d.ts listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptions): Promise; - // Warning: (ae-forgotten-export) The symbol "PagedTimeSeriesElement" needs to be exported by the entry point index.d.ts - listMetrics(testRunId: string, options?: ListMetricsOptions): Promise; - // Warning: (ae-forgotten-export) The symbol "PagedTestRun" needs to be exported by the entry point index.d.ts - listTestRuns(options?: ListTestRunsOptions): Promise; + listMetrics(testRunId: string, options?: ListMetricsOptions): PagedAsyncIterableIterator; + listTestRuns(options?: ListTestRunsOptions): PagedAsyncIterableIterator; stopTestRun(testRunId: string, options?: StopTestRunOptions): Promise; testRun(testRunId: string, options?: TestRunOptions): Promise; } @@ -688,6 +689,9 @@ export interface Secret { // @public export type SecretType = string; +// @public (undocumented) +export function setContinuationToken(page: unknown, continuationToken: string | undefined): void; + // @public export type Status = string; 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 cd91d5d41b..46ba67b2f8 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 @@ -63,6 +63,10 @@ export { DeleteTestFileOptions, DeleteTestOptions, } from "./loadTestAdministration/models/index.js"; +export { + getContinuationToken, + setContinuationToken, +} from "./util/pagingUtil.js"; export { LoadTestRunClient, LoadTestRunClientOptions, 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 4fea050495..0287705b5f 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 @@ -8,8 +8,6 @@ import { TestAppComponents, AppComponent, TestServerMetricConfig, - PagedFileInfo, - PagedTest, } from "./models/models.js"; import { CreateOrUpdateTestOptions, @@ -42,6 +40,7 @@ import { deleteTestFile, deleteTest, } from "./api/index.js"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; export { LoadTestAdministrationClientOptions } from "./api/LoadTestAdministrationContext.js"; @@ -123,7 +122,7 @@ export class LoadTestAdministrationClient { listTestFiles( testId: string, options: ListTestFilesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTestFiles(this._client, testId, options); } @@ -133,7 +132,7 @@ export class LoadTestAdministrationClient { */ listTests( options: ListTestsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTests(this._client, options); } 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 1c1a4e0033..4ec4cb73b2 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 @@ -45,6 +45,8 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { buildPagedAsyncIterator } from "../../util/pagingUtil.js"; import { CreateOrUpdateTestOptions, CreateOrUpdateAppComponentsOptions, @@ -766,13 +768,17 @@ export async function _listTestFilesDeserialize( } /** Get all test files. */ -export async function listTestFiles( +export function listTestFiles( context: Client, testId: string, options: ListTestFilesOptions = { requestOptions: {} } -): Promise { - const result = await _listTestFilesSend(context, testId, options); - return _listTestFilesDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listTestFilesSend, + _listTestFilesDeserialize, + [context, testId, options] + ); } export function _listTestsSend( @@ -947,12 +953,16 @@ export async function _listTestsDeserialize( * Get all load tests by the fully qualified resource Id e.g * subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.LoadTestService/loadtests/{resName}. */ -export async function listTests( +export function listTests( context: Client, options: ListTestsOptions = { requestOptions: {} } -): Promise { - const result = await _listTestsSend(context, options); - return _listTestsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listTestsSend, + _listTestsDeserialize, + [context, options] + ); } export function _uploadTestFileSend( 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 5682157ae5..e6f48fe62d 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 @@ -10,9 +10,8 @@ import { TestRunServerMetricConfig, MetricDefinitionCollection, MetricNamespaceCollection, - PagedTimeSeriesElement, - PagedTestRun, - PagedDimensionValueList, + TimeSeriesElement, + DimensionValueList, } from "./models/models.js"; import { TestRunOptions, @@ -49,6 +48,7 @@ import { listTestRuns, stopTestRun, } from "./api/index.js"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; export { LoadTestRunClientOptions } from "./api/LoadTestRunContext.js"; @@ -143,7 +143,7 @@ export class LoadTestRunClient { name: string, metricNamespace: string, options: ListMetricDimensionValuesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listMetricDimensionValues( this._client, testRunId, @@ -173,14 +173,14 @@ export class LoadTestRunClient { listMetrics( testRunId: string, options: ListMetricsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listMetrics(this._client, testRunId, options); } /** Get all test runs with given filters */ listTestRuns( options: ListTestRunsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTestRuns(this._client, options); } 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 c6b9f45b38..d28111e66e 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 @@ -10,8 +10,10 @@ import { MetricDefinitionCollection, MetricNamespaceCollection, PagedTimeSeriesElement, + TimeSeriesElement, PagedTestRun, PagedDimensionValueList, + DimensionValueList, } from "../models/models.js"; import { isUnexpected, @@ -53,6 +55,8 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { buildPagedAsyncIterator } from "../../util/pagingUtil.js"; import { TestRunOptions, CreateOrUpdateAppComponentsOptions, @@ -953,21 +957,19 @@ export async function _listMetricDimensionValuesDeserialize( } /** List the dimension values for the given metric dimension name. */ -export async function listMetricDimensionValues( +export function listMetricDimensionValues( context: Client, testRunId: string, name: string, metricNamespace: string, options: ListMetricDimensionValuesOptions = { requestOptions: {} } -): Promise { - const result = await _listMetricDimensionValuesSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - testRunId, - name, - metricNamespace, - options + _listMetricDimensionValuesSend, + _listMetricDimensionValuesDeserialize, + [context, testRunId, name, metricNamespace, options] ); - return _listMetricDimensionValuesDeserialize(result); } export function _listMetricDefinitionsSend( @@ -1111,13 +1113,17 @@ export async function _listMetricsDeserialize( } /** List the metric values for a load test run. */ -export async function listMetrics( +export function listMetrics( context: Client, testRunId: string, options: ListMetricsOptions = { requestOptions: {} } -): Promise { - const result = await _listMetricsSend(context, testRunId, options); - return _listMetricsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listMetricsSend, + _listMetricsDeserialize, + [context, testRunId, options] + ); } export function _listTestRunsSend( @@ -1404,12 +1410,16 @@ export async function _listTestRunsDeserialize( } /** Get all test runs with given filters */ -export async function listTestRuns( +export function listTestRuns( context: Client, options: ListTestRunsOptions = { requestOptions: {} } -): Promise { - const result = await _listTestRunsSend(context, options); - return _listTestRunsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listTestRunsSend, + _listTestRunsDeserialize, + [context, options] + ); } export function _stopTestRunSend( diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts new file mode 100644 index 0000000000..163afff75d --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +export interface PageInfo { + continuationToken?: string; +} + +const pageMap = new WeakMap(); + +/** + * Given the last `.value` produced by the `byPage` iterator, + * returns a continuation token that can be used to begin paging from + * that point later. + * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. + * @returns The continuation token that can be passed into byPage() during future calls. + */ +export function getContinuationToken(page: unknown): string | undefined { + if (typeof page !== "object" || page === null) { + return undefined; + } + return pageMap.get(page)?.continuationToken; +} + +export function setContinuationToken( + page: unknown, + continuationToken: string | undefined +): void { + if (typeof page !== "object" || page === null || !continuationToken) { + return; + } + const pageInfo = pageMap.get(page) ?? {}; + pageInfo.continuationToken = continuationToken; + pageMap.set(page, pageInfo); +} + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: (result: TResponse) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string, maxPageSize?: number) => { + if (maxPageSize) { + throw new Error("maxPageSize is not supported by this operation."); + } + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + setContinuationToken(values, nextLink); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index 9a937d5673..59a1eb1c15 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -10,7 +10,10 @@ import { import { toCamelCase } from "../utils/casingUtils.js"; import { getClientParameters } from "./helpers/clientHelpers.js"; import { getClientName } from "./helpers/namingHelpers.js"; -import { getOperationFunction } from "./helpers/operationHelpers.js"; +import { + getOperationFunction, + hasPagingOperation +} from "./helpers/operationHelpers.js"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; import { getDocsFromDescription } from "./helpers/docsHelpers.js"; @@ -73,6 +76,14 @@ export function buildClassicalClient( importAllModels(clientFile, srcPath, subfolder); buildClientOperationGroups(client, clientClass, subfolder); importAllApis(clientFile, srcPath, subfolder); + if (hasPagingOperation(codeModel)) { + clientFile.addImportDeclarations([ + { + moduleSpecifier: "@azure/core-paging", + namedImports: ["PagedAsyncIterableIterator"] + } + ]); + } clientFile.fixMissingImports(); clientFile.fixUnusedIdentifiers(); } diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index a03ac3bcd9..459a612fe0 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -5,7 +5,8 @@ import { getOperationFunction, getSendPrivateFunction, getDeserializePrivateFunction, - getOperationOptionsName + getOperationOptionsName, + hasPagingOperation } from "./helpers/operationHelpers.js"; import { Client, ModularCodeModel, Operation } from "./modularCodeModel.js"; import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; @@ -111,6 +112,14 @@ export function buildOperationFiles( ]); } } + if (hasPagingOperation(codeModel)) { + operationGroupFile.addImportDeclarations([ + { + moduleSpecifier: "@azure/core-paging", + namedImports: ["PagedAsyncIterableIterator"] + } + ]); + } operationGroupFile.fixMissingImports(); // have to fixUnusedIdentifiers after everything get generated. operationGroupFile.fixUnusedIdentifiers(); diff --git a/packages/typespec-ts/src/modular/buildRootIndex.ts b/packages/typespec-ts/src/modular/buildRootIndex.ts index cc45480183..2448d07b0a 100644 --- a/packages/typespec-ts/src/modular/buildRootIndex.ts +++ b/packages/typespec-ts/src/modular/buildRootIndex.ts @@ -1,6 +1,7 @@ import { Project, SourceFile } from "ts-morph"; import { getClientName } from "./helpers/namingHelpers.js"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; +import { hasPagingOperation } from "./helpers/operationHelpers.js"; export function buildRootIndex( codeModel: ModularCodeModel, @@ -81,11 +82,7 @@ function exportPagingUtil( if (client !== codeModel.clients[0]) { return; } - const hasPaging = codeModel.clients.some((client) => - client.operationGroups.some((group) => - group.operations.some((op) => op.discriminator === "paging") - ) - ); + const hasPaging = hasPagingOperation(codeModel); if (!hasPaging) { return; } diff --git a/packages/typespec-ts/src/modular/static/pagingUtil.ts b/packages/typespec-ts/src/modular/static/pagingUtil.ts index 21cc7f797f..201b16b549 100644 --- a/packages/typespec-ts/src/modular/static/pagingUtil.ts +++ b/packages/typespec-ts/src/modular/static/pagingUtil.ts @@ -69,9 +69,7 @@ export function buildPagedAsyncIterator< >( client: Client, initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: ( - resp: TResponse | PathUncheckedResponse - ) => Promise, + deserializeFunction: (result: TResponse) => Promise, sendFunctionArgs: any[] = [] ): PagedAsyncIterableIterator { let firstRun = true; @@ -94,9 +92,10 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result); + const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); + setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts index 16a5b8b15a..163afff75d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts @@ -72,9 +72,7 @@ export function buildPagedAsyncIterator< >( client: Client, initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: ( - resp: TResponse | PathUncheckedResponse - ) => Promise, + deserializeFunction: (result: TResponse) => Promise, sendFunctionArgs: any[] = [] ): PagedAsyncIterableIterator { let firstRun = true; @@ -97,9 +95,10 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result); + const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); + setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink, diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts index 16a5b8b15a..163afff75d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts @@ -72,9 +72,7 @@ export function buildPagedAsyncIterator< >( client: Client, initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: ( - resp: TResponse | PathUncheckedResponse - ) => Promise, + deserializeFunction: (result: TResponse) => Promise, sendFunctionArgs: any[] = [] ): PagedAsyncIterableIterator { let firstRun = true; @@ -97,9 +95,10 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result); + const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); + setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink, diff --git a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts b/packages/typespec-ts/test/modularIntegration/pageable.spec.ts new file mode 100644 index 0000000000..53dcac18b1 --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/pageable.spec.ts @@ -0,0 +1,98 @@ +import { + PageableClient, + User, + getContinuationToken +} from "./generated/payload/pageable/src/index.js"; +import { assert } from "chai"; + +describe("PageableClient Classical Client", () => { + let client: PageableClient; + + beforeEach(() => { + client = new PageableClient({ + allowInsecureConnection: true + }); + }); + + it("should throw exceptions if no maxpagesize set", async () => { + const iter = client.list(); + const items = []; + try { + for await (const user of iter) { + items.push(user); + } + assert.fail("Should throw exception"); + } catch (err: any) { + assert.isNotNull(err); + } + }); + + it("should list all users if maxpagesize=3", async () => { + const iter = client.list({ + maxpagesize: 3 + }); + const items = []; + try { + for await (const user of iter) { + items.push(user); + } + assert.strictEqual(items.length, 4); + } catch (err: any) { + assert.fail(err as string); + } + }); + + it("should list all users byPage", async () => { + const iter = client.list({ + maxpagesize: 3 + }); + const items: User[] = []; + try { + for await (const user of iter.byPage()) { + items.push(...user); + } + assert.strictEqual(items.length, 4); + } catch (err: any) { + assert.fail(err as string); + } + }); + + it("should list left users byPage if continuationToken is set", async () => { + const iter = client.list({ + maxpagesize: 3 + }); + /** + * two pages: + * - 1st page has 3 items + * - 2nd page has 1 item + */ + const firstPage = await iter.byPage().next(); + assert.strictEqual(firstPage.done, false); + assert.strictEqual(firstPage.value.length, 3); + // initiate another iterator starting with 2nd page + const continuationToken = getContinuationToken(firstPage.value); + const items: User[] = []; + for await (const pagedUsers of iter.byPage({ continuationToken })) { + items.push(...pagedUsers); + } + assert.strictEqual(items.length, 1); + }); + + it("maxPageSize is not allowed and should throw exceptions", async () => { + const pagedIter = client.list().byPage({ maxPageSize: 10 }); + try { + const items: User[] = []; + for await (const user of pagedIter) { + items.push(...user); + } + assert.fail( + "`maxPageSize` is not allowed to customize and should throw exceptions" + ); + } catch (err: any) { + assert.strictEqual( + err.message, + "maxPageSize is not supported by this operation." + ); + } + }); +}); From 18987a0eb2032a0533f710a873d33f1952af37c1 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 22:14:10 +0800 Subject: [PATCH 07/60] update paths --- packages/typespec-ts/test/commands/cadl-ranch-list.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index a200e788e6..c5d8f96ceb 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -87,7 +87,7 @@ export const rlcTsps: TypeSpecRanchConfig[] = [ }, { outputPath: "models/propertyOptional", - inputPath: "type/property/optional" + inputPath: "type/property/optionality" }, { outputPath: "models/propertyNullable", From e8be6adc958e89b017f57c21f130444a9076f7fe Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 29 Aug 2023 22:32:31 +0800 Subject: [PATCH 08/60] Regenerate rlc codes in int testing --- .../generated/unions/src/clientDefinitions.ts | 40 +++++++++++++++++++ .../integration/generated/unions/src/index.ts | 1 + .../generated/unions/src/outputModels.ts | 27 +++++++++++++ .../generated/unions/src/parameters.ts | 4 ++ .../generated/unions/src/responses.ts | 28 +++++++++++++ 5 files changed, 100 insertions(+) create mode 100644 packages/typespec-ts/test/integration/generated/unions/src/outputModels.ts diff --git a/packages/typespec-ts/test/integration/generated/unions/src/clientDefinitions.ts b/packages/typespec-ts/test/integration/generated/unions/src/clientDefinitions.ts index 1d00282e44..2d8977d277 100644 --- a/packages/typespec-ts/test/integration/generated/unions/src/clientDefinitions.ts +++ b/packages/typespec-ts/test/integration/generated/unions/src/clientDefinitions.ts @@ -6,12 +6,20 @@ import { SendIntArrayParameters, SendFirstNamedUnionValueParameters, SendSecondNamedUnionValueParameters, + ReceiveStringParameters, + ReceiveIntArrayParameters, + ReceiveFirstNamedUnionValueParameters, + ReceiveSecondNamedUnionValueParameters, } from "./parameters"; import { SendInt200Response, SendIntArray200Response, SendFirstNamedUnionValue200Response, SendSecondNamedUnionValue200Response, + ReceiveString200Response, + ReceiveIntArray200Response, + ReceiveFirstNamedUnionValue200Response, + ReceiveSecondNamedUnionValue200Response, } from "./responses"; import { Client, StreamableMethod } from "@azure-rest/core-client"; @@ -37,6 +45,30 @@ export interface SendSecondNamedUnionValue { ): StreamableMethod; } +export interface ReceiveString { + get( + options?: ReceiveStringParameters + ): StreamableMethod; +} + +export interface ReceiveIntArray { + get( + options?: ReceiveIntArrayParameters + ): StreamableMethod; +} + +export interface ReceiveFirstNamedUnionValue { + get( + options?: ReceiveFirstNamedUnionValueParameters + ): StreamableMethod; +} + +export interface ReceiveSecondNamedUnionValue { + get( + options?: ReceiveSecondNamedUnionValueParameters + ): StreamableMethod; +} + export interface Routes { /** Resource for '/type/union/int' has methods for the following verbs: post */ (path: "/type/union/int"): SendInt; @@ -46,6 +78,14 @@ export interface Routes { (path: "/type/union/model1"): SendFirstNamedUnionValue; /** Resource for '/type/union/model2' has methods for the following verbs: post */ (path: "/type/union/model2"): SendSecondNamedUnionValue; + /** Resource for '/type/union/receive/string' has methods for the following verbs: get */ + (path: "/type/union/receive/string"): ReceiveString; + /** Resource for '/type/union/receive/int-array' has methods for the following verbs: get */ + (path: "/type/union/receive/int-array"): ReceiveIntArray; + /** Resource for '/type/union/receive/model1' has methods for the following verbs: get */ + (path: "/type/union/receive/model1"): ReceiveFirstNamedUnionValue; + /** Resource for '/type/union/receive/model2' has methods for the following verbs: get */ + (path: "/type/union/receive/model2"): ReceiveSecondNamedUnionValue; } export type UnionsClient = Client & { diff --git a/packages/typespec-ts/test/integration/generated/unions/src/index.ts b/packages/typespec-ts/test/integration/generated/unions/src/index.ts index 07dc5f4619..14a67c2385 100644 --- a/packages/typespec-ts/test/integration/generated/unions/src/index.ts +++ b/packages/typespec-ts/test/integration/generated/unions/src/index.ts @@ -8,5 +8,6 @@ export * from "./parameters"; export * from "./responses"; export * from "./clientDefinitions"; export * from "./models"; +export * from "./outputModels"; export default UnionsClient; diff --git a/packages/typespec-ts/test/integration/generated/unions/src/outputModels.ts b/packages/typespec-ts/test/integration/generated/unions/src/outputModels.ts new file mode 100644 index 0000000000..135d9cadf5 --- /dev/null +++ b/packages/typespec-ts/test/integration/generated/unions/src/outputModels.ts @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** The first one of the unioned model type. */ +export interface Model1Output extends BaseModelOutput { + prop1: number; +} + +/** This is a base model. */ +export interface BaseModelOutput { + name: string; +} + +/** The second one of the unioned model type. */ +export interface Model2Output extends BaseModelOutput { + prop2: number; +} + +export interface ModelWithSimpleUnionPropertyInResponseOutput { + simpleUnion: string | number[]; +} + +export interface ModelWithNamedUnionPropertyInResponseOutput { + namedUnion: MyNamedUnionOutput; +} + +export type MyNamedUnionOutput = Model1Output | Model2Output; diff --git a/packages/typespec-ts/test/integration/generated/unions/src/parameters.ts b/packages/typespec-ts/test/integration/generated/unions/src/parameters.ts index 99006c883f..7e8929ff67 100644 --- a/packages/typespec-ts/test/integration/generated/unions/src/parameters.ts +++ b/packages/typespec-ts/test/integration/generated/unions/src/parameters.ts @@ -32,3 +32,7 @@ export interface SendSecondNamedUnionValueBodyParam { export type SendSecondNamedUnionValueParameters = SendSecondNamedUnionValueBodyParam & RequestParameters; +export type ReceiveStringParameters = RequestParameters; +export type ReceiveIntArrayParameters = RequestParameters; +export type ReceiveFirstNamedUnionValueParameters = RequestParameters; +export type ReceiveSecondNamedUnionValueParameters = RequestParameters; diff --git a/packages/typespec-ts/test/integration/generated/unions/src/responses.ts b/packages/typespec-ts/test/integration/generated/unions/src/responses.ts index 91bc6716c9..ef30ce1156 100644 --- a/packages/typespec-ts/test/integration/generated/unions/src/responses.ts +++ b/packages/typespec-ts/test/integration/generated/unions/src/responses.ts @@ -2,6 +2,10 @@ // Licensed under the MIT license. import { HttpResponse } from "@azure-rest/core-client"; +import { + ModelWithSimpleUnionPropertyInResponseOutput, + ModelWithNamedUnionPropertyInResponseOutput, +} from "./outputModels"; /** The request has succeeded. */ export interface SendInt200Response extends HttpResponse { @@ -22,3 +26,27 @@ export interface SendFirstNamedUnionValue200Response extends HttpResponse { export interface SendSecondNamedUnionValue200Response extends HttpResponse { status: "200"; } + +/** The request has succeeded. */ +export interface ReceiveString200Response extends HttpResponse { + status: "200"; + body: ModelWithSimpleUnionPropertyInResponseOutput; +} + +/** The request has succeeded. */ +export interface ReceiveIntArray200Response extends HttpResponse { + status: "200"; + body: ModelWithSimpleUnionPropertyInResponseOutput; +} + +/** The request has succeeded. */ +export interface ReceiveFirstNamedUnionValue200Response extends HttpResponse { + status: "200"; + body: ModelWithNamedUnionPropertyInResponseOutput; +} + +/** The request has succeeded. */ +export interface ReceiveSecondNamedUnionValue200Response extends HttpResponse { + status: "200"; + body: ModelWithNamedUnionPropertyInResponseOutput; +} From 80390142f2ff3964d65e8178399f4f1bb637e425 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Fri, 8 Sep 2023 18:05:04 +0800 Subject: [PATCH 09/60] Update the changes --- .../test/modularIntegration/azureCore.spec.ts | 10 +- .../generated/azure/core/src/BasicClient.ts | 6 +- .../azure/core/src/api/operations.ts | 125 +++++++++--------- .../azure/core/src/util/pagingUtil.ts | 103 +++++++++++++-- 4 files changed, 160 insertions(+), 84 deletions(-) diff --git a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts index 7d68403cdb..bf1e0f6f35 100644 --- a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts @@ -10,7 +10,7 @@ describe("BasicClient Classical Client", () => { }); }); - describe("list", () => { + describe.only("list", () => { describe("next", () => { it("should list all users", async () => { const iter = client.list({ @@ -49,7 +49,7 @@ describe("BasicClient Classical Client", () => { const pagedItems = iter.byPage(); const items: User[] = []; for await (const page of pagedItems) { - items.push(...page); + items.push(...page.page); } assert.strictEqual(items.length, 2); assert.strictEqual(items[0]?.name, "Madge"); @@ -69,11 +69,11 @@ describe("BasicClient Classical Client", () => { expand: ["orders"], requestOptions: { skipUrlEncoding: true } }); - const pagedItems = iter.byPage({ maxPageSize: 10 }); + const pagedItems = iter.byPage({ maxPageSize: 10 } as any); try { const items: User[] = []; for await (const user of pagedItems) { - items.push(...user); + items.push(...user.page); } assert.fail( "`maxPageSize` is not allowed to customize and should throw exceptions" @@ -94,7 +94,7 @@ describe("BasicClient Classical Client", () => { }); const items: User[] = []; for await (const user of pagedItems) { - items.push(...user); + items.push(...user.page); } assert.strictEqual(items.length, 2); assert.strictEqual(items[0]?.name, "Madge"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts index 29e2825514..c5427872d5 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts @@ -10,7 +10,7 @@ import { ListWithPageOptions, ListWithCustomPageModelOptions, DeleteOptions, - ExportOptions, + ExportOptions } from "./models/options.js"; import { createBasic, @@ -23,9 +23,9 @@ import { listWithPage, listWithCustomPageModel, deleteOperation, - exportOperation, + exportOperation } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; export { BasicClientOptions } from "./api/BasicContext.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index c8321b8687..d98fdc390f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -23,13 +23,12 @@ import { ListWithCustomPageModel200Response, ListWithCustomPageModelDefaultResponse, ListWithPage200Response, - ListWithPageDefaultResponse, + ListWithPageDefaultResponse } from "../rest/index.js"; import { StreamableMethod, - operationOptionsToRequestParameters, + operationOptionsToRequestParameters } from "@azure-rest/core-client"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, @@ -38,9 +37,12 @@ import { ListWithPageOptions, ListWithCustomPageModelOptions, DeleteOptions, - ExportOptions, + ExportOptions } from "../models/options.js"; -import { buildPagedAsyncIterator } from "../util/pagingUtil.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator +} from "../util/pagingUtil.js"; export function _createOrUpdateSend( context: Client, @@ -52,14 +54,11 @@ export function _createOrUpdateSend( | CreateOrUpdate201Response | CreateOrUpdateDefaultResponse > { - return context - .path("/azure/core/basic/users/{id}", id) - .patch({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/merge-patch+json", - body: { name: name, orders: options?.orders }, - }); + return context.path("/azure/core/basic/users/{id}", id).patch({ + ...operationOptionsToRequestParameters(options), + contentType: (options.contentType as any) ?? "application/merge-patch+json", + body: { name: name, orders: options?.orders } + }); } export async function _createOrUpdateDeserialize( @@ -78,9 +77,9 @@ export async function _createOrUpdateDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: result.body["etag"], + etag: result.body["etag"] }; } @@ -105,12 +104,10 @@ export function _createOrReplaceSend( | CreateOrReplace201Response | CreateOrReplaceDefaultResponse > { - return context - .path("/azure/core/basic/users/{id}", id) - .put({ - ...operationOptionsToRequestParameters(options), - body: { name: name, orders: options?.orders }, - }); + return context.path("/azure/core/basic/users/{id}", id).put({ + ...operationOptionsToRequestParameters(options), + body: { name: name, orders: options?.orders } + }); } export async function _createOrReplaceDeserialize( @@ -129,9 +126,9 @@ export async function _createOrReplaceDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: result.body["etag"], + etag: result.body["etag"] }; } @@ -169,9 +166,9 @@ export async function _getDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: result.body["etag"], + etag: result.body["etag"] }; } @@ -189,29 +186,27 @@ export function _listSend( context: Client, options: ListOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/azure/core/basic/users") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - top: options?.top, - skip: options?.skip, - maxpagesize: options?.maxpagesize, - orderby: - options?.orderby !== undefined - ? buildMultiCollection(options?.orderby, "orderby") - : undefined, - filter: options?.filter, - select: - options?.select !== undefined - ? buildMultiCollection(options?.select, "select") - : undefined, - expand: - options?.expand !== undefined - ? buildMultiCollection(options?.expand, "expand") - : undefined, - }, - }); + return context.path("/azure/core/basic/users").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + top: options?.top, + skip: options?.skip, + maxpagesize: options?.maxpagesize, + orderby: + options?.orderby !== undefined + ? buildMultiCollection(options?.orderby, "orderby") + : undefined, + filter: options?.filter, + select: + options?.select !== undefined + ? buildMultiCollection(options?.select, "select") + : undefined, + expand: + options?.expand !== undefined + ? buildMultiCollection(options?.expand, "expand") + : undefined + } + }); } export async function _listDeserialize( @@ -228,11 +223,11 @@ export async function _listDeserialize( orders: (p["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: p["etag"], + etag: p["etag"] })), - nextLink: result.body["nextLink"], + nextLink: result.body["nextLink"] }; } @@ -243,7 +238,7 @@ export function list( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator(context, _listSend, _listDeserialize, [ context, - options, + options ]); } @@ -270,11 +265,11 @@ export async function _listWithPageDeserialize( orders: (p["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: p["etag"], + etag: p["etag"] })), - nextLink: result.body["nextLink"], + nextLink: result.body["nextLink"] }; } @@ -318,11 +313,11 @@ export async function _listWithCustomPageModelDeserialize( orders: (p["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: p["etag"], + etag: p["etag"] })), - nextLink: result.body["nextLink"], + nextLink: result.body["nextLink"] }; } @@ -383,12 +378,10 @@ export function _exportOperationSend( ): StreamableMethod< ExportOperation200Response | ExportOperationDefaultResponse > { - return context - .path("/azure/core/basic/users/{id}:export", id) - .post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { format: format }, - }); + return context.path("/azure/core/basic/users/{id}:export", id).post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { format: format } + }); } export async function _exportOperationDeserialize( @@ -404,9 +397,9 @@ export async function _exportOperationDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"], + detail: p["detail"] })), - etag: result.body["etag"], + etag: result.body["etag"] }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts index 163afff75d..9b6dda0cbd 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts @@ -3,13 +3,14 @@ import { getPagedAsyncIterator, - PagedAsyncIterableIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, PagedResult, + PageSettings as CorePageSettings } from "@azure/core-paging"; import { Client, createRestError, - PathUncheckedResponse, + PathUncheckedResponse } from "@azure-rest/core-client"; export interface PageInfo { @@ -66,6 +67,48 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; +export interface PageSettings { + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: string; +} + +export interface ContinuablePage { + /** + * Gets a list of elements in the page. + */ + page: TPage; + /** + * The token that keeps track of where to continue the iterator + */ + continuationToken?: TLink; +} + +/** + * An interface that allows async iterable iteration both to completion and by page. + */ +export interface PagedAsyncIterableIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator>; +} + export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -80,10 +123,7 @@ export function buildPagedAsyncIterator< const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string, maxPageSize?: number) => { - if (maxPageSize) { - throw new Error("maxPageSize is not supported by this operation."); - } + getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder ? await initialSendFunction(...sendFunctionArgs) @@ -101,12 +141,55 @@ export function buildPagedAsyncIterator< setContinuationToken(values, nextLink); return { page: values, - nextPageLink: nextLink, + nextPageLink: nextLink }; }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken + }) as any; + } }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); - return getPagedAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator>; + } + }; +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: TLink; + } = {} +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + yield { page: response.page, continuationToken: response.nextPageLink }; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + yield { page: response.page, continuationToken: response.nextPageLink }; + } } /** @@ -160,7 +243,7 @@ function checkPagingRequest(response: PathUncheckedResponse): void { "206", "207", "208", - "226", + "226" ]; if (!Http2xxStatusCodes.includes(response.status)) { throw createRestError( @@ -206,7 +289,7 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames, + ...itemNames ].join(" OR ")}` ); } From a835f80ad904472a1ff8f3c74181de30a6e747f7 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 13:28:14 +0800 Subject: [PATCH 10/60] Fix the build error --- packages/typespec-ts/src/modular/helpers/operationHelpers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 6c285805cd..e0d90f95d3 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -257,7 +257,7 @@ export function getOperationFunction( if (isPaging) { type = extractPagingType(type, operation.itemName) ?? type; } - returnType = buildType(type.name, type); + returnType = buildType(type.name, type, type.format); } const { name, fixme = [] } = getOperationName(operation); const functionStatement: OptionalKind = { From 38cc90c321db50186e5053ca6e0f52afb65c4c76 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 15:27:09 +0800 Subject: [PATCH 11/60] Update the page utils --- .../src/modular/static/pagingUtil.ts | 117 ++++++++++++------ 1 file changed, 81 insertions(+), 36 deletions(-) diff --git a/packages/typespec-ts/src/modular/static/pagingUtil.ts b/packages/typespec-ts/src/modular/static/pagingUtil.ts index 201b16b549..a750c4975b 100644 --- a/packages/typespec-ts/src/modular/static/pagingUtil.ts +++ b/packages/typespec-ts/src/modular/static/pagingUtil.ts @@ -1,7 +1,8 @@ import { getPagedAsyncIterator, - PagedAsyncIterableIterator, - PagedResult + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, + PagedResult, + PageSettings as CorePageSettings } from "@azure/core-paging"; import { Client, @@ -13,34 +14,6 @@ export interface PageInfo { continuationToken?: string; } -const pageMap = new WeakMap(); - -/** - * Given the last `.value` produced by the `byPage` iterator, - * returns a continuation token that can be used to begin paging from - * that point later. - * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. - * @returns The continuation token that can be passed into byPage() during future calls. - */ -export function getContinuationToken(page: unknown): string | undefined { - if (typeof page !== "object" || page === null) { - return undefined; - } - return pageMap.get(page)?.continuationToken; -} - -export function setContinuationToken( - page: unknown, - continuationToken: string | undefined -): void { - if (typeof page !== "object" || page === null || !continuationToken) { - return; - } - const pageInfo = pageMap.get(page) ?? {}; - pageInfo.continuationToken = continuationToken; - pageMap.set(page, pageInfo); -} - /** * Helper type to extract the type of an array */ @@ -63,6 +36,37 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} + export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -77,10 +81,7 @@ export function buildPagedAsyncIterator< const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string, maxPageSize?: number) => { - if (maxPageSize) { - throw new Error("maxPageSize is not supported by this operation."); - } + getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder ? await initialSendFunction(...sendFunctionArgs) @@ -95,15 +96,59 @@ export function buildPagedAsyncIterator< const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); - setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink }; + }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken + }) as any; + } + }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); + + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; } }; +} - return getPagedAsyncIterator(pagedResult); +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + yield { ...response.page, continuationToken: response.nextPageLink }; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + yield { ...response.page, continuationToken: response.nextPageLink }; + } } /** From 84b2a3dab36ced90cdd3dd8cfd7075691d57840f Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 15:28:46 +0800 Subject: [PATCH 12/60] Update the generation --- .../typespec-ts/src/modular/buildRootIndex.ts | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildRootIndex.ts b/packages/typespec-ts/src/modular/buildRootIndex.ts index 2448d07b0a..b412403eb3 100644 --- a/packages/typespec-ts/src/modular/buildRootIndex.ts +++ b/packages/typespec-ts/src/modular/buildRootIndex.ts @@ -1,7 +1,6 @@ import { Project, SourceFile } from "ts-morph"; import { getClientName } from "./helpers/namingHelpers.js"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; -import { hasPagingOperation } from "./helpers/operationHelpers.js"; export function buildRootIndex( codeModel: ModularCodeModel, @@ -22,7 +21,6 @@ export function buildRootIndex( exportClassicalClient(client, rootIndexFile, subfolder); exportModels(rootIndexFile, project, srcPath, clientName, subfolder, true); - exportPagingUtil(codeModel, rootIndexFile, client); } function exportClassicalClient( @@ -73,25 +71,6 @@ function exportModels( }); } -function exportPagingUtil( - codeModel: ModularCodeModel, - indexFile: SourceFile, - client: Client -) { - // Only import the paging helper once - if (client !== codeModel.clients[0]) { - return; - } - const hasPaging = hasPagingOperation(codeModel); - if (!hasPaging) { - return; - } - indexFile.addExportDeclaration({ - moduleSpecifier: `./util/pagingUtil.js`, - namedExports: ["getContinuationToken", "setContinuationToken"] // Only export the getContinuationToken and setContinuationToken to public - }); -} - export function buildSubClientIndexFile( codeModel: ModularCodeModel, client: Client From 8df91b230d9e7b3f50181ed18cb055f4de277555 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 16:19:43 +0800 Subject: [PATCH 13/60] update the generated paging --- .../src/modular/buildClassicalClient.ts | 36 +++-- .../src/modular/buildOperations.ts | 7 +- .../src/modular/static/pagingUtil.ts | 6 +- .../test/commands/cadl-ranch-list.ts | 4 +- .../test/modularIntegration/azureCore.spec.ts | 20 ++- .../generated/azure/core/src/BasicClient.ts | 4 +- .../azure/core/src/api/operations.ts | 127 ++++++++++-------- .../generated/azure/core/src/index.ts | 4 - .../azure/core/src/util/pagingUtil.ts | 81 +++-------- .../payload/pageable/src/PageableClient.ts | 2 +- .../payload/pageable/src/api/operations.ts | 6 +- .../generated/payload/pageable/src/index.ts | 4 - .../payload/pageable/src/util/pagingUtil.ts | 122 +++++++++++------ .../test/modularIntegration/pageable.spec.ts | 20 ++- 14 files changed, 229 insertions(+), 214 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index 59a1eb1c15..8490c95db2 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -10,10 +10,7 @@ import { import { toCamelCase } from "../utils/casingUtils.js"; import { getClientParameters } from "./helpers/clientHelpers.js"; import { getClientName } from "./helpers/namingHelpers.js"; -import { - getOperationFunction, - hasPagingOperation -} from "./helpers/operationHelpers.js"; +import { getOperationFunction } from "./helpers/operationHelpers.js"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; import { getDocsFromDescription } from "./helpers/docsHelpers.js"; @@ -76,18 +73,33 @@ export function buildClassicalClient( importAllModels(clientFile, srcPath, subfolder); buildClientOperationGroups(client, clientClass, subfolder); importAllApis(clientFile, srcPath, subfolder); - if (hasPagingOperation(codeModel)) { - clientFile.addImportDeclarations([ - { - moduleSpecifier: "@azure/core-paging", - namedImports: ["PagedAsyncIterableIterator"] - } - ]); - } + importAllUtils(clientFile, srcPath, subfolder); clientFile.fixMissingImports(); clientFile.fixUnusedIdentifiers(); } +function importAllUtils( + clientFile: SourceFile, + srcPath: string, + subfolder: string +) { + const project = clientFile.getProject(); + const utils = project.getSourceFile( + `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}util/pagingUtil.ts` + ); + + if (!utils) { + return; + } + + const exported = [...utils.getExportedDeclarations().keys()]; + + clientFile.addImportDeclaration({ + moduleSpecifier: `./util/pagingUtil.js`, + namedImports: exported + }); +} + function importAllApis( clientFile: SourceFile, srcPath: string, diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index d051ec28bc..8f19efaaca 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -116,8 +116,11 @@ export function buildOperationFiles( if (hasPagingOperation(codeModel)) { operationGroupFile.addImportDeclarations([ { - moduleSpecifier: "@azure/core-paging", - namedImports: ["PagedAsyncIterableIterator"] + moduleSpecifier: "../util/pagingUtil.js", + namedImports: [ + "PagedAsyncIterableIterator", + "buildPagedAsyncIterator" + ] } ]); } diff --git a/packages/typespec-ts/src/modular/static/pagingUtil.ts b/packages/typespec-ts/src/modular/static/pagingUtil.ts index a750c4975b..b5058ac15e 100644 --- a/packages/typespec-ts/src/modular/static/pagingUtil.ts +++ b/packages/typespec-ts/src/modular/static/pagingUtil.ts @@ -141,13 +141,15 @@ async function* getPageAsyncIterator( if (!response) { return; } - yield { ...response.page, continuationToken: response.nextPageLink }; + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - yield { ...response.page, continuationToken: response.nextPageLink }; + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; } } diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index f9bc2b889a..c61c83f594 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -222,12 +222,14 @@ export const modularTsps: TypeSpecRanchConfig[] = [ }, { outputPath: "azure/core", - inputPath: "azure/core/basic" + inputPath: "azure/core/basic", + debug: true }, { outputPath: "payload/pageable", inputPath: "payload/pageable", debug: true + }, { outputPath: "encode/duration", inputPath: "encode/duration" diff --git a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts index bf1e0f6f35..19acd0bb03 100644 --- a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts @@ -10,7 +10,7 @@ describe("BasicClient Classical Client", () => { }); }); - describe.only("list", () => { + describe("list", () => { describe("next", () => { it("should list all users", async () => { const iter = client.list({ @@ -49,7 +49,7 @@ describe("BasicClient Classical Client", () => { const pagedItems = iter.byPage(); const items: User[] = []; for await (const page of pagedItems) { - items.push(...page.page); + items.push(...page); } assert.strictEqual(items.length, 2); assert.strictEqual(items[0]?.name, "Madge"); @@ -59,7 +59,7 @@ describe("BasicClient Classical Client", () => { ); }); - it("maxPageSize is not allowed and should throw exceptions", async () => { + it("maxPageSize param should be ignored", async () => { const iter = client.list({ top: 5, skip: 10, @@ -69,15 +69,11 @@ describe("BasicClient Classical Client", () => { expand: ["orders"], requestOptions: { skipUrlEncoding: true } }); - const pagedItems = iter.byPage({ maxPageSize: 10 } as any); + + const pagedIter = iter.byPage({ maxPageSize: 10 } as any); try { - const items: User[] = []; - for await (const user of pagedItems) { - items.push(...user.page); - } - assert.fail( - "`maxPageSize` is not allowed to customize and should throw exceptions" - ); + const items: User[] = (await pagedIter.next()).value; + assert.strictEqual(items.length, 2); } catch (err: any) { assert.strictEqual( err.message, @@ -94,7 +90,7 @@ describe("BasicClient Classical Client", () => { }); const items: User[] = []; for await (const user of pagedItems) { - items.push(...user.page); + items.push(...user); } assert.strictEqual(items.length, 2); assert.strictEqual(items[0]?.name, "Madge"); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts index c5427872d5..63566a9bff 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts @@ -10,7 +10,7 @@ import { ListWithPageOptions, ListWithCustomPageModelOptions, DeleteOptions, - ExportOptions + ExportOptions, } from "./models/options.js"; import { createBasic, @@ -23,7 +23,7 @@ import { listWithPage, listWithCustomPageModel, deleteOperation, - exportOperation + exportOperation, } from "./api/index.js"; import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 398160d5b2..876dddde3f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -23,12 +23,16 @@ import { ListWithCustomPageModel200Response, ListWithCustomPageModelDefaultResponse, ListWithPage200Response, - ListWithPageDefaultResponse + ListWithPageDefaultResponse, } from "../rest/index.js"; import { StreamableMethod, - operationOptionsToRequestParameters + operationOptionsToRequestParameters, } from "@azure-rest/core-client"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../util/pagingUtil.js"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, @@ -37,12 +41,8 @@ import { ListWithPageOptions, ListWithCustomPageModelOptions, DeleteOptions, - ExportOptions + ExportOptions, } from "../models/options.js"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator -} from "../util/pagingUtil.js"; export function _createOrUpdateSend( context: Client, @@ -54,17 +54,20 @@ export function _createOrUpdateSend( | CreateOrUpdate201Response | CreateOrUpdateDefaultResponse > { - return context.path("/azure/core/basic/users/{id}", id).patch({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "application/merge-patch+json", - body: { name: name, orders: options?.orders } + return context + .path("/azure/core/basic/users/{id}", id) + .patch({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/merge-patch+json", + body: { name: name, orders: (options?.orders ?? []).map((p) => ({ userId: p["userId"], detail: p["detail"], })), }, - }); + }); } export async function _createOrUpdateDeserialize( @@ -83,9 +86,9 @@ export async function _createOrUpdateDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: result.body["etag"] + etag: result.body["etag"], }; } @@ -110,16 +113,18 @@ export function _createOrReplaceSend( | CreateOrReplace201Response | CreateOrReplaceDefaultResponse > { - return context.path("/azure/core/basic/users/{id}", id).put({ - ...operationOptionsToRequestParameters(options), - body: { name: name, orders: options?.orders } + return context + .path("/azure/core/basic/users/{id}", id) + .put({ + ...operationOptionsToRequestParameters(options), + body: { name: name, orders: (options?.orders ?? []).map((p) => ({ userId: p["userId"], detail: p["detail"], })), }, - }); + }); } export async function _createOrReplaceDeserialize( @@ -138,9 +143,9 @@ export async function _createOrReplaceDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: result.body["etag"] + etag: result.body["etag"], }; } @@ -178,9 +183,9 @@ export async function _getDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: result.body["etag"] + etag: result.body["etag"], }; } @@ -198,27 +203,29 @@ export function _listSend( context: Client, options: ListOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/azure/core/basic/users").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - top: options?.top, - skip: options?.skip, - maxpagesize: options?.maxpagesize, - orderby: - options?.orderby !== undefined - ? buildMultiCollection(options?.orderby, "orderby") - : undefined, - filter: options?.filter, - select: - options?.select !== undefined - ? buildMultiCollection(options?.select, "select") - : undefined, - expand: - options?.expand !== undefined - ? buildMultiCollection(options?.expand, "expand") - : undefined - } - }); + return context + .path("/azure/core/basic/users") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + top: options?.top, + skip: options?.skip, + maxpagesize: options?.maxpagesize, + orderby: + options?.orderby !== undefined + ? buildMultiCollection(options?.orderby, "orderby") + : undefined, + filter: options?.filter, + select: + options?.select !== undefined + ? buildMultiCollection(options?.select, "select") + : undefined, + expand: + options?.expand !== undefined + ? buildMultiCollection(options?.expand, "expand") + : undefined, + }, + }); } export async function _listDeserialize( @@ -235,11 +242,11 @@ export async function _listDeserialize( orders: (p["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: p["etag"] + etag: p["etag"], })), - nextLink: result.body["nextLink"] + nextLink: result.body["nextLink"], }; } @@ -250,7 +257,7 @@ export function list( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator(context, _listSend, _listDeserialize, [ context, - options + options, ]); } @@ -277,11 +284,11 @@ export async function _listWithPageDeserialize( orders: (p["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: p["etag"] + etag: p["etag"], })), - nextLink: result.body["nextLink"] + nextLink: result.body["nextLink"], }; } @@ -325,11 +332,11 @@ export async function _listWithCustomPageModelDeserialize( orders: (p["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: p["etag"] + etag: p["etag"], })), - nextLink: result.body["nextLink"] + nextLink: result.body["nextLink"], }; } @@ -390,10 +397,12 @@ export function _exportOperationSend( ): StreamableMethod< ExportOperation200Response | ExportOperationDefaultResponse > { - return context.path("/azure/core/basic/users/{id}:export", id).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { format: format } - }); + return context + .path("/azure/core/basic/users/{id}:export", id) + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { format: format }, + }); } export async function _exportOperationDeserialize( @@ -409,9 +418,9 @@ export async function _exportOperationDeserialize( orders: (result.body["orders"] ?? []).map((p) => ({ id: p["id"], userId: p["userId"], - detail: p["detail"] + detail: p["detail"], })), - etag: result.body["etag"] + etag: result.body["etag"], }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts index bee953a15b..6521a8e214 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts @@ -16,7 +16,3 @@ export { DeleteOptions, ExportOptions, } from "./models/index.js"; -export { - getContinuationToken, - setContinuationToken, -} from "./util/pagingUtil.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts index 9b6dda0cbd..e7221e3e53 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts @@ -5,46 +5,13 @@ import { getPagedAsyncIterator, PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, PagedResult, - PageSettings as CorePageSettings + PageSettings as CorePageSettings, } from "@azure/core-paging"; import { Client, createRestError, - PathUncheckedResponse + PathUncheckedResponse, } from "@azure-rest/core-client"; - -export interface PageInfo { - continuationToken?: string; -} - -const pageMap = new WeakMap(); - -/** - * Given the last `.value` produced by the `byPage` iterator, - * returns a continuation token that can be used to begin paging from - * that point later. - * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. - * @returns The continuation token that can be passed into byPage() during future calls. - */ -export function getContinuationToken(page: unknown): string | undefined { - if (typeof page !== "object" || page === null) { - return undefined; - } - return pageMap.get(page)?.continuationToken; -} - -export function setContinuationToken( - page: unknown, - continuationToken: string | undefined -): void { - if (typeof page !== "object" || page === null || !continuationToken) { - return; - } - const pageInfo = pageMap.get(page) ?? {}; - pageInfo.continuationToken = continuationToken; - pageMap.set(page, pageInfo); -} - /** * Helper type to extract the type of an array */ @@ -74,17 +41,6 @@ export interface PageSettings { continuationToken?: string; } -export interface ContinuablePage { - /** - * Gets a list of elements in the page. - */ - page: TPage; - /** - * The token that keeps track of where to continue the iterator - */ - continuationToken?: TLink; -} - /** * An interface that allows async iterable iteration both to completion and by page. */ @@ -106,7 +62,7 @@ export interface PagedAsyncIterableIterator< */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator>; + ) => AsyncIterableIterator; } export function buildPagedAsyncIterator< @@ -138,18 +94,17 @@ export function buildPagedAsyncIterator< const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); - setContinuationToken(values, nextLink); return { page: values, - nextPageLink: nextLink + nextPageLink: nextLink, }; }, byPage: (settings?: PageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken + pageLink: continuationToken, }) as any; - } + }, }; const iter: CorePagedAsyncIterableIterator = getPagedAsyncIterator(pagedResult); @@ -164,17 +119,19 @@ export function buildPagedAsyncIterator< byPage: (settings?: PageSettings) => { return iter.byPage( settings as CorePageSettings - ) as unknown as AsyncIterableIterator>; - } + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + }, }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { - pageLink?: TLink; + pageLink?: string; } = {} -): AsyncIterableIterator> { +): AsyncIterableIterator { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -182,13 +139,15 @@ async function* getPageAsyncIterator( if (!response) { return; } - yield { page: response.page, continuationToken: response.nextPageLink }; + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - yield { page: response.page, continuationToken: response.nextPageLink }; + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; } } @@ -243,7 +202,7 @@ function checkPagingRequest(response: PathUncheckedResponse): void { "206", "207", "208", - "226" + "226", ]; if (!Http2xxStatusCodes.includes(response.status)) { throw createRestError( @@ -289,7 +248,7 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames + ...itemNames, ].join(" OR ")}` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts index 9628266714..9ea532f28f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts @@ -9,7 +9,7 @@ import { PageableClientOptions, PageableContext, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; export { PageableClientOptions } from "./api/PageableContext.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts index 7e082ec1ca..21713f06fc 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts @@ -7,9 +7,11 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../util/pagingUtil.js"; import { ListOptions } from "../models/options.js"; -import { buildPagedAsyncIterator } from "../util/pagingUtil.js"; export function _listSend( context: Client, diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts index c48416f4d3..61faa1ac7b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts @@ -3,7 +3,3 @@ export { PageableClient, PageableClientOptions } from "./PageableClient.js"; export { PagedUser, User, ListOptions } from "./models/index.js"; -export { - getContinuationToken, - setContinuationToken, -} from "./util/pagingUtil.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts index 163afff75d..e7221e3e53 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts @@ -3,47 +3,15 @@ import { getPagedAsyncIterator, - PagedAsyncIterableIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, PagedResult, + PageSettings as CorePageSettings, } from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; - -export interface PageInfo { - continuationToken?: string; -} - -const pageMap = new WeakMap(); - -/** - * Given the last `.value` produced by the `byPage` iterator, - * returns a continuation token that can be used to begin paging from - * that point later. - * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. - * @returns The continuation token that can be passed into byPage() during future calls. - */ -export function getContinuationToken(page: unknown): string | undefined { - if (typeof page !== "object" || page === null) { - return undefined; - } - return pageMap.get(page)?.continuationToken; -} - -export function setContinuationToken( - page: unknown, - continuationToken: string | undefined -): void { - if (typeof page !== "object" || page === null || !continuationToken) { - return; - } - const pageInfo = pageMap.get(page) ?? {}; - pageInfo.continuationToken = continuationToken; - pageMap.set(page, pageInfo); -} - /** * Helper type to extract the type of an array */ @@ -66,6 +34,37 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} + export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -80,10 +79,7 @@ export function buildPagedAsyncIterator< const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string, maxPageSize?: number) => { - if (maxPageSize) { - throw new Error("maxPageSize is not supported by this operation."); - } + getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder ? await initialSendFunction(...sendFunctionArgs) @@ -98,15 +94,61 @@ export function buildPagedAsyncIterator< const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); - setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink, }; }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }) as any; + }, }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); - return getPagedAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + }, + }; +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + } } /** diff --git a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts b/packages/typespec-ts/test/modularIntegration/pageable.spec.ts index 53dcac18b1..c289417986 100644 --- a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/pageable.spec.ts @@ -1,7 +1,6 @@ import { PageableClient, - User, - getContinuationToken + User } from "./generated/payload/pageable/src/index.js"; import { assert } from "chai"; @@ -70,7 +69,7 @@ describe("PageableClient Classical Client", () => { assert.strictEqual(firstPage.done, false); assert.strictEqual(firstPage.value.length, 3); // initiate another iterator starting with 2nd page - const continuationToken = getContinuationToken(firstPage.value); + const continuationToken = firstPage.value.continuationToken; const items: User[] = []; for await (const pagedUsers of iter.byPage({ continuationToken })) { items.push(...pagedUsers); @@ -78,16 +77,13 @@ describe("PageableClient Classical Client", () => { assert.strictEqual(items.length, 1); }); - it("maxPageSize is not allowed and should throw exceptions", async () => { - const pagedIter = client.list().byPage({ maxPageSize: 10 }); + it("maxPageSize param should be ignored", async () => { + const pagedIter = client + .list({ maxpagesize: 3 }) + .byPage({ maxPageSize: 10 } as any); try { - const items: User[] = []; - for await (const user of pagedIter) { - items.push(...user); - } - assert.fail( - "`maxPageSize` is not allowed to customize and should throw exceptions" - ); + const items: User[] = (await pagedIter.next()).value; + assert.strictEqual(items.length, 3); } catch (err: any) { assert.strictEqual( err.message, From a35c6003b4e9099866128da7cb7fb894bbaf283d Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 17:09:11 +0800 Subject: [PATCH 14/60] Generate the smoke testing --- .../review/ai-content-safety.api.md | 8 +- .../typespec-ts/src/ContentSafetyClient.ts | 2 +- .../typespec-ts/src/api/operations.ts | 6 +- .../generated/typespec-ts/src/index.ts | 4 - .../typespec-ts/src/util/pagingUtil.ts | 122 ++- .../typespec-ts/review/load-testing.api.md | 867 ------------------ .../generated/typespec-ts/src/index.ts | 4 - .../LoadTestAdministrationClient.ts | 2 +- .../loadTestAdministration/api/operations.ts | 6 +- .../src/loadTestRun/LoadTestRunClient.ts | 2 +- .../src/loadTestRun/api/operations.ts | 6 +- .../typespec-ts/src/util/pagingUtil.ts | 122 ++- 12 files changed, 180 insertions(+), 971 deletions(-) delete mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md 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 dbc1f63e35..be1b4f8c36 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 @@ -7,7 +7,6 @@ import { ClientOptions } from '@azure-rest/core-client'; import { KeyCredential } from '@azure/core-auth'; import { OperationOptions } from '@azure-rest/core-client'; -import { PagedAsyncIterableIterator } from '@azure/core-paging'; import { TokenCredential } from '@azure/core-auth'; // @public (undocumented) @@ -61,6 +60,7 @@ export class ContentSafetyClient { getTextBlocklist(blocklistName: string, options?: GetTextBlocklistOptions): Promise; getTextBlocklistItem(blocklistName: string, blockItemId: string, options?: GetTextBlocklistItemOptions): Promise; listTextBlocklistItems(blocklistName: string, options?: ListTextBlocklistItemsOptions): PagedAsyncIterableIterator; + // Warning: (ae-forgotten-export) The symbol "PagedAsyncIterableIterator" needs to be exported by the entry point index.d.ts listTextBlocklists(options?: ListTextBlocklistsOptions): PagedAsyncIterableIterator; removeBlockItems(blockItemIds: string[], blocklistName: string, options?: RemoveBlockItemsRequestOptions): Promise; } @@ -79,9 +79,6 @@ export interface CreateOrUpdateTextBlocklistOptions extends OperationOptions { export interface DeleteTextBlocklistOptions extends OperationOptions { } -// @public -export function getContinuationToken(page: unknown): string | undefined; - // @public (undocumented) export interface GetTextBlocklistItemOptions extends OperationOptions { } @@ -133,9 +130,6 @@ export interface PagedTextBlocklist { export interface RemoveBlockItemsRequestOptions extends OperationOptions { } -// @public (undocumented) -export function setContinuationToken(page: unknown, continuationToken: string | undefined): void; - // @public export interface TextAnalyzeSeverityResult { category: TextCategory; 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 36cecddc0c..d8c2f72c90 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 @@ -38,7 +38,7 @@ import { getTextBlocklistItem, listTextBlocklistItems, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; export { ContentSafetyClientOptions } from "./api/ContentSafetyContext.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 92d9ed02e1..d4d084f554 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 @@ -42,7 +42,10 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../util/pagingUtil.js"; import { AnalyzeTextRequestOptions, AnalyzeImageRequestOptions, @@ -55,7 +58,6 @@ import { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "../models/options.js"; -import { buildPagedAsyncIterator } from "../util/pagingUtil.js"; export function _analyzeTextSend( context: Client, 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 8c51c481b1..b88674e51a 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 @@ -33,7 +33,3 @@ export { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "./models/index.js"; -export { - getContinuationToken, - setContinuationToken, -} from "./util/pagingUtil.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts index 163afff75d..e7221e3e53 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts @@ -3,47 +3,15 @@ import { getPagedAsyncIterator, - PagedAsyncIterableIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, PagedResult, + PageSettings as CorePageSettings, } from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; - -export interface PageInfo { - continuationToken?: string; -} - -const pageMap = new WeakMap(); - -/** - * Given the last `.value` produced by the `byPage` iterator, - * returns a continuation token that can be used to begin paging from - * that point later. - * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. - * @returns The continuation token that can be passed into byPage() during future calls. - */ -export function getContinuationToken(page: unknown): string | undefined { - if (typeof page !== "object" || page === null) { - return undefined; - } - return pageMap.get(page)?.continuationToken; -} - -export function setContinuationToken( - page: unknown, - continuationToken: string | undefined -): void { - if (typeof page !== "object" || page === null || !continuationToken) { - return; - } - const pageInfo = pageMap.get(page) ?? {}; - pageInfo.continuationToken = continuationToken; - pageMap.set(page, pageInfo); -} - /** * Helper type to extract the type of an array */ @@ -66,6 +34,37 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} + export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -80,10 +79,7 @@ export function buildPagedAsyncIterator< const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string, maxPageSize?: number) => { - if (maxPageSize) { - throw new Error("maxPageSize is not supported by this operation."); - } + getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder ? await initialSendFunction(...sendFunctionArgs) @@ -98,15 +94,61 @@ export function buildPagedAsyncIterator< const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); - setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink, }; }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }) as any; + }, }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); - return getPagedAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + }, + }; +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + } } /** 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 deleted file mode 100644 index 8902add426..0000000000 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md +++ /dev/null @@ -1,867 +0,0 @@ -## API Report File for "@azure/load-testing" - -> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). - -```ts - -import { ClientOptions } from '@azure-rest/core-client'; -import { OperationOptions } from '@azure-rest/core-client'; -import { PagedAsyncIterableIterator } from '@azure/core-paging'; -import { TokenCredential } from '@azure/core-auth'; - -// @public -export type AggregationType = string; - -// @public -export interface AppComponent { - displayName?: string; - kind?: string; - readonly resourceGroup?: string; - readonly resourceId?: string; - resourceName?: string; - resourceType?: string; - readonly subscriptionId?: string; -} - -// @public -export interface CertificateMetadata { - name?: string; - type?: CertificateType; - value?: string; -} - -// @public -export type CertificateType = string; - -// @public (undocumented) -export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { - // (undocumented) - contentType?: string; - createdBy?: string; - createdDateTime?: Date; - lastModifiedBy?: string; - lastModifiedDateTime?: Date; - testId?: string; -} - -// @public (undocumented) -export interface CreateOrUpdateServerMetricsConfigOptions extends OperationOptions { - // (undocumented) - contentType?: string; - createdBy?: string; - createdDateTime?: Date; - lastModifiedBy?: string; - lastModifiedDateTime?: Date; - metrics?: Record; - testId?: string; -} - -// @public (undocumented) -export interface CreateOrUpdateTestOptions extends OperationOptions { - certificate?: CertificateMetadata; - // (undocumented) - contentType?: string; - createdBy?: string; - createdDateTime?: Date; - description?: string; - displayName?: string; - environmentVariables?: Record; - inputArtifacts?: TestInputArtifacts; - keyvaultReferenceIdentityId?: string; - keyvaultReferenceIdentityType?: string; - lastModifiedBy?: string; - lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestConfiguration; - passFailCriteria?: PassFailCriteria; - secrets?: Record; - subnetId?: string; - testId?: string; -} - -// @public (undocumented) -export interface DeleteTestFileOptions extends OperationOptions { -} - -// @public (undocumented) -export interface DeleteTestOptions extends OperationOptions { -} - -// @public (undocumented) -export interface DeleteTestRunOptions extends OperationOptions { -} - -// @public -export interface DimensionFilter { - name?: string; - values?: string[]; -} - -// @public -export interface DimensionValue { - name?: string; - value?: string; -} - -// @public (undocumented) -export interface DimensionValueList { - // (undocumented) - readonly value: string[]; -} - -// @public -export interface ErrorDetails { - readonly message?: string; -} - -// @public -export interface FileInfo { - expireDateTime?: Date; - fileName?: string; - fileType?: FileType; - url?: string; - validationFailureDetails?: string; - validationStatus?: FileStatus; -} - -// @public -export type FileStatus = string; - -// @public -export type FileType = string; - -// @public (undocumented) -export interface GetAppComponentsOptions extends OperationOptions { -} - -// @public -export function getContinuationToken(page: unknown): string | undefined; - -// @public (undocumented) -export interface GetServerMetricsConfigOptions extends OperationOptions { -} - -// @public (undocumented) -export interface GetTestFileOptions extends OperationOptions { -} - -// @public (undocumented) -export interface GetTestOptions extends OperationOptions { -} - -// @public (undocumented) -export interface GetTestRunFileOptions extends OperationOptions { -} - -// @public (undocumented) -export interface GetTestRunOptions extends OperationOptions { -} - -// @public -export type Interval = string; - -// @public (undocumented) -export interface ListMetricDefinitionsOptions extends OperationOptions { - metricNamespace?: string; -} - -// @public (undocumented) -export interface ListMetricDimensionValuesOptions extends OperationOptions { - interval?: LoadTestRunClientInterval; - metricName?: string; - timespan?: string; -} - -// @public (undocumented) -export interface ListMetricNamespacesOptions extends OperationOptions { -} - -// @public (undocumented) -export interface ListMetricsOptions extends OperationOptions { - aggregation?: string; - filters?: LoadTestRunClientDimensionFilter[]; - interval?: LoadTestRunClientInterval; - metricName?: string; - metricNamespace?: string; - timespan?: string; -} - -// @public (undocumented) -export interface ListTestFilesOptions extends OperationOptions { -} - -// @public (undocumented) -export interface ListTestRunsOptions extends OperationOptions { - executionFrom?: Date; - executionTo?: Date; - maxpagesize?: number; - orderby?: string; - search?: string; - status?: string; - testId?: string; -} - -// @public (undocumented) -export interface ListTestsOptions extends OperationOptions { - lastModifiedEndTime?: Date; - lastModifiedStartTime?: Date; - maxpagesize?: number; - orderby?: string; - search?: string; -} - -// @public (undocumented) -export class LoadTestAdministrationClient { - constructor(endpoint: string, credential: TokenCredential, options?: LoadTestAdministrationClientOptions); - createOrUpdateAppComponents(components: Record, testId: string, options?: CreateOrUpdateAppComponentsOptions): Promise; - createOrUpdateServerMetricsConfig(testId: string, options?: CreateOrUpdateServerMetricsConfigOptions): Promise; - createOrUpdateTest(testId: string, options?: CreateOrUpdateTestOptions): Promise; - deleteTest(testId: string, options?: DeleteTestOptions): Promise; - deleteTestFile(testId: string, fileName: string, options?: DeleteTestFileOptions): Promise; - getAppComponents(testId: string, options?: GetAppComponentsOptions): Promise; - getServerMetricsConfig(testId: string, options?: GetServerMetricsConfigOptions): Promise; - getTest(testId: string, options?: GetTestOptions): Promise; - getTestFile(testId: string, fileName: string, options?: GetTestFileOptions): Promise; - listTestFiles(testId: string, options?: ListTestFilesOptions): PagedAsyncIterableIterator; - listTests(options?: ListTestsOptions): PagedAsyncIterableIterator; - uploadTestFile(body: Uint8Array, testId: string, fileName: string, options?: UploadTestFileOptions): Promise; -} - -// @public (undocumented) -export interface LoadTestAdministrationClientOptions extends ClientOptions { -} - -// @public -export interface LoadTestConfiguration { - engineInstances?: number; - optionalLoadTestConfig?: OptionalLoadTestConfig; - quickStartTest?: boolean; - splitAllCSVs?: boolean; -} - -// @public (undocumented) -export class LoadTestRunClient { - constructor(endpoint: string, credential: TokenCredential, options?: LoadTestRunClientOptions); - // Warning: (ae-forgotten-export) The symbol "TestRunAppComponents" needs to be exported by the entry point index.d.ts - createOrUpdateAppComponents(components: Record, testRunId: string, options?: LoadTestRunClientCreateOrUpdateAppComponentsOptions): Promise; - // Warning: (ae-forgotten-export) The symbol "TestRunServerMetricConfig" needs to be exported by the entry point index.d.ts - createOrUpdateServerMetricsConfig(testRunId: string, options?: LoadTestRunClientCreateOrUpdateServerMetricsConfigOptions): Promise; - deleteTestRun(testRunId: string, options?: DeleteTestRunOptions): Promise; - getAppComponents(testRunId: string, options?: LoadTestRunClientGetAppComponentsOptions): Promise; - getServerMetricsConfig(testRunId: string, options?: LoadTestRunClientGetServerMetricsConfigOptions): Promise; - getTestRun(testRunId: string, options?: GetTestRunOptions): Promise; - getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptions): Promise; - // Warning: (ae-forgotten-export) The symbol "MetricDefinitionCollection" needs to be exported by the entry point index.d.ts - listMetricDefinitions(testRunId: string, options?: ListMetricDefinitionsOptions): Promise; - listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptions): PagedAsyncIterableIterator; - // Warning: (ae-forgotten-export) The symbol "MetricNamespaceCollection" needs to be exported by the entry point index.d.ts - listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptions): Promise; - listMetrics(testRunId: string, options?: ListMetricsOptions): PagedAsyncIterableIterator; - listTestRuns(options?: ListTestRunsOptions): PagedAsyncIterableIterator; - stopTestRun(testRunId: string, options?: StopTestRunOptions): Promise; - testRun(testRunId: string, options?: TestRunOptions): Promise; -} - -// @public -export type LoadTestRunClientAggregationType = string; - -// @public -export interface LoadTestRunClientAppComponent { - displayName?: string; - kind?: string; - readonly resourceGroup?: string; - readonly resourceId?: string; - resourceName?: string; - resourceType?: string; - readonly subscriptionId?: string; -} - -// @public -export interface LoadTestRunClientCertificateMetadata { - name?: string; - type?: LoadTestRunClientCertificateType; - value?: string; -} - -// @public -export type LoadTestRunClientCertificateType = string; - -// @public (undocumented) -export interface LoadTestRunClientCreateOrUpdateAppComponentsOptions extends OperationOptions { - // (undocumented) - contentType?: string; - createdBy?: string; - createdDateTime?: Date; - lastModifiedBy?: string; - lastModifiedDateTime?: Date; - testRunId?: string; -} - -// @public (undocumented) -export interface LoadTestRunClientCreateOrUpdateServerMetricsConfigOptions extends OperationOptions { - // (undocumented) - contentType?: string; - createdBy?: string; - createdDateTime?: Date; - lastModifiedBy?: string; - lastModifiedDateTime?: Date; - metrics?: Record; - testRunId?: string; -} - -// @public -export interface LoadTestRunClientDimensionFilter { - name?: string; - values?: string[]; -} - -// @public -export interface LoadTestRunClientDimensionValue { - name?: string; - value?: string; -} - -// @public (undocumented) -export interface LoadTestRunClientDimensionValueList { - // (undocumented) - readonly value: string[]; -} - -// @public -export interface LoadTestRunClientErrorDetails { - readonly message?: string; -} - -// @public -export interface LoadTestRunClientFileInfo { - expireDateTime?: Date; - fileName?: string; - fileType?: LoadTestRunClientFileType; - url?: string; - validationFailureDetails?: string; - validationStatus?: LoadTestRunClientFileStatus; -} - -// @public -export type LoadTestRunClientFileStatus = string; - -// @public -export type LoadTestRunClientFileType = string; - -// @public (undocumented) -export interface LoadTestRunClientGetAppComponentsOptions extends OperationOptions { -} - -// @public (undocumented) -export interface LoadTestRunClientGetServerMetricsConfigOptions extends OperationOptions { -} - -// @public -export type LoadTestRunClientInterval = string; - -// @public -export interface LoadTestRunClientLoadTestConfiguration { - engineInstances?: number; - optionalLoadTestConfig?: LoadTestRunClientOptionalLoadTestConfig; - quickStartTest?: boolean; - splitAllCSVs?: boolean; -} - -// @public -export interface LoadTestRunClientMetricAvailability { - timeGrain?: LoadTestRunClientTimeGrain; -} - -// @public -export interface LoadTestRunClientMetricDefinition { - description?: string; - dimensions?: LoadTestRunClientNameAndDesc[]; - metricAvailabilities?: LoadTestRunClientMetricAvailability[]; - name?: string; - namespace?: string; - primaryAggregationType?: LoadTestRunClientAggregationType; - supportedAggregationTypes?: string[]; - unit?: LoadTestRunClientMetricUnit; -} - -// @public -export interface LoadTestRunClientMetricNamespace { - description?: string; - name?: string; -} - -// @public -export type LoadTestRunClientMetricUnit = string; - -// @public -export interface LoadTestRunClientMetricValue { - timestamp?: string; - value?: number; -} - -// @public -export interface LoadTestRunClientNameAndDesc { - description?: string; - name?: string; -} - -// @public -export interface LoadTestRunClientOptionalLoadTestConfig { - duration?: number; - endpointUrl?: string; - rampUpTime?: number; - virtualUsers?: number; -} - -// @public (undocumented) -export interface LoadTestRunClientOptions extends ClientOptions { -} - -// @public -export interface LoadTestRunClientPassFailCriteria { - passFailMetrics?: Record; -} - -// @public -export interface LoadTestRunClientPassFailMetric { - action?: LoadTestRunClientPFAction; - readonly actualValue?: number; - aggregate?: LoadTestRunClientPFAgFunc; - clientMetric?: LoadTestRunClientPFMetrics; - condition?: string; - requestName?: string; - readonly result?: LoadTestRunClientPFResult; - value?: number; -} - -// @public -export type LoadTestRunClientPFAction = string; - -// @public -export type LoadTestRunClientPFAgFunc = string; - -// @public -export type LoadTestRunClientPFMetrics = string; - -// @public -export type LoadTestRunClientPFResult = string; - -// @public -export type LoadTestRunClientPFTestResult = string; - -// @public -export interface LoadTestRunClientResourceMetric { - aggregation: string; - displayDescription?: string; - readonly id?: string; - metricNamespace: string; - name: string; - resourceId: string; - resourceType: string; - unit?: string; -} - -// @public -export interface LoadTestRunClientSecret { - type?: LoadTestRunClientSecretType; - value?: string; -} - -// @public -export type LoadTestRunClientSecretType = string; - -// @public -export type LoadTestRunClientStatus = string; - -// @public -export interface LoadTestRunClientTest { - certificate?: LoadTestRunClientCertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - environmentVariables?: Record; - readonly inputArtifacts?: LoadTestRunClientTestInputArtifacts; - keyvaultReferenceIdentityId?: string; - keyvaultReferenceIdentityType?: string; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; - passFailCriteria?: LoadTestRunClientPassFailCriteria; - secrets?: Record; - subnetId?: string; - readonly testId?: string; -} - -// @public -export interface LoadTestRunClientTestInputArtifacts { - readonly additionalFileInfo?: LoadTestRunClientFileInfo[]; - configFileInfo?: LoadTestRunClientFileInfo; - inputArtifactsZipFileInfo?: LoadTestRunClientFileInfo; - testScriptFileInfo?: LoadTestRunClientFileInfo; - userPropFileInfo?: LoadTestRunClientFileInfo; -} - -// @public -export interface LoadTestRunClientTestRun { - certificate?: LoadTestRunClientCertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly duration?: number; - readonly endDateTime?: Date; - environmentVariables?: Record; - readonly errorDetails?: LoadTestRunClientErrorDetails[]; - readonly executedDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; - passFailCriteria?: LoadTestRunClientPassFailCriteria; - readonly portalUrl?: string; - secrets?: Record; - readonly startDateTime?: Date; - readonly status?: LoadTestRunClientStatus; - readonly subnetId?: string; - readonly testArtifacts?: LoadTestRunClientTestRunArtifacts; - testId?: string; - readonly testResult?: LoadTestRunClientPFTestResult; - readonly testRunId: string; - readonly testRunStatistics?: Record; - readonly virtualUsers?: number; -} - -// @public -export interface LoadTestRunClientTestRunArtifacts { - readonly inputArtifacts?: LoadTestRunClientTestRunInputArtifacts; - outputArtifacts?: LoadTestRunClientTestRunOutputArtifacts; -} - -// @public -export interface LoadTestRunClientTestRunInputArtifacts { - readonly additionalFileInfo?: LoadTestRunClientFileInfo[]; - configFileInfo?: LoadTestRunClientFileInfo; - inputArtifactsZipFileInfo?: LoadTestRunClientFileInfo; - testScriptFileInfo?: LoadTestRunClientFileInfo; - userPropFileInfo?: LoadTestRunClientFileInfo; -} - -// @public -export interface LoadTestRunClientTestRunOutputArtifacts { - logsFileInfo?: LoadTestRunClientFileInfo; - resultFileInfo?: LoadTestRunClientFileInfo; -} - -// @public -export interface LoadTestRunClientTestRunStatistics { - readonly errorCount?: number; - readonly errorPct?: number; - readonly maxResTime?: number; - readonly meanResTime?: number; - readonly medianResTime?: number; - readonly minResTime?: number; - readonly pct1ResTime?: number; - readonly pct2ResTime?: number; - readonly pct3ResTime?: number; - readonly receivedKBytesPerSec?: number; - readonly sampleCount?: number; - readonly sentKBytesPerSec?: number; - readonly throughput?: number; - readonly transaction?: string; -} - -// @public -export type LoadTestRunClientTimeGrain = string; - -// @public -export interface LoadTestRunClientTimeSeriesElement { - data?: LoadTestRunClientMetricValue[]; - dimensionValues?: LoadTestRunClientDimensionValue[]; -} - -// @public -export interface MetricAvailability { - timeGrain?: TimeGrain; -} - -// @public -export interface MetricDefinition { - description?: string; - dimensions?: NameAndDesc[]; - metricAvailabilities?: MetricAvailability[]; - name?: string; - namespace?: string; - primaryAggregationType?: AggregationType; - supportedAggregationTypes?: string[]; - unit?: MetricUnit; -} - -// @public -export interface MetricNamespace { - description?: string; - name?: string; -} - -// @public -export type MetricUnit = string; - -// @public -export interface MetricValue { - timestamp?: string; - value?: number; -} - -// @public -export interface NameAndDesc { - description?: string; - name?: string; -} - -// @public -export interface OptionalLoadTestConfig { - duration?: number; - endpointUrl?: string; - rampUpTime?: number; - virtualUsers?: number; -} - -// @public -export interface PagedFileInfo { - nextLink?: string; - value: FileInfo[]; -} - -// @public -export interface PagedTest { - nextLink?: string; - value: Test[]; -} - -// @public -export interface PassFailCriteria { - passFailMetrics?: Record; -} - -// @public -export interface PassFailMetric { - action?: PFAction; - readonly actualValue?: number; - aggregate?: PFAgFunc; - clientMetric?: PFMetrics; - condition?: string; - requestName?: string; - readonly result?: PFResult; - value?: number; -} - -// @public -export type PFAction = string; - -// @public -export type PFAgFunc = string; - -// @public -export type PFMetrics = string; - -// @public -export type PFResult = string; - -// @public -export type PFTestResult = string; - -// @public -export interface ResourceMetric { - aggregation: string; - displayDescription?: string; - readonly id?: string; - metricNamespace: string; - name: string; - resourceId: string; - resourceType: string; - unit?: string; -} - -// @public -export interface Secret { - type?: SecretType; - value?: string; -} - -// @public -export type SecretType = string; - -// @public (undocumented) -export function setContinuationToken(page: unknown, continuationToken: string | undefined): void; - -// @public -export type Status = string; - -// @public (undocumented) -export interface StopTestRunOptions extends OperationOptions { -} - -// @public -export interface Test { - certificate?: CertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - environmentVariables?: Record; - readonly inputArtifacts?: TestInputArtifacts; - keyvaultReferenceIdentityId?: string; - keyvaultReferenceIdentityType?: string; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestConfiguration; - passFailCriteria?: PassFailCriteria; - secrets?: Record; - subnetId?: string; - readonly testId?: string; -} - -// @public -export interface TestAppComponents { - components: Record; - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - readonly testId?: string; -} - -// @public -export interface TestInputArtifacts { - readonly additionalFileInfo?: FileInfo[]; - configFileInfo?: FileInfo; - inputArtifactsZipFileInfo?: FileInfo; - testScriptFileInfo?: FileInfo; - userPropFileInfo?: FileInfo; -} - -// @public -export interface TestRun { - certificate?: CertificateMetadata; - readonly createdBy?: string; - readonly createdDateTime?: Date; - description?: string; - displayName?: string; - readonly duration?: number; - readonly endDateTime?: Date; - environmentVariables?: Record; - readonly errorDetails?: ErrorDetails[]; - readonly executedDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestConfiguration; - passFailCriteria?: PassFailCriteria; - readonly portalUrl?: string; - secrets?: Record; - readonly startDateTime?: Date; - readonly status?: Status; - readonly subnetId?: string; - readonly testArtifacts?: TestRunArtifacts; - testId?: string; - readonly testResult?: PFTestResult; - readonly testRunId: string; - readonly testRunStatistics?: Record; - readonly virtualUsers?: number; -} - -// @public -export interface TestRunArtifacts { - readonly inputArtifacts?: TestRunInputArtifacts; - outputArtifacts?: TestRunOutputArtifacts; -} - -// @public -export interface TestRunInputArtifacts { - readonly additionalFileInfo?: FileInfo[]; - configFileInfo?: FileInfo; - inputArtifactsZipFileInfo?: FileInfo; - testScriptFileInfo?: FileInfo; - userPropFileInfo?: FileInfo; -} - -// @public (undocumented) -export interface TestRunOptions extends OperationOptions { - certificate?: LoadTestRunClientCertificateMetadata; - contentType?: string; - createdBy?: string; - createdDateTime?: Date; - description?: string; - displayName?: string; - duration?: number; - endDateTime?: Date; - environmentVariables?: Record; - errorDetails?: LoadTestRunClientErrorDetails[]; - executedDateTime?: Date; - lastModifiedBy?: string; - lastModifiedDateTime?: Date; - loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; - oldTestRunId?: string; - passFailCriteria?: LoadTestRunClientPassFailCriteria; - portalUrl?: string; - secrets?: Record; - startDateTime?: Date; - status?: LoadTestRunClientStatus; - subnetId?: string; - testArtifacts?: LoadTestRunClientTestRunArtifacts; - testId?: string; - testResult?: LoadTestRunClientPFTestResult; - testRunStatistics?: Record; - virtualUsers?: number; -} - -// @public -export interface TestRunOutputArtifacts { - logsFileInfo?: FileInfo; - resultFileInfo?: FileInfo; -} - -// @public -export interface TestRunStatistics { - readonly errorCount?: number; - readonly errorPct?: number; - readonly maxResTime?: number; - readonly meanResTime?: number; - readonly medianResTime?: number; - readonly minResTime?: number; - readonly pct1ResTime?: number; - readonly pct2ResTime?: number; - readonly pct3ResTime?: number; - readonly receivedKBytesPerSec?: number; - readonly sampleCount?: number; - readonly sentKBytesPerSec?: number; - readonly throughput?: number; - readonly transaction?: string; -} - -// @public -export interface TestServerMetricConfig { - readonly createdBy?: string; - readonly createdDateTime?: Date; - readonly lastModifiedBy?: string; - readonly lastModifiedDateTime?: Date; - metrics?: Record; - readonly testId?: string; -} - -// @public -export type TimeGrain = string; - -// @public -export interface TimeSeriesElement { - data?: MetricValue[]; - dimensionValues?: DimensionValue[]; -} - -// @public (undocumented) -export interface UploadTestFileOptions extends OperationOptions { - // (undocumented) - contentType?: string; - fileType?: FileType; -} - -// (No @packageDocumentation comment for this package) - -``` 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 46ba67b2f8..cd91d5d41b 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 @@ -63,10 +63,6 @@ export { DeleteTestFileOptions, DeleteTestOptions, } from "./loadTestAdministration/models/index.js"; -export { - getContinuationToken, - setContinuationToken, -} from "./util/pagingUtil.js"; export { LoadTestRunClient, LoadTestRunClientOptions, 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 0287705b5f..7009d96ba6 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 @@ -40,7 +40,7 @@ import { deleteTestFile, deleteTest, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { PagedAsyncIterableIterator } from "../util/pagingUtil.js"; export { LoadTestAdministrationClientOptions } from "./api/LoadTestAdministrationContext.js"; 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 28812fbff8..f176647209 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 @@ -45,8 +45,10 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; -import { buildPagedAsyncIterator } from "../../util/pagingUtil.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../util/pagingUtil.js"; import { CreateOrUpdateTestOptions, CreateOrUpdateAppComponentsOptions, 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 e6f48fe62d..bb8eca6430 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 @@ -48,7 +48,7 @@ import { listTestRuns, stopTestRun, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { PagedAsyncIterableIterator } from "../util/pagingUtil.js"; export { LoadTestRunClientOptions } from "./api/LoadTestRunContext.js"; 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 30c708a476..c6d0f1f240 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 @@ -55,8 +55,10 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; -import { buildPagedAsyncIterator } from "../../util/pagingUtil.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../util/pagingUtil.js"; import { TestRunOptions, CreateOrUpdateAppComponentsOptions, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts index 163afff75d..e7221e3e53 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts @@ -3,47 +3,15 @@ import { getPagedAsyncIterator, - PagedAsyncIterableIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, PagedResult, + PageSettings as CorePageSettings, } from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; - -export interface PageInfo { - continuationToken?: string; -} - -const pageMap = new WeakMap(); - -/** - * Given the last `.value` produced by the `byPage` iterator, - * returns a continuation token that can be used to begin paging from - * that point later. - * @param page An object from accessing `value` on the IteratorResult from a `byPage` iterator. - * @returns The continuation token that can be passed into byPage() during future calls. - */ -export function getContinuationToken(page: unknown): string | undefined { - if (typeof page !== "object" || page === null) { - return undefined; - } - return pageMap.get(page)?.continuationToken; -} - -export function setContinuationToken( - page: unknown, - continuationToken: string | undefined -): void { - if (typeof page !== "object" || page === null || !continuationToken) { - return; - } - const pageInfo = pageMap.get(page) ?? {}; - pageInfo.continuationToken = continuationToken; - pageMap.set(page, pageInfo); -} - /** * Helper type to extract the type of an array */ @@ -66,6 +34,37 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} + export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -80,10 +79,7 @@ export function buildPagedAsyncIterator< const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string, maxPageSize?: number) => { - if (maxPageSize) { - throw new Error("maxPageSize is not supported by this operation."); - } + getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder ? await initialSendFunction(...sendFunctionArgs) @@ -98,15 +94,61 @@ export function buildPagedAsyncIterator< const results = await deserializeFunction(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); - setContinuationToken(values, nextLink); return { page: values, nextPageLink: nextLink, }; }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }) as any; + }, }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); - return getPagedAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + }, + }; +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + } } /** From be9beb8dab1cf39f86261eb37443a971f84c6e49 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 18:45:44 +0800 Subject: [PATCH 15/60] Fix the load testing issues --- .../typespec-ts/review/load-testing.api.md | 861 ++++++++++++++++++ .../loadTestAdministration/api/operations.ts | 2 +- .../src/loadTestRun/api/operations.ts | 2 +- .../src/modular/buildClassicalClient.ts | 6 +- .../src/modular/buildOperations.ts | 4 +- 5 files changed, 868 insertions(+), 7 deletions(-) create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md 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 new file mode 100644 index 0000000000..8e5b2d42af --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/review/load-testing.api.md @@ -0,0 +1,861 @@ +## API Report File for "@azure/load-testing" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +import { ClientOptions } from '@azure-rest/core-client'; +import { OperationOptions } from '@azure-rest/core-client'; +import { TokenCredential } from '@azure/core-auth'; + +// @public +export type AggregationType = string; + +// @public +export interface AppComponent { + displayName?: string; + kind?: string; + readonly resourceGroup?: string; + readonly resourceId?: string; + resourceName?: string; + resourceType?: string; + readonly subscriptionId?: string; +} + +// @public +export interface CertificateMetadata { + name?: string; + type?: CertificateType; + value?: string; +} + +// @public +export type CertificateType = string; + +// @public (undocumented) +export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { + // (undocumented) + contentType?: string; + createdBy?: string; + createdDateTime?: Date; + lastModifiedBy?: string; + lastModifiedDateTime?: Date; + testId?: string; +} + +// @public (undocumented) +export interface CreateOrUpdateServerMetricsConfigOptions extends OperationOptions { + // (undocumented) + contentType?: string; + createdBy?: string; + createdDateTime?: Date; + lastModifiedBy?: string; + lastModifiedDateTime?: Date; + metrics?: Record; + testId?: string; +} + +// @public (undocumented) +export interface CreateOrUpdateTestOptions extends OperationOptions { + certificate?: CertificateMetadata; + // (undocumented) + contentType?: string; + createdBy?: string; + createdDateTime?: Date; + description?: string; + displayName?: string; + environmentVariables?: Record; + inputArtifacts?: TestInputArtifacts; + keyvaultReferenceIdentityId?: string; + keyvaultReferenceIdentityType?: string; + lastModifiedBy?: string; + lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestConfiguration; + passFailCriteria?: PassFailCriteria; + secrets?: Record; + subnetId?: string; + testId?: string; +} + +// @public (undocumented) +export interface DeleteTestFileOptions extends OperationOptions { +} + +// @public (undocumented) +export interface DeleteTestOptions extends OperationOptions { +} + +// @public (undocumented) +export interface DeleteTestRunOptions extends OperationOptions { +} + +// @public +export interface DimensionFilter { + name?: string; + values?: string[]; +} + +// @public +export interface DimensionValue { + name?: string; + value?: string; +} + +// @public (undocumented) +export interface DimensionValueList { + // (undocumented) + readonly value: string[]; +} + +// @public +export interface ErrorDetails { + readonly message?: string; +} + +// @public +export interface FileInfo { + expireDateTime?: Date; + fileName?: string; + fileType?: FileType; + url?: string; + validationFailureDetails?: string; + validationStatus?: FileStatus; +} + +// @public +export type FileStatus = string; + +// @public +export type FileType = string; + +// @public (undocumented) +export interface GetAppComponentsOptions extends OperationOptions { +} + +// @public (undocumented) +export interface GetServerMetricsConfigOptions extends OperationOptions { +} + +// @public (undocumented) +export interface GetTestFileOptions extends OperationOptions { +} + +// @public (undocumented) +export interface GetTestOptions extends OperationOptions { +} + +// @public (undocumented) +export interface GetTestRunFileOptions extends OperationOptions { +} + +// @public (undocumented) +export interface GetTestRunOptions extends OperationOptions { +} + +// @public +export type Interval = string; + +// @public (undocumented) +export interface ListMetricDefinitionsOptions extends OperationOptions { + metricNamespace?: string; +} + +// @public (undocumented) +export interface ListMetricDimensionValuesOptions extends OperationOptions { + interval?: LoadTestRunClientInterval; + metricName?: string; + timespan?: string; +} + +// @public (undocumented) +export interface ListMetricNamespacesOptions extends OperationOptions { +} + +// @public (undocumented) +export interface ListMetricsOptions extends OperationOptions { + aggregation?: string; + filters?: LoadTestRunClientDimensionFilter[]; + interval?: LoadTestRunClientInterval; + metricName?: string; + metricNamespace?: string; + timespan?: string; +} + +// @public (undocumented) +export interface ListTestFilesOptions extends OperationOptions { +} + +// @public (undocumented) +export interface ListTestRunsOptions extends OperationOptions { + executionFrom?: Date; + executionTo?: Date; + maxpagesize?: number; + orderby?: string; + search?: string; + status?: string; + testId?: string; +} + +// @public (undocumented) +export interface ListTestsOptions extends OperationOptions { + lastModifiedEndTime?: Date; + lastModifiedStartTime?: Date; + maxpagesize?: number; + orderby?: string; + search?: string; +} + +// @public (undocumented) +export class LoadTestAdministrationClient { + constructor(endpoint: string, credential: TokenCredential, options?: LoadTestAdministrationClientOptions); + createOrUpdateAppComponents(components: Record, testId: string, options?: CreateOrUpdateAppComponentsOptions): Promise; + createOrUpdateServerMetricsConfig(testId: string, options?: CreateOrUpdateServerMetricsConfigOptions): Promise; + createOrUpdateTest(testId: string, options?: CreateOrUpdateTestOptions): Promise; + deleteTest(testId: string, options?: DeleteTestOptions): Promise; + deleteTestFile(testId: string, fileName: string, options?: DeleteTestFileOptions): Promise; + getAppComponents(testId: string, options?: GetAppComponentsOptions): Promise; + getServerMetricsConfig(testId: string, options?: GetServerMetricsConfigOptions): Promise; + getTest(testId: string, options?: GetTestOptions): Promise; + getTestFile(testId: string, fileName: string, options?: GetTestFileOptions): Promise; + // Warning: (ae-forgotten-export) The symbol "PagedAsyncIterableIterator" needs to be exported by the entry point index.d.ts + listTestFiles(testId: string, options?: ListTestFilesOptions): PagedAsyncIterableIterator; + listTests(options?: ListTestsOptions): PagedAsyncIterableIterator; + uploadTestFile(body: Uint8Array, testId: string, fileName: string, options?: UploadTestFileOptions): Promise; +} + +// @public (undocumented) +export interface LoadTestAdministrationClientOptions extends ClientOptions { +} + +// @public +export interface LoadTestConfiguration { + engineInstances?: number; + optionalLoadTestConfig?: OptionalLoadTestConfig; + quickStartTest?: boolean; + splitAllCSVs?: boolean; +} + +// @public (undocumented) +export class LoadTestRunClient { + constructor(endpoint: string, credential: TokenCredential, options?: LoadTestRunClientOptions); + // Warning: (ae-forgotten-export) The symbol "TestRunAppComponents" needs to be exported by the entry point index.d.ts + createOrUpdateAppComponents(components: Record, testRunId: string, options?: LoadTestRunClientCreateOrUpdateAppComponentsOptions): Promise; + // Warning: (ae-forgotten-export) The symbol "TestRunServerMetricConfig" needs to be exported by the entry point index.d.ts + createOrUpdateServerMetricsConfig(testRunId: string, options?: LoadTestRunClientCreateOrUpdateServerMetricsConfigOptions): Promise; + deleteTestRun(testRunId: string, options?: DeleteTestRunOptions): Promise; + getAppComponents(testRunId: string, options?: LoadTestRunClientGetAppComponentsOptions): Promise; + getServerMetricsConfig(testRunId: string, options?: LoadTestRunClientGetServerMetricsConfigOptions): Promise; + getTestRun(testRunId: string, options?: GetTestRunOptions): Promise; + getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptions): Promise; + // Warning: (ae-forgotten-export) The symbol "MetricDefinitionCollection" needs to be exported by the entry point index.d.ts + listMetricDefinitions(testRunId: string, options?: ListMetricDefinitionsOptions): Promise; + listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptions): PagedAsyncIterableIterator; + // Warning: (ae-forgotten-export) The symbol "MetricNamespaceCollection" needs to be exported by the entry point index.d.ts + listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptions): Promise; + listMetrics(testRunId: string, options?: ListMetricsOptions): PagedAsyncIterableIterator; + listTestRuns(options?: ListTestRunsOptions): PagedAsyncIterableIterator; + stopTestRun(testRunId: string, options?: StopTestRunOptions): Promise; + testRun(testRunId: string, options?: TestRunOptions): Promise; +} + +// @public +export type LoadTestRunClientAggregationType = string; + +// @public +export interface LoadTestRunClientAppComponent { + displayName?: string; + kind?: string; + readonly resourceGroup?: string; + readonly resourceId?: string; + resourceName?: string; + resourceType?: string; + readonly subscriptionId?: string; +} + +// @public +export interface LoadTestRunClientCertificateMetadata { + name?: string; + type?: LoadTestRunClientCertificateType; + value?: string; +} + +// @public +export type LoadTestRunClientCertificateType = string; + +// @public (undocumented) +export interface LoadTestRunClientCreateOrUpdateAppComponentsOptions extends OperationOptions { + // (undocumented) + contentType?: string; + createdBy?: string; + createdDateTime?: Date; + lastModifiedBy?: string; + lastModifiedDateTime?: Date; + testRunId?: string; +} + +// @public (undocumented) +export interface LoadTestRunClientCreateOrUpdateServerMetricsConfigOptions extends OperationOptions { + // (undocumented) + contentType?: string; + createdBy?: string; + createdDateTime?: Date; + lastModifiedBy?: string; + lastModifiedDateTime?: Date; + metrics?: Record; + testRunId?: string; +} + +// @public +export interface LoadTestRunClientDimensionFilter { + name?: string; + values?: string[]; +} + +// @public +export interface LoadTestRunClientDimensionValue { + name?: string; + value?: string; +} + +// @public (undocumented) +export interface LoadTestRunClientDimensionValueList { + // (undocumented) + readonly value: string[]; +} + +// @public +export interface LoadTestRunClientErrorDetails { + readonly message?: string; +} + +// @public +export interface LoadTestRunClientFileInfo { + expireDateTime?: Date; + fileName?: string; + fileType?: LoadTestRunClientFileType; + url?: string; + validationFailureDetails?: string; + validationStatus?: LoadTestRunClientFileStatus; +} + +// @public +export type LoadTestRunClientFileStatus = string; + +// @public +export type LoadTestRunClientFileType = string; + +// @public (undocumented) +export interface LoadTestRunClientGetAppComponentsOptions extends OperationOptions { +} + +// @public (undocumented) +export interface LoadTestRunClientGetServerMetricsConfigOptions extends OperationOptions { +} + +// @public +export type LoadTestRunClientInterval = string; + +// @public +export interface LoadTestRunClientLoadTestConfiguration { + engineInstances?: number; + optionalLoadTestConfig?: LoadTestRunClientOptionalLoadTestConfig; + quickStartTest?: boolean; + splitAllCSVs?: boolean; +} + +// @public +export interface LoadTestRunClientMetricAvailability { + timeGrain?: LoadTestRunClientTimeGrain; +} + +// @public +export interface LoadTestRunClientMetricDefinition { + description?: string; + dimensions?: LoadTestRunClientNameAndDesc[]; + metricAvailabilities?: LoadTestRunClientMetricAvailability[]; + name?: string; + namespace?: string; + primaryAggregationType?: LoadTestRunClientAggregationType; + supportedAggregationTypes?: string[]; + unit?: LoadTestRunClientMetricUnit; +} + +// @public +export interface LoadTestRunClientMetricNamespace { + description?: string; + name?: string; +} + +// @public +export type LoadTestRunClientMetricUnit = string; + +// @public +export interface LoadTestRunClientMetricValue { + timestamp?: string; + value?: number; +} + +// @public +export interface LoadTestRunClientNameAndDesc { + description?: string; + name?: string; +} + +// @public +export interface LoadTestRunClientOptionalLoadTestConfig { + duration?: number; + endpointUrl?: string; + rampUpTime?: number; + virtualUsers?: number; +} + +// @public (undocumented) +export interface LoadTestRunClientOptions extends ClientOptions { +} + +// @public +export interface LoadTestRunClientPassFailCriteria { + passFailMetrics?: Record; +} + +// @public +export interface LoadTestRunClientPassFailMetric { + action?: LoadTestRunClientPFAction; + readonly actualValue?: number; + aggregate?: LoadTestRunClientPFAgFunc; + clientMetric?: LoadTestRunClientPFMetrics; + condition?: string; + requestName?: string; + readonly result?: LoadTestRunClientPFResult; + value?: number; +} + +// @public +export type LoadTestRunClientPFAction = string; + +// @public +export type LoadTestRunClientPFAgFunc = string; + +// @public +export type LoadTestRunClientPFMetrics = string; + +// @public +export type LoadTestRunClientPFResult = string; + +// @public +export type LoadTestRunClientPFTestResult = string; + +// @public +export interface LoadTestRunClientResourceMetric { + aggregation: string; + displayDescription?: string; + readonly id?: string; + metricNamespace: string; + name: string; + resourceId: string; + resourceType: string; + unit?: string; +} + +// @public +export interface LoadTestRunClientSecret { + type?: LoadTestRunClientSecretType; + value?: string; +} + +// @public +export type LoadTestRunClientSecretType = string; + +// @public +export type LoadTestRunClientStatus = string; + +// @public +export interface LoadTestRunClientTest { + certificate?: LoadTestRunClientCertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + environmentVariables?: Record; + readonly inputArtifacts?: LoadTestRunClientTestInputArtifacts; + keyvaultReferenceIdentityId?: string; + keyvaultReferenceIdentityType?: string; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; + passFailCriteria?: LoadTestRunClientPassFailCriteria; + secrets?: Record; + subnetId?: string; + readonly testId?: string; +} + +// @public +export interface LoadTestRunClientTestInputArtifacts { + readonly additionalFileInfo?: LoadTestRunClientFileInfo[]; + configFileInfo?: LoadTestRunClientFileInfo; + inputArtifactsZipFileInfo?: LoadTestRunClientFileInfo; + testScriptFileInfo?: LoadTestRunClientFileInfo; + userPropFileInfo?: LoadTestRunClientFileInfo; +} + +// @public +export interface LoadTestRunClientTestRun { + certificate?: LoadTestRunClientCertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly duration?: number; + readonly endDateTime?: Date; + environmentVariables?: Record; + readonly errorDetails?: LoadTestRunClientErrorDetails[]; + readonly executedDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; + passFailCriteria?: LoadTestRunClientPassFailCriteria; + readonly portalUrl?: string; + secrets?: Record; + readonly startDateTime?: Date; + readonly status?: LoadTestRunClientStatus; + readonly subnetId?: string; + readonly testArtifacts?: LoadTestRunClientTestRunArtifacts; + testId?: string; + readonly testResult?: LoadTestRunClientPFTestResult; + readonly testRunId: string; + readonly testRunStatistics?: Record; + readonly virtualUsers?: number; +} + +// @public +export interface LoadTestRunClientTestRunArtifacts { + readonly inputArtifacts?: LoadTestRunClientTestRunInputArtifacts; + outputArtifacts?: LoadTestRunClientTestRunOutputArtifacts; +} + +// @public +export interface LoadTestRunClientTestRunInputArtifacts { + readonly additionalFileInfo?: LoadTestRunClientFileInfo[]; + configFileInfo?: LoadTestRunClientFileInfo; + inputArtifactsZipFileInfo?: LoadTestRunClientFileInfo; + testScriptFileInfo?: LoadTestRunClientFileInfo; + userPropFileInfo?: LoadTestRunClientFileInfo; +} + +// @public +export interface LoadTestRunClientTestRunOutputArtifacts { + logsFileInfo?: LoadTestRunClientFileInfo; + resultFileInfo?: LoadTestRunClientFileInfo; +} + +// @public +export interface LoadTestRunClientTestRunStatistics { + readonly errorCount?: number; + readonly errorPct?: number; + readonly maxResTime?: number; + readonly meanResTime?: number; + readonly medianResTime?: number; + readonly minResTime?: number; + readonly pct1ResTime?: number; + readonly pct2ResTime?: number; + readonly pct3ResTime?: number; + readonly receivedKBytesPerSec?: number; + readonly sampleCount?: number; + readonly sentKBytesPerSec?: number; + readonly throughput?: number; + readonly transaction?: string; +} + +// @public +export type LoadTestRunClientTimeGrain = string; + +// @public +export interface LoadTestRunClientTimeSeriesElement { + data?: LoadTestRunClientMetricValue[]; + dimensionValues?: LoadTestRunClientDimensionValue[]; +} + +// @public +export interface MetricAvailability { + timeGrain?: TimeGrain; +} + +// @public +export interface MetricDefinition { + description?: string; + dimensions?: NameAndDesc[]; + metricAvailabilities?: MetricAvailability[]; + name?: string; + namespace?: string; + primaryAggregationType?: AggregationType; + supportedAggregationTypes?: string[]; + unit?: MetricUnit; +} + +// @public +export interface MetricNamespace { + description?: string; + name?: string; +} + +// @public +export type MetricUnit = string; + +// @public +export interface MetricValue { + timestamp?: string; + value?: number; +} + +// @public +export interface NameAndDesc { + description?: string; + name?: string; +} + +// @public +export interface OptionalLoadTestConfig { + duration?: number; + endpointUrl?: string; + rampUpTime?: number; + virtualUsers?: number; +} + +// @public +export interface PagedFileInfo { + nextLink?: string; + value: FileInfo[]; +} + +// @public +export interface PagedTest { + nextLink?: string; + value: Test[]; +} + +// @public +export interface PassFailCriteria { + passFailMetrics?: Record; +} + +// @public +export interface PassFailMetric { + action?: PFAction; + readonly actualValue?: number; + aggregate?: PFAgFunc; + clientMetric?: PFMetrics; + condition?: string; + requestName?: string; + readonly result?: PFResult; + value?: number; +} + +// @public +export type PFAction = string; + +// @public +export type PFAgFunc = string; + +// @public +export type PFMetrics = string; + +// @public +export type PFResult = string; + +// @public +export type PFTestResult = string; + +// @public +export interface ResourceMetric { + aggregation: string; + displayDescription?: string; + readonly id?: string; + metricNamespace: string; + name: string; + resourceId: string; + resourceType: string; + unit?: string; +} + +// @public +export interface Secret { + type?: SecretType; + value?: string; +} + +// @public +export type SecretType = string; + +// @public +export type Status = string; + +// @public (undocumented) +export interface StopTestRunOptions extends OperationOptions { +} + +// @public +export interface Test { + certificate?: CertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + environmentVariables?: Record; + readonly inputArtifacts?: TestInputArtifacts; + keyvaultReferenceIdentityId?: string; + keyvaultReferenceIdentityType?: string; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestConfiguration; + passFailCriteria?: PassFailCriteria; + secrets?: Record; + subnetId?: string; + readonly testId?: string; +} + +// @public +export interface TestAppComponents { + components: Record; + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + readonly testId?: string; +} + +// @public +export interface TestInputArtifacts { + readonly additionalFileInfo?: FileInfo[]; + configFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: FileInfo; + testScriptFileInfo?: FileInfo; + userPropFileInfo?: FileInfo; +} + +// @public +export interface TestRun { + certificate?: CertificateMetadata; + readonly createdBy?: string; + readonly createdDateTime?: Date; + description?: string; + displayName?: string; + readonly duration?: number; + readonly endDateTime?: Date; + environmentVariables?: Record; + readonly errorDetails?: ErrorDetails[]; + readonly executedDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestConfiguration; + passFailCriteria?: PassFailCriteria; + readonly portalUrl?: string; + secrets?: Record; + readonly startDateTime?: Date; + readonly status?: Status; + readonly subnetId?: string; + readonly testArtifacts?: TestRunArtifacts; + testId?: string; + readonly testResult?: PFTestResult; + readonly testRunId: string; + readonly testRunStatistics?: Record; + readonly virtualUsers?: number; +} + +// @public +export interface TestRunArtifacts { + readonly inputArtifacts?: TestRunInputArtifacts; + outputArtifacts?: TestRunOutputArtifacts; +} + +// @public +export interface TestRunInputArtifacts { + readonly additionalFileInfo?: FileInfo[]; + configFileInfo?: FileInfo; + inputArtifactsZipFileInfo?: FileInfo; + testScriptFileInfo?: FileInfo; + userPropFileInfo?: FileInfo; +} + +// @public (undocumented) +export interface TestRunOptions extends OperationOptions { + certificate?: LoadTestRunClientCertificateMetadata; + contentType?: string; + createdBy?: string; + createdDateTime?: Date; + description?: string; + displayName?: string; + duration?: number; + endDateTime?: Date; + environmentVariables?: Record; + errorDetails?: LoadTestRunClientErrorDetails[]; + executedDateTime?: Date; + lastModifiedBy?: string; + lastModifiedDateTime?: Date; + loadTestConfiguration?: LoadTestRunClientLoadTestConfiguration; + oldTestRunId?: string; + passFailCriteria?: LoadTestRunClientPassFailCriteria; + portalUrl?: string; + secrets?: Record; + startDateTime?: Date; + status?: LoadTestRunClientStatus; + subnetId?: string; + testArtifacts?: LoadTestRunClientTestRunArtifacts; + testId?: string; + testResult?: LoadTestRunClientPFTestResult; + testRunStatistics?: Record; + virtualUsers?: number; +} + +// @public +export interface TestRunOutputArtifacts { + logsFileInfo?: FileInfo; + resultFileInfo?: FileInfo; +} + +// @public +export interface TestRunStatistics { + readonly errorCount?: number; + readonly errorPct?: number; + readonly maxResTime?: number; + readonly meanResTime?: number; + readonly medianResTime?: number; + readonly minResTime?: number; + readonly pct1ResTime?: number; + readonly pct2ResTime?: number; + readonly pct3ResTime?: number; + readonly receivedKBytesPerSec?: number; + readonly sampleCount?: number; + readonly sentKBytesPerSec?: number; + readonly throughput?: number; + readonly transaction?: string; +} + +// @public +export interface TestServerMetricConfig { + readonly createdBy?: string; + readonly createdDateTime?: Date; + readonly lastModifiedBy?: string; + readonly lastModifiedDateTime?: Date; + metrics?: Record; + readonly testId?: string; +} + +// @public +export type TimeGrain = string; + +// @public +export interface TimeSeriesElement { + data?: MetricValue[]; + dimensionValues?: DimensionValue[]; +} + +// @public (undocumented) +export interface UploadTestFileOptions extends OperationOptions { + // (undocumented) + contentType?: string; + fileType?: FileType; +} + +// (No @packageDocumentation comment for this package) + +``` 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 f176647209..20cb629446 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 @@ -48,7 +48,7 @@ import { import { PagedAsyncIterableIterator, buildPagedAsyncIterator, -} from "../util/pagingUtil.js"; +} from "../../util/pagingUtil.js"; import { CreateOrUpdateTestOptions, CreateOrUpdateAppComponentsOptions, 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 c6d0f1f240..5c9ada29eb 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 @@ -58,7 +58,7 @@ import { import { PagedAsyncIterableIterator, buildPagedAsyncIterator, -} from "../util/pagingUtil.js"; +} from "../../util/pagingUtil.js"; import { TestRunOptions, CreateOrUpdateAppComponentsOptions, diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index 8490c95db2..c119302198 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -84,9 +84,7 @@ function importAllUtils( subfolder: string ) { const project = clientFile.getProject(); - const utils = project.getSourceFile( - `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}util/pagingUtil.ts` - ); + const utils = project.getSourceFile(`${srcPath}/util/pagingUtil.ts`); if (!utils) { return; @@ -95,7 +93,7 @@ function importAllUtils( const exported = [...utils.getExportedDeclarations().keys()]; clientFile.addImportDeclaration({ - moduleSpecifier: `./util/pagingUtil.js`, + moduleSpecifier: `${subfolder !== "" ? "." : ""}./util/pagingUtil.js`, namedImports: exported }); } diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index 8f19efaaca..6d2fd68b96 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -116,7 +116,9 @@ export function buildOperationFiles( if (hasPagingOperation(codeModel)) { operationGroupFile.addImportDeclarations([ { - moduleSpecifier: "../util/pagingUtil.js", + moduleSpecifier: `${ + subfolder && subfolder !== "" ? "../" : "" + }../util/pagingUtil.js`, namedImports: [ "PagedAsyncIterableIterator", "buildPagedAsyncIterator" From 8036a360f9e490ffeb8e0b9d014ceeb05e0d607e Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 14 Sep 2023 21:57:20 +0800 Subject: [PATCH 16/60] update the comments --- .../typespec-ts/test/modularIntegration/pageable.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts b/packages/typespec-ts/test/modularIntegration/pageable.spec.ts index c289417986..4e6389b4b7 100644 --- a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/pageable.spec.ts @@ -4,6 +4,11 @@ import { } from "./generated/payload/pageable/src/index.js"; import { assert } from "chai"; +/** + * Add test cases to test the iterable and iterator + * Add test cases to test error handling + */ + describe("PageableClient Classical Client", () => { let client: PageableClient; From 52ea22793375c10b6fe7d401886728a46b9e3975 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 8 Nov 2023 16:32:50 +0800 Subject: [PATCH 17/60] Rebuild and update the build issue --- common/config/rush/pnpm-lock.yaml | 161 ++++++++++++++++-- .../src/modular/helpers/operationHelpers.ts | 1 - 2 files changed, 151 insertions(+), 11 deletions(-) diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index b69539ff15..46be02da38 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -283,7 +283,7 @@ importers: '@azure-rest/core-client': 1.1.4 '@azure-tools/cadl-ranch': 0.9.0_tezp5rjfyokhpujhigtdeqwzp4 '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky - '@azure-tools/cadl-ranch-specs': 0.20.0_i6m56vm2373g7aupg6kc6ttsfe + '@azure-tools/cadl-ranch-specs': 0.20.0_o47dwcig7y553a2ndtr7sutngq '@azure/core-auth': 1.5.0 '@azure/core-lro': 2.5.4 '@azure/core-paging': 1.5.0 @@ -375,6 +375,18 @@ packages: - '@types/express' dev: true + /@azure-tools/cadl-ranch-coverage-sdk/0.3.1: + resolution: {integrity: sha512-rquOYpZR/Bfy5FdbkLAAuDB8KAVbd317EcmG7ZdCthUXGvu+2+g0MJXEDQd0iCvvp4rgbRSBGEPbjNN/cDalkw==} + engines: {node: '>=16.0.0'} + dependencies: + '@azure/identity': 3.3.0 + '@azure/storage-blob': 12.16.0 + '@types/node': 18.18.0 + transitivePeerDependencies: + - encoding + - supports-color + dev: true + /@azure-tools/cadl-ranch-coverage-sdk/0.4.0: resolution: {integrity: sha512-hK6xVcVacJeuXQB18gEc8+oaHXzHDoFv5rGHoTHagBajOZfgf0vwPdMYUkWH+YLtZadtn0MJP8AOVYnwmqeAyg==} engines: {node: '>=16.0.0'} @@ -387,6 +399,21 @@ packages: - supports-color dev: true + /@azure-tools/cadl-ranch-expect/0.6.0_nk5iko3z3s7n6ut32rpqpshvvq: + resolution: {integrity: sha512-symkbB9p1VMUs6VvFu465ACZPZrPn9sAP/Anjccx9grW0pkrQnE84lA9vkezJ9pJoT+vrJdpPEnjZjNoBQ8GFQ==} + engines: {node: '>=16.0.0'} + peerDependencies: + '@typespec/compiler': ~0.47.0 + '@typespec/http': ~0.47.0 + '@typespec/rest': ~0.47.0 + '@typespec/versioning': ~0.47.0 + dependencies: + '@typespec/compiler': 0.47.1 + '@typespec/http': 0.47.0_@typespec+compiler@0.47.1 + '@typespec/rest': 0.47.0_@typespec+compiler@0.47.1 + '@typespec/versioning': 0.49.0_@typespec+compiler@0.49.0 + dev: true + /@azure-tools/cadl-ranch-expect/0.8.0_hyg5yyh7beodvmafzqxellnzky: resolution: {integrity: sha512-BjyiGorzaq7ejerrEgK4AiDrBgun5A/Q3U7kEGpK+lpjxON4nHkut07DnDqp3uEvxeHp4yZUIOX9MHd+nDPOPg==} engines: {node: '>=16.0.0'} @@ -402,18 +429,18 @@ packages: '@typespec/versioning': 0.49.0_@typespec+compiler@0.49.0 dev: true - /@azure-tools/cadl-ranch-specs/0.20.0_i6m56vm2373g7aupg6kc6ttsfe: + /@azure-tools/cadl-ranch-specs/0.20.0_o47dwcig7y553a2ndtr7sutngq: resolution: {integrity: sha512-eCCZjuPXd3hy6psqh3Es9l9R6GQ7gqe/uPL56h1pUaOXcnvAAJGeny6N/USdqztYjcTx6JkX0V13/KnzGUdz/Q==} engines: {node: '>=16.0.0'} peerDependencies: - '@azure-tools/cadl-ranch-expect': ~0.8.0 - '@azure-tools/typespec-azure-core': ~0.35.0 - '@typespec/compiler': ~0.49.0 - '@typespec/http': ~0.49.0 - '@typespec/rest': ~0.49.0 - '@typespec/versioning': ~0.49.0 - dependencies: - '@azure-tools/cadl-ranch': 0.9.0_tezp5rjfyokhpujhigtdeqwzp4 + '@azure-tools/cadl-ranch-expect': ~0.6.0 + '@azure-tools/typespec-azure-core': ~0.33.0 + '@typespec/compiler': ~0.47.0 + '@typespec/http': ~0.47.0 + '@typespec/rest': ~0.47.0 + '@typespec/versioning': ~0.47.0 + dependencies: + '@azure-tools/cadl-ranch': 0.7.0_tezp5rjfyokhpujhigtdeqwzp4 '@azure-tools/cadl-ranch-api': 0.4.1 '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky '@azure-tools/typespec-azure-core': 0.35.0_l2k6cauhiswc7cyef3ltb45dhy @@ -427,6 +454,42 @@ packages: - supports-color dev: true + /@azure-tools/cadl-ranch/0.7.0_tezp5rjfyokhpujhigtdeqwzp4: + resolution: {integrity: sha512-udtCNpsRvuQC17aBV8ed+D+9gr0X/sF6n9v+JSDeHlT1BEXAqsml2xbU/TuQPj1v11K0E/6Ft336oA+qYvIlDA==} + engines: {node: '>=16.0.0'} + hasBin: true + dependencies: + '@azure-tools/cadl-ranch-api': 0.4.1 + '@azure-tools/cadl-ranch-coverage-sdk': 0.3.1 + '@azure-tools/cadl-ranch-expect': 0.6.0_nk5iko3z3s7n6ut32rpqpshvvq + '@azure/identity': 3.3.0 + '@types/js-yaml': 4.0.6 + '@typespec/compiler': 0.47.1 + '@typespec/http': 0.47.0_@typespec+compiler@0.47.1 + '@typespec/rest': 0.47.0_@typespec+compiler@0.47.1 + ajv: 8.12.0 + body-parser: 1.20.2 + deep-equal: 2.2.2 + express: 4.18.2 + express-promise-router: 4.1.1_express@4.18.2 + glob: 10.3.9 + jackspeak: 2.1.1 + js-yaml: 4.1.0 + morgan: 1.10.0 + node-fetch: 3.3.2 + picocolors: 1.0.0 + prettier: 2.8.8 + source-map-support: 0.5.21 + winston: 3.10.0 + xml2js: 0.5.0 + yargs: 17.7.2 + transitivePeerDependencies: + - '@types/express' + - '@typespec/versioning' + - encoding + - supports-color + dev: true + /@azure-tools/cadl-ranch/0.9.0_tezp5rjfyokhpujhigtdeqwzp4: resolution: {integrity: sha512-EjY+NJ5DprIuVRrpNoTiJANcy5tqHQCRT7KVc3ry1kdQNhEMXV0VVSq8qDhyF60JRbfwMEv97nIpa743yUYW9w==} engines: {node: '>=16.0.0'} @@ -1339,6 +1402,26 @@ packages: eslint-visitor-keys: 3.4.3 dev: true + /@typespec/compiler/0.47.1: + resolution: {integrity: sha512-EBTweucgrUiFLVbBLYJobgV1emoGzM50iPrOz/Fr3dwFFnISpZJ8wzapq+z0okrvx75+W5q12bms8DjsUWapTA==} + engines: {node: '>=16.0.0'} + hasBin: true + dependencies: + '@babel/code-frame': 7.22.13 + ajv: 8.12.0 + change-case: 4.1.2 + globby: 13.1.4 + js-yaml: 4.1.0 + mustache: 4.2.0 + picocolors: 1.0.0 + prettier: 3.0.3 + prompts: 2.4.2 + semver: 7.5.4 + vscode-languageserver: 8.1.0 + vscode-languageserver-textdocument: 1.0.8 + yargs: 17.7.2 + dev: true + /@typespec/compiler/0.49.0: resolution: {integrity: sha512-wu0BzCnG6K8GArO1Mo0UIAVvsGnip+Dce3uBuPcW6mGSAv6Y0NljWBHp8dAJNs+uv45wFWpdkZFQvjr3SNUDJw==} engines: {node: '>=16.0.0'} @@ -1358,6 +1441,15 @@ packages: yaml: 2.3.2 yargs: 17.7.2 + /@typespec/http/0.47.0_@typespec+compiler@0.47.1: + resolution: {integrity: sha512-HrVu5mGV+p3KGPtcNFHB5gXm9pU4rYRG3hJWZdLcN8fy+OuwbhmOgjOGN4AB7HLllnISmcFn6LtlqGnr0LpyfA==} + engines: {node: '>=16.0.0'} + peerDependencies: + '@typespec/compiler': ~0.47.0 + dependencies: + '@typespec/compiler': 0.47.1 + dev: true + /@typespec/http/0.49.0_@typespec+compiler@0.49.0: resolution: {integrity: sha512-MvDJ0s7CjeA/nmutQ4PSTYOj0Gy+78PNd/xe4W5II5w4Kb32Q1vT/oWI2bVZ9G5MkTugKK9P6jmfzwY7EiHksg==} engines: {node: '>=16.0.0'} @@ -1393,6 +1485,15 @@ packages: yaml: 2.3.2 dev: false + /@typespec/rest/0.47.0_@typespec+compiler@0.47.1: + resolution: {integrity: sha512-sjxCY2dQ6Wc51W7NYDLgcZdeTI35vFJR0aK+tuYHMTwjhZJK20ezwb/c+RZQ8xyGIyX+vUj9yhTc7lBZGw4n1A==} + engines: {node: '>=16.0.0'} + peerDependencies: + '@typespec/compiler': ~0.47.0 + dependencies: + '@typespec/compiler': 0.47.1 + dev: true + /@typespec/rest/0.49.0_eeytn2g3ek3zpawg2doqsgnp3y: resolution: {integrity: sha512-C5Ym3Dal5MzDkDIAzTekLsGtPDzRSC9cbiagq4LQfFtzfUPA8tJlJOnD8txTw/XIaFg0hvAPNgTZSa+xtiXskQ==} engines: {node: '>=16.0.0'} @@ -3224,6 +3325,17 @@ packages: slash: 3.0.0 dev: true + /globby/13.1.4: + resolution: {integrity: sha512-iui/IiiW+QrJ1X1hKH5qwlMQyv34wJAYwH1vrf8b9kBA4sNiif3gKsMHa+BrdnOpEudWjpotfa7LrTzB1ERS/g==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + dependencies: + dir-glob: 3.0.1 + fast-glob: 3.3.1 + ignore: 5.2.4 + merge2: 1.4.1 + slash: 4.0.0 + dev: true + /globby/13.2.2: resolution: {integrity: sha512-Y1zNGV+pzQdh7H39l9zgB4PJqjRNqydvdYCDG4HFXM4XuvSaQQlEc91IU1yALL8gUTDomgBAfz3XJdmUS+oo0w==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -4668,6 +4780,12 @@ packages: engines: {node: '>=10.13.0'} hasBin: true + /prettier/2.8.8: + resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} + engines: {node: '>=10.13.0'} + hasBin: true + dev: true + /prettier/3.0.3: resolution: {integrity: sha512-L/4pUDMxcNa8R/EthV08Zt42WBO4h1rarVtK0K+QJG0X187OLo7l699jWw0GKuwzkPQ//jMFA/8Xm6Fh3J/DAg==} engines: {node: '>=14'} @@ -5825,10 +5943,22 @@ packages: engines: {node: '>=4.0.0 || >=6.0.0'} dev: false + /vscode-jsonrpc/8.1.0: + resolution: {integrity: sha512-6TDy/abTQk+zDGYazgbIPc+4JoXdwC8NHU9Pbn4UJP1fehUyZmM4RHp5IthX7A6L5KS30PRui+j+tbbMMMafdw==} + engines: {node: '>=14.0.0'} + dev: true + /vscode-jsonrpc/8.2.0: resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==} engines: {node: '>=14.0.0'} + /vscode-languageserver-protocol/3.17.3: + resolution: {integrity: sha512-924/h0AqsMtA5yK22GgMtCYiMdCOtWTSGgUOkgEDX+wk2b0x4sAfLiO4NxBxqbiVtz7K7/1/RgVrVI0NClZwqA==} + dependencies: + vscode-jsonrpc: 8.1.0 + vscode-languageserver-types: 3.17.3 + dev: true + /vscode-languageserver-protocol/3.17.5: resolution: {integrity: sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==} dependencies: @@ -5838,9 +5968,20 @@ packages: /vscode-languageserver-textdocument/1.0.8: resolution: {integrity: sha512-1bonkGqQs5/fxGT5UchTgjGVnfysL0O8v1AYMBjqTbWQTFn721zaPGDYFkOKtfDgFiSgXM3KwaG3FMGfW4Ed9Q==} + /vscode-languageserver-types/3.17.3: + resolution: {integrity: sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==} + dev: true + /vscode-languageserver-types/3.17.5: resolution: {integrity: sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==} + /vscode-languageserver/8.1.0: + resolution: {integrity: sha512-eUt8f1z2N2IEUDBsKaNapkz7jl5QpskN2Y0G01T/ItMxBxw1fJwvtySGB9QMecatne8jFIWJGWI61dWjyTLQsw==} + hasBin: true + dependencies: + vscode-languageserver-protocol: 3.17.3 + dev: true + /vscode-languageserver/9.0.1: resolution: {integrity: sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==} hasBin: true diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 4cc49b05d4..6011fca611 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -22,7 +22,6 @@ import { normalizeName } from "@azure-tools/rlc-common"; import { getClassicalLayerPrefix, getOperationName } from "./namingHelpers.js"; -import { getOperationName } from "./namingHelpers.js"; import { getFixmeForMultilineDocs, getDocsFromDescription From 960263f0fbb8fac543f7bf990cfd1011b55c9f49 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 8 Nov 2023 16:51:59 +0800 Subject: [PATCH 18/60] Update the ranch version --- common/config/rush/pnpm-lock.yaml | 159 +++++++----------------------- packages/typespec-ts/package.json | 2 +- 2 files changed, 35 insertions(+), 126 deletions(-) diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 46be02da38..23ce4ed8eb 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -231,7 +231,7 @@ importers: '@azure-rest/core-client': ^1.1.4 '@azure-tools/cadl-ranch': ^0.9.0 '@azure-tools/cadl-ranch-expect': ^0.8.0 - '@azure-tools/cadl-ranch-specs': ^0.20.0 + '@azure-tools/cadl-ranch-specs': ^0.25.0 '@azure-tools/rlc-common': workspace:^0.18.0 '@azure-tools/typespec-azure-core': '>=0.35.0 <1.0.0' '@azure-tools/typespec-client-generator-core': '>=0.35.0 <1.0.0' @@ -283,7 +283,7 @@ importers: '@azure-rest/core-client': 1.1.4 '@azure-tools/cadl-ranch': 0.9.0_tezp5rjfyokhpujhigtdeqwzp4 '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky - '@azure-tools/cadl-ranch-specs': 0.20.0_o47dwcig7y553a2ndtr7sutngq + '@azure-tools/cadl-ranch-specs': 0.25.0_o47dwcig7y553a2ndtr7sutngq '@azure/core-auth': 1.5.0 '@azure/core-lro': 2.5.4 '@azure/core-paging': 1.5.0 @@ -375,18 +375,6 @@ packages: - '@types/express' dev: true - /@azure-tools/cadl-ranch-coverage-sdk/0.3.1: - resolution: {integrity: sha512-rquOYpZR/Bfy5FdbkLAAuDB8KAVbd317EcmG7ZdCthUXGvu+2+g0MJXEDQd0iCvvp4rgbRSBGEPbjNN/cDalkw==} - engines: {node: '>=16.0.0'} - dependencies: - '@azure/identity': 3.3.0 - '@azure/storage-blob': 12.16.0 - '@types/node': 18.18.0 - transitivePeerDependencies: - - encoding - - supports-color - dev: true - /@azure-tools/cadl-ranch-coverage-sdk/0.4.0: resolution: {integrity: sha512-hK6xVcVacJeuXQB18gEc8+oaHXzHDoFv5rGHoTHagBajOZfgf0vwPdMYUkWH+YLtZadtn0MJP8AOVYnwmqeAyg==} engines: {node: '>=16.0.0'} @@ -399,23 +387,23 @@ packages: - supports-color dev: true - /@azure-tools/cadl-ranch-expect/0.6.0_nk5iko3z3s7n6ut32rpqpshvvq: - resolution: {integrity: sha512-symkbB9p1VMUs6VvFu465ACZPZrPn9sAP/Anjccx9grW0pkrQnE84lA9vkezJ9pJoT+vrJdpPEnjZjNoBQ8GFQ==} + /@azure-tools/cadl-ranch-expect/0.8.0_hyg5yyh7beodvmafzqxellnzky: + resolution: {integrity: sha512-BjyiGorzaq7ejerrEgK4AiDrBgun5A/Q3U7kEGpK+lpjxON4nHkut07DnDqp3uEvxeHp4yZUIOX9MHd+nDPOPg==} engines: {node: '>=16.0.0'} peerDependencies: - '@typespec/compiler': ~0.47.0 - '@typespec/http': ~0.47.0 - '@typespec/rest': ~0.47.0 - '@typespec/versioning': ~0.47.0 - dependencies: - '@typespec/compiler': 0.47.1 - '@typespec/http': 0.47.0_@typespec+compiler@0.47.1 - '@typespec/rest': 0.47.0_@typespec+compiler@0.47.1 + '@typespec/compiler': ~0.49.0 + '@typespec/http': ~0.49.0 + '@typespec/rest': ~0.49.0 + '@typespec/versioning': ~0.49.0 + dependencies: + '@typespec/compiler': 0.49.0 + '@typespec/http': 0.49.0_@typespec+compiler@0.49.0 + '@typespec/rest': 0.49.0_eeytn2g3ek3zpawg2doqsgnp3y '@typespec/versioning': 0.49.0_@typespec+compiler@0.49.0 dev: true - /@azure-tools/cadl-ranch-expect/0.8.0_hyg5yyh7beodvmafzqxellnzky: - resolution: {integrity: sha512-BjyiGorzaq7ejerrEgK4AiDrBgun5A/Q3U7kEGpK+lpjxON4nHkut07DnDqp3uEvxeHp4yZUIOX9MHd+nDPOPg==} + /@azure-tools/cadl-ranch-expect/0.8.1_hyg5yyh7beodvmafzqxellnzky: + resolution: {integrity: sha512-ea2X6BlImkPmeCEaMUniTIkJRo7EfJy1SdHy4rrdhg2rTPRQUGQJHLdsWle2Stiy7uTkEQCXngg+RmpsQP9PRg==} engines: {node: '>=16.0.0'} peerDependencies: '@typespec/compiler': ~0.49.0 @@ -429,18 +417,18 @@ packages: '@typespec/versioning': 0.49.0_@typespec+compiler@0.49.0 dev: true - /@azure-tools/cadl-ranch-specs/0.20.0_o47dwcig7y553a2ndtr7sutngq: - resolution: {integrity: sha512-eCCZjuPXd3hy6psqh3Es9l9R6GQ7gqe/uPL56h1pUaOXcnvAAJGeny6N/USdqztYjcTx6JkX0V13/KnzGUdz/Q==} + /@azure-tools/cadl-ranch-specs/0.25.0_o47dwcig7y553a2ndtr7sutngq: + resolution: {integrity: sha512-TV1EsOCjeRCS/54KWCekwMDjGZN/H4F9Hqkp3djNhpemBCThiuGImNLC01b0ivY1r1NhiPZ08rFRq3QpFU22Rw==} engines: {node: '>=16.0.0'} peerDependencies: - '@azure-tools/cadl-ranch-expect': ~0.6.0 - '@azure-tools/typespec-azure-core': ~0.33.0 - '@typespec/compiler': ~0.47.0 - '@typespec/http': ~0.47.0 - '@typespec/rest': ~0.47.0 - '@typespec/versioning': ~0.47.0 - dependencies: - '@azure-tools/cadl-ranch': 0.7.0_tezp5rjfyokhpujhigtdeqwzp4 + '@azure-tools/cadl-ranch-expect': ~0.8.1 + '@azure-tools/typespec-azure-core': ~0.35.0 + '@typespec/compiler': ~0.49.0 + '@typespec/http': ~0.49.0 + '@typespec/rest': ~0.49.0 + '@typespec/versioning': ~0.49.0 + dependencies: + '@azure-tools/cadl-ranch': 0.9.1_tezp5rjfyokhpujhigtdeqwzp4 '@azure-tools/cadl-ranch-api': 0.4.1 '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky '@azure-tools/typespec-azure-core': 0.35.0_l2k6cauhiswc7cyef3ltb45dhy @@ -454,19 +442,19 @@ packages: - supports-color dev: true - /@azure-tools/cadl-ranch/0.7.0_tezp5rjfyokhpujhigtdeqwzp4: - resolution: {integrity: sha512-udtCNpsRvuQC17aBV8ed+D+9gr0X/sF6n9v+JSDeHlT1BEXAqsml2xbU/TuQPj1v11K0E/6Ft336oA+qYvIlDA==} + /@azure-tools/cadl-ranch/0.9.0_tezp5rjfyokhpujhigtdeqwzp4: + resolution: {integrity: sha512-EjY+NJ5DprIuVRrpNoTiJANcy5tqHQCRT7KVc3ry1kdQNhEMXV0VVSq8qDhyF60JRbfwMEv97nIpa743yUYW9w==} engines: {node: '>=16.0.0'} hasBin: true dependencies: '@azure-tools/cadl-ranch-api': 0.4.1 - '@azure-tools/cadl-ranch-coverage-sdk': 0.3.1 - '@azure-tools/cadl-ranch-expect': 0.6.0_nk5iko3z3s7n6ut32rpqpshvvq + '@azure-tools/cadl-ranch-coverage-sdk': 0.4.0 + '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky '@azure/identity': 3.3.0 '@types/js-yaml': 4.0.6 - '@typespec/compiler': 0.47.1 - '@typespec/http': 0.47.0_@typespec+compiler@0.47.1 - '@typespec/rest': 0.47.0_@typespec+compiler@0.47.1 + '@typespec/compiler': 0.49.0 + '@typespec/http': 0.49.0_@typespec+compiler@0.49.0 + '@typespec/rest': 0.49.0_eeytn2g3ek3zpawg2doqsgnp3y ajv: 8.12.0 body-parser: 1.20.2 deep-equal: 2.2.2 @@ -478,7 +466,6 @@ packages: morgan: 1.10.0 node-fetch: 3.3.2 picocolors: 1.0.0 - prettier: 2.8.8 source-map-support: 0.5.21 winston: 3.10.0 xml2js: 0.5.0 @@ -490,14 +477,14 @@ packages: - supports-color dev: true - /@azure-tools/cadl-ranch/0.9.0_tezp5rjfyokhpujhigtdeqwzp4: - resolution: {integrity: sha512-EjY+NJ5DprIuVRrpNoTiJANcy5tqHQCRT7KVc3ry1kdQNhEMXV0VVSq8qDhyF60JRbfwMEv97nIpa743yUYW9w==} + /@azure-tools/cadl-ranch/0.9.1_tezp5rjfyokhpujhigtdeqwzp4: + resolution: {integrity: sha512-tkfBrPKKKe7C0Wjkz7CvITUg+w5X9WPqFu3wqCCOirofZ/QB1MQboOUI6jPxODMNNiGXJkWPm045YY55ROTA1g==} engines: {node: '>=16.0.0'} hasBin: true dependencies: '@azure-tools/cadl-ranch-api': 0.4.1 '@azure-tools/cadl-ranch-coverage-sdk': 0.4.0 - '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky + '@azure-tools/cadl-ranch-expect': 0.8.1_hyg5yyh7beodvmafzqxellnzky '@azure/identity': 3.3.0 '@types/js-yaml': 4.0.6 '@typespec/compiler': 0.49.0 @@ -1402,26 +1389,6 @@ packages: eslint-visitor-keys: 3.4.3 dev: true - /@typespec/compiler/0.47.1: - resolution: {integrity: sha512-EBTweucgrUiFLVbBLYJobgV1emoGzM50iPrOz/Fr3dwFFnISpZJ8wzapq+z0okrvx75+W5q12bms8DjsUWapTA==} - engines: {node: '>=16.0.0'} - hasBin: true - dependencies: - '@babel/code-frame': 7.22.13 - ajv: 8.12.0 - change-case: 4.1.2 - globby: 13.1.4 - js-yaml: 4.1.0 - mustache: 4.2.0 - picocolors: 1.0.0 - prettier: 3.0.3 - prompts: 2.4.2 - semver: 7.5.4 - vscode-languageserver: 8.1.0 - vscode-languageserver-textdocument: 1.0.8 - yargs: 17.7.2 - dev: true - /@typespec/compiler/0.49.0: resolution: {integrity: sha512-wu0BzCnG6K8GArO1Mo0UIAVvsGnip+Dce3uBuPcW6mGSAv6Y0NljWBHp8dAJNs+uv45wFWpdkZFQvjr3SNUDJw==} engines: {node: '>=16.0.0'} @@ -1441,15 +1408,6 @@ packages: yaml: 2.3.2 yargs: 17.7.2 - /@typespec/http/0.47.0_@typespec+compiler@0.47.1: - resolution: {integrity: sha512-HrVu5mGV+p3KGPtcNFHB5gXm9pU4rYRG3hJWZdLcN8fy+OuwbhmOgjOGN4AB7HLllnISmcFn6LtlqGnr0LpyfA==} - engines: {node: '>=16.0.0'} - peerDependencies: - '@typespec/compiler': ~0.47.0 - dependencies: - '@typespec/compiler': 0.47.1 - dev: true - /@typespec/http/0.49.0_@typespec+compiler@0.49.0: resolution: {integrity: sha512-MvDJ0s7CjeA/nmutQ4PSTYOj0Gy+78PNd/xe4W5II5w4Kb32Q1vT/oWI2bVZ9G5MkTugKK9P6jmfzwY7EiHksg==} engines: {node: '>=16.0.0'} @@ -1485,15 +1443,6 @@ packages: yaml: 2.3.2 dev: false - /@typespec/rest/0.47.0_@typespec+compiler@0.47.1: - resolution: {integrity: sha512-sjxCY2dQ6Wc51W7NYDLgcZdeTI35vFJR0aK+tuYHMTwjhZJK20ezwb/c+RZQ8xyGIyX+vUj9yhTc7lBZGw4n1A==} - engines: {node: '>=16.0.0'} - peerDependencies: - '@typespec/compiler': ~0.47.0 - dependencies: - '@typespec/compiler': 0.47.1 - dev: true - /@typespec/rest/0.49.0_eeytn2g3ek3zpawg2doqsgnp3y: resolution: {integrity: sha512-C5Ym3Dal5MzDkDIAzTekLsGtPDzRSC9cbiagq4LQfFtzfUPA8tJlJOnD8txTw/XIaFg0hvAPNgTZSa+xtiXskQ==} engines: {node: '>=16.0.0'} @@ -3325,17 +3274,6 @@ packages: slash: 3.0.0 dev: true - /globby/13.1.4: - resolution: {integrity: sha512-iui/IiiW+QrJ1X1hKH5qwlMQyv34wJAYwH1vrf8b9kBA4sNiif3gKsMHa+BrdnOpEudWjpotfa7LrTzB1ERS/g==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - dependencies: - dir-glob: 3.0.1 - fast-glob: 3.3.1 - ignore: 5.2.4 - merge2: 1.4.1 - slash: 4.0.0 - dev: true - /globby/13.2.2: resolution: {integrity: sha512-Y1zNGV+pzQdh7H39l9zgB4PJqjRNqydvdYCDG4HFXM4XuvSaQQlEc91IU1yALL8gUTDomgBAfz3XJdmUS+oo0w==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -4780,12 +4718,6 @@ packages: engines: {node: '>=10.13.0'} hasBin: true - /prettier/2.8.8: - resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} - engines: {node: '>=10.13.0'} - hasBin: true - dev: true - /prettier/3.0.3: resolution: {integrity: sha512-L/4pUDMxcNa8R/EthV08Zt42WBO4h1rarVtK0K+QJG0X187OLo7l699jWw0GKuwzkPQ//jMFA/8Xm6Fh3J/DAg==} engines: {node: '>=14'} @@ -5943,22 +5875,10 @@ packages: engines: {node: '>=4.0.0 || >=6.0.0'} dev: false - /vscode-jsonrpc/8.1.0: - resolution: {integrity: sha512-6TDy/abTQk+zDGYazgbIPc+4JoXdwC8NHU9Pbn4UJP1fehUyZmM4RHp5IthX7A6L5KS30PRui+j+tbbMMMafdw==} - engines: {node: '>=14.0.0'} - dev: true - /vscode-jsonrpc/8.2.0: resolution: {integrity: sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==} engines: {node: '>=14.0.0'} - /vscode-languageserver-protocol/3.17.3: - resolution: {integrity: sha512-924/h0AqsMtA5yK22GgMtCYiMdCOtWTSGgUOkgEDX+wk2b0x4sAfLiO4NxBxqbiVtz7K7/1/RgVrVI0NClZwqA==} - dependencies: - vscode-jsonrpc: 8.1.0 - vscode-languageserver-types: 3.17.3 - dev: true - /vscode-languageserver-protocol/3.17.5: resolution: {integrity: sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==} dependencies: @@ -5968,20 +5888,9 @@ packages: /vscode-languageserver-textdocument/1.0.8: resolution: {integrity: sha512-1bonkGqQs5/fxGT5UchTgjGVnfysL0O8v1AYMBjqTbWQTFn721zaPGDYFkOKtfDgFiSgXM3KwaG3FMGfW4Ed9Q==} - /vscode-languageserver-types/3.17.3: - resolution: {integrity: sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==} - dev: true - /vscode-languageserver-types/3.17.5: resolution: {integrity: sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==} - /vscode-languageserver/8.1.0: - resolution: {integrity: sha512-eUt8f1z2N2IEUDBsKaNapkz7jl5QpskN2Y0G01T/ItMxBxw1fJwvtySGB9QMecatne8jFIWJGWI61dWjyTLQsw==} - hasBin: true - dependencies: - vscode-languageserver-protocol: 3.17.3 - dev: true - /vscode-languageserver/9.0.1: resolution: {integrity: sha512-woByF3PDpkHFUreUa7Hos7+pUWdeWMXRd26+ZX2A8cFx6v/JPTtd4/uN0/jB6XQHYaOlHbio03NTHCqrgG5n7g==} hasBin: true diff --git a/packages/typespec-ts/package.json b/packages/typespec-ts/package.json index c24e8e6513..b6c866f80d 100644 --- a/packages/typespec-ts/package.json +++ b/packages/typespec-ts/package.json @@ -58,7 +58,7 @@ "ts-node": "~10.9.1", "typescript": "~5.2.0", "prettier": "~2.7.1", - "@azure-tools/cadl-ranch-specs": "^0.20.0", + "@azure-tools/cadl-ranch-specs": "^0.25.0", "@azure-tools/cadl-ranch-expect": "^0.8.0", "@azure-tools/cadl-ranch": "^0.9.0", "chalk": "^4.0.0", From 068b10b11c133e7c4c32ab9e7c2fb0aadb6a530c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 17:52:15 +0800 Subject: [PATCH 19/60] Refactor the paging codes --- .../generated/typespec-ts/src/BatchClient.ts | 49 +- .../typespec-ts/src/api/operations.ts | 16791 ++++++++-------- .../typespec-ts/src/api/pagingHelper.ts | 229 + .../generated/typespec-ts/src/index.ts | 2 + .../generated/typespec-ts/src/models/index.ts | 2 + .../typespec-ts/src/models/pagings.ts | 33 + .../typespec-ts/src/{util => }/pagingUtil.ts | 0 7 files changed, 8575 insertions(+), 8531 deletions(-) create mode 100644 packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts create mode 100644 packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagings.ts rename packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/{util => }/pagingUtil.ts (100%) 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 ff17ba9756..3d4c790c80 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 @@ -4,11 +4,9 @@ import { TokenCredential } from "@azure/core-auth"; import { Pipeline } from "@azure/core-rest-pipeline"; import { - ApplicationListResult, BatchApplication, - PoolListUsageMetricsResult, + PoolUsageMetrics, BatchPoolCreateOptions, - BatchPoolListResult, BatchPool, AutoScaleRun, BatchPoolUpdateOptions, @@ -17,29 +15,25 @@ import { BatchPoolResizeOptions, BatchPoolReplaceOptions, NodeRemoveOptions, - AccountListSupportedImagesResult, - PoolNodeCountsListResult, + ImageInformation, + PoolNodeCounts, BatchJob, BatchJobUpdateOptions, BatchJobDisableOptions, BatchJobTerminateOptions, BatchJobCreateOptions, - BatchJobListResult, - BatchJobListPreparationAndReleaseTaskStatusResult, + JobPreparationAndReleaseTaskExecutionInformation, TaskCountsResult, BatchCertificate, - CertificateListResult, BatchJobSchedule, BatchJobScheduleUpdateOptions, BatchJobScheduleCreateOptions, - BatchJobScheduleListResult, BatchTaskCreateOptions, - BatchTaskListResult, BatchTask, BatchTaskCollection, TaskAddCollectionResult, BatchTaskListSubtasksResult, - NodeFileListResult, + NodeFile, BatchNodeUserCreateOptions, BatchNodeUserUpdateOptions, BatchNode, @@ -49,9 +43,7 @@ import { BatchNodeRemoteLoginSettingsResult, UploadBatchServiceLogsOptions, UploadBatchServiceLogsResult, - BatchNodeListResult, NodeVMExtension, - NodeVMExtensionList, } from "./models/models.js"; import { ListApplicationsOptions, @@ -212,6 +204,7 @@ import { getNodeFileProperties, listNodeFiles, } from "./api/index.js"; +import { PagedAsyncIterableIterator } from "./models/index.js"; export { BatchClientOptions } from "./api/BatchContext.js"; @@ -239,7 +232,7 @@ export class BatchClient { */ listApplications( options: ListApplicationsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listApplications(this._client, options); } @@ -267,7 +260,7 @@ export class BatchClient { */ listPoolUsageMetrics( options: ListPoolUsageMetricsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listPoolUsageMetrics(this._client, options); } @@ -286,7 +279,7 @@ export class BatchClient { /** Lists all of the Pools in the specified Account. */ listPools( options: ListPoolsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listPools(this._client, options); } @@ -439,7 +432,7 @@ export class BatchClient { /** Lists all Virtual Machine Images supported by the Azure Batch service. */ listSupportedImages( options: ListSupportedImagesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listSupportedImages(this._client, options); } @@ -450,7 +443,7 @@ export class BatchClient { */ listPoolNodeCounts( options: ListPoolNodeCountsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listPoolNodeCounts(this._client, options); } @@ -575,7 +568,7 @@ export class BatchClient { /** Lists all of the Jobs in the specified Account. */ listJobs( options: ListJobsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listJobs(this._client, options); } @@ -583,7 +576,7 @@ export class BatchClient { listJobsFromSchedule( jobScheduleId: string, options: ListJobsFromScheduleOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listJobsFromSchedule(this._client, jobScheduleId, options); } @@ -600,7 +593,7 @@ export class BatchClient { options: ListJobPreparationAndReleaseTaskStatusOptions = { requestOptions: {}, } - ): Promise { + ): PagedAsyncIterableIterator { return listJobPreparationAndReleaseTaskStatus(this._client, jobId, options); } @@ -628,7 +621,7 @@ export class BatchClient { /** Lists all of the Certificates that have been added to the specified Account. */ listCertificates( options: ListCertificatesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listCertificates(this._client, options); } @@ -787,7 +780,7 @@ export class BatchClient { /** Lists all of the Job Schedules in the specified Account. */ listJobSchedules( options: ListJobSchedulesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listJobSchedules(this._client, options); } @@ -812,7 +805,7 @@ export class BatchClient { listTasks( jobId: string, options: ListTasksOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTasks(this._client, jobId, options); } @@ -958,7 +951,7 @@ export class BatchClient { jobId: string, taskId: string, options: ListTaskFilesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listTaskFiles(this._client, jobId, taskId, options); } @@ -1117,7 +1110,7 @@ export class BatchClient { listNodes( poolId: string, options: ListNodesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listNodes(this._client, poolId, options); } @@ -1142,7 +1135,7 @@ export class BatchClient { poolId: string, nodeId: string, options: ListNodeExtensionsOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listNodeExtensions(this._client, poolId, nodeId, options); } @@ -1187,7 +1180,7 @@ export class BatchClient { poolId: string, nodeId: string, options: ListNodeFilesOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listNodeFiles(this._client, poolId, nodeId, options); } } 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 13f022ec10..8985c94e31 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 @@ -5,6 +5,7 @@ import { ApplicationListResult, BatchApplication, PoolListUsageMetricsResult, + PoolUsageMetrics, BatchPoolCreateOptions, BatchPoolListResult, BatchPool, @@ -16,7 +17,9 @@ import { BatchPoolReplaceOptions, NodeRemoveOptions, AccountListSupportedImagesResult, + ImageInformation, PoolNodeCountsListResult, + PoolNodeCounts, BatchJob, BatchJobUpdateOptions, BatchJobDisableOptions, @@ -24,6 +27,7 @@ import { BatchJobCreateOptions, BatchJobListResult, BatchJobListPreparationAndReleaseTaskStatusResult, + JobPreparationAndReleaseTaskExecutionInformation, TaskCountsResult, BatchCertificate, CertificateListResult, @@ -38,6 +42,7 @@ import { TaskAddCollectionResult, BatchTaskListSubtasksResult, NodeFileListResult, + NodeFile, BatchNodeUserCreateOptions, BatchNodeUserUpdateOptions, BatchNode, @@ -214,6 +219,7 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; +import { buildPagedAsyncIterator } from "./pagingHelper.js"; import { ListApplicationsOptions, GetApplicationOptions, @@ -292,6 +298,7 @@ import { GetNodeFilePropertiesOptions, ListNodeFilesOptions, } from "../models/options.js"; +import { PagedAsyncIterableIterator } from "../models/index.js"; export function _listApplicationsSend( context: Client, @@ -299,15 +306,13 @@ export function _listApplicationsSend( ): StreamableMethod< ListApplications200Response | ListApplicationsDefaultResponse > { - return context - .path("/applications") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - }, - }); + return context.path("/applications").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + }, + }); } export async function _listApplicationsDeserialize( @@ -334,12 +339,16 @@ export async function _listApplicationsDeserialize( * available to Compute Nodes, use the Azure portal or the Azure Resource Manager * API. */ -export async function listApplications( +export function listApplications( context: Client, options: ListApplicationsOptions = { requestOptions: {} } -): Promise { - const result = await _listApplicationsSend(context, options); - return _listApplicationsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listApplicationsSend, + _listApplicationsDeserialize, + [context, options] + ); } export function _getApplicationSend( @@ -347,12 +356,10 @@ export function _getApplicationSend( applicationId: string, options: GetApplicationOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/applications/{applicationId}", applicationId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/applications/{applicationId}", applicationId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _getApplicationDeserialize( @@ -391,18 +398,16 @@ export function _listPoolUsageMetricsSend( ): StreamableMethod< ListPoolUsageMetrics200Response | ListPoolUsageMetricsDefaultResponse > { - return context - .path("/poolusagemetrics") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - starttime: options?.starttime?.toISOString(), - endtime: options?.endtime?.toISOString(), - $filter: options?.$filter, - }, - }); + return context.path("/poolusagemetrics").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + starttime: options?.starttime?.toISOString(), + endtime: options?.endtime?.toISOString(), + $filter: options?.$filter, + }, + }); } export async function _listPoolUsageMetricsDeserialize( @@ -432,12 +437,16 @@ export async function _listPoolUsageMetricsDeserialize( * times of the last aggregation interval currently available; that is, only the * last aggregation interval is returned. */ -export async function listPoolUsageMetrics( +export function listPoolUsageMetrics( context: Client, options: ListPoolUsageMetricsOptions = { requestOptions: {} } -): Promise { - const result = await _listPoolUsageMetricsSend(context, options); - return _listPoolUsageMetricsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listPoolUsageMetricsSend, + _listPoolUsageMetricsDeserialize, + [context, options] + ); } export function _createPoolSend( @@ -445,344 +454,336 @@ export function _createPoolSend( body: BatchPoolCreateOptions, options: CreatePoolOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - vmSize: body["vmSize"], - cloudServiceConfiguration: !body.cloudServiceConfiguration + return context.path("/pools").post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + vmSize: body["vmSize"], + cloudServiceConfiguration: !body.cloudServiceConfiguration + ? undefined + : { + osFamily: body.cloudServiceConfiguration?.["osFamily"], + osVersion: body.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.virtualMachineConfiguration?.imageReference["publisher"], + offer: body.virtualMachineConfiguration?.imageReference["offer"], + sku: body.virtualMachineConfiguration?.imageReference["sku"], + version: + body.virtualMachineConfiguration?.imageReference["version"], + virtualMachineImageId: + body.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + }, + nodeAgentSKUId: + body.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !body.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.virtualMachineConfiguration?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: body.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.virtualMachineConfiguration?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.virtualMachineConfiguration?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + diskEncryptionConfiguration: !body.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], + }, + nodePlacementConfiguration: !body.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + body.virtualMachineConfiguration?.["extensions"] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: p["provisionAfterExtensions"], + })), + osDisk: !body.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings?.["placement"], + }, + }, + }, + resizeTimeout: body["resizeTimeout"], + targetDedicatedNodes: body["targetDedicatedNodes"], + targetLowPriorityNodes: body["targetLowPriorityNodes"], + enableAutoScale: body["enableAutoScale"], + autoScaleFormula: body["autoScaleFormula"], + autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], + enableInterNodeCommunication: body["enableInterNodeCommunication"], + networkConfiguration: !body.networkConfiguration + ? undefined + : { + subnetId: body.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.networkConfiguration?.["dynamicVNetAssignmentScope"], + endpointConfiguration: !body.networkConfiguration + ?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.networkConfiguration?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: p["frontendPortRangeStart"], + frontendPortRangeEnd: p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.networkConfiguration?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.networkConfiguration?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.networkConfiguration?.["enableAcceleratedNetworking"], + }, + startTask: !body.startTask + ? undefined + : { + commandLine: body.startTask?.["commandLine"], + containerSettings: !body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.startTask?.containerSettings?.["containerRunOptions"], + imageName: body.startTask?.containerSettings?.["imageName"], + registry: !body.startTask?.containerSettings?.registry + ? undefined + : { + username: + body.startTask?.containerSettings?.registry?.[ + "username" + ], + password: + body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.startTask?.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !body.startTask?.userIdentity + ? undefined + : { + username: body.startTask?.userIdentity?.["username"], + autoUser: !body.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.startTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], + waitForSuccess: body.startTask?.["waitForSuccess"], + }, + certificateReferences: (body["certificateReferences"] ?? []).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: body["applicationLicenses"], + taskSlotsPerNode: body["taskSlotsPerNode"], + taskSchedulingPolicy: !body.taskSchedulingPolicy + ? undefined + : { nodeFillType: body.taskSchedulingPolicy?.["nodeFillType"] }, + userAccounts: (body["userAccounts"] ?? []).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined : { - osFamily: body.cloudServiceConfiguration?.["osFamily"], - osVersion: body.cloudServiceConfiguration?.["osVersion"], + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], }, - virtualMachineConfiguration: !body.virtualMachineConfiguration + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, + })), + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: (body["mountConfiguration"] ?? []).map((p) => ({ + azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration ? undefined : { - imageReference: { - publisher: - body.virtualMachineConfiguration?.imageReference["publisher"], - offer: - body.virtualMachineConfiguration?.imageReference["offer"], - sku: body.virtualMachineConfiguration?.imageReference["sku"], - version: - body.virtualMachineConfiguration?.imageReference["version"], - virtualMachineImageId: - body.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !body.virtualMachineConfiguration - ?.windowsConfiguration + accountName: p.azureBlobFileSystemConfiguration?.["accountName"], + containerName: + p.azureBlobFileSystemConfiguration?.["containerName"], + accountKey: p.azureBlobFileSystemConfiguration?.["accountKey"], + sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.["relativeMountPath"], + identityReference: !p.azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - enableAutomaticUpdates: - body.virtualMachineConfiguration?.windowsConfiguration?.[ - "enableAutomaticUpdates" + resourceId: + p.azureBlobFileSystemConfiguration?.identityReference?.[ + "resourceId" ], }, - dataDisks: ( - body.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: body.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.virtualMachineConfiguration - ?.containerConfiguration?.["containerImageNames"], - containerRegistries: ( - body.virtualMachineConfiguration - ?.containerConfiguration?.["containerRegistries"] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - diskEncryptionConfiguration: !body.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !body.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.virtualMachineConfiguration?.["extensions"] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: p["provisionAfterExtensions"], - })), - osDisk: !body.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.["placement"], - }, - }, }, - resizeTimeout: body["resizeTimeout"], - targetDedicatedNodes: body["targetDedicatedNodes"], - targetLowPriorityNodes: body["targetLowPriorityNodes"], - enableAutoScale: body["enableAutoScale"], - autoScaleFormula: body["autoScaleFormula"], - autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], - enableInterNodeCommunication: body["enableInterNodeCommunication"], - networkConfiguration: !body.networkConfiguration + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - subnetId: body.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !body.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.networkConfiguration?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.networkConfiguration?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.networkConfiguration?.["enableAcceleratedNetworking"], + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: p.nfsMountConfiguration?.["mountOptions"], }, - startTask: !body.startTask + cifsMountConfiguration: !p.cifsMountConfiguration ? undefined : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], }, - certificateReferences: (body["certificateReferences"] ?? []).map( - (p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }) - ), - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: body["applicationLicenses"], - taskSlotsPerNode: body["taskSlotsPerNode"], - taskSchedulingPolicy: !body.taskSchedulingPolicy + azureFileShareConfiguration: !p.azureFileShareConfiguration ? undefined - : { nodeFillType: body.taskSchedulingPolicy?.["nodeFillType"] }, - userAccounts: (body["userAccounts"] ?? []).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, - })), - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: (body["mountConfiguration"] ?? []).map((p) => ({ - azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.["accountName"], - containerName: - p.azureBlobFileSystemConfiguration?.["containerName"], - accountKey: p.azureBlobFileSystemConfiguration?.["accountKey"], - sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.["relativeMountPath"], - identityReference: !p.azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: !p.azureFileShareConfiguration - ? undefined - : { - accountName: p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.["relativeMountPath"], - mountOptions: p.azureFileShareConfiguration?.["mountOptions"], - }, - })), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, - }); + : { + accountName: p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.["relativeMountPath"], + mountOptions: p.azureFileShareConfiguration?.["mountOptions"], + }, + })), + targetNodeCommunicationMode: body["targetNodeCommunicationMode"], + }, + }); } export async function _createPoolDeserialize( @@ -813,18 +814,16 @@ export function _listPoolsSend( context: Client, options: ListPoolsOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/pools").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _listPoolsDeserialize( @@ -1257,12 +1256,16 @@ export async function _listPoolsDeserialize( } /** Lists all of the Pools in the specified Account. */ -export async function listPools( +export function listPools( context: Client, options: ListPoolsOptions = { requestOptions: {} } -): Promise { - const result = await _listPoolsSend(context, options); - return _listPoolsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listPoolsSend, + _listPoolsDeserialize, + [context, options] + ); } export function _deletePoolSend( @@ -1270,26 +1273,24 @@ export function _deletePoolSend( poolId: string, options: DeletePoolOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}", poolId) - .delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/pools/{poolId}", poolId).delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _deletePoolDeserialize( @@ -1332,26 +1333,24 @@ export function _poolExistsSend( ): StreamableMethod< PoolExists200Response | PoolExists404Response | PoolExistsDefaultResponse > { - return context - .path("/pools/{poolId}", poolId) - .head({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/pools/{poolId}", poolId).head({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _poolExistsDeserialize( @@ -1382,30 +1381,28 @@ export function _getPoolSend( poolId: string, options: GetPoolOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}", poolId) - .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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/pools/{poolId}", poolId).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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _getPoolDeserialize( @@ -1875,124 +1872,117 @@ export function _updatePoolSend( body: BatchPoolUpdateOptions, options: UpdatePoolOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}", poolId) - .patch({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + return context.path("/pools/{poolId}", poolId).patch({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + startTask: !body.startTask + ? undefined + : { + commandLine: body.startTask?.["commandLine"], + containerSettings: !body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.startTask?.containerSettings?.["containerRunOptions"], + imageName: body.startTask?.containerSettings?.["imageName"], + registry: !body.startTask?.containerSettings?.registry ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, - certificateReferences: (body["certificateReferences"] ?? []).map( - (p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }) - ), - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, - }); + : { + username: + body.startTask?.containerSettings?.registry?.[ + "username" + ], + password: + body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.startTask?.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !body.startTask?.userIdentity + ? undefined + : { + username: body.startTask?.userIdentity?.["username"], + autoUser: !body.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.startTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], + waitForSuccess: body.startTask?.["waitForSuccess"], + }, + certificateReferences: (body["certificateReferences"] ?? []).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + targetNodeCommunicationMode: body["targetNodeCommunicationMode"], + }, + }); } export async function _updatePoolDeserialize( @@ -2027,12 +2017,10 @@ export function _disablePoolAutoScaleSend( ): StreamableMethod< DisablePoolAutoScale200Response | DisablePoolAutoScaleDefaultResponse > { - return context - .path("/pools/{poolId}/disableautoscale", poolId) - .post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/pools/{poolId}/disableautoscale", poolId).post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _disablePoolAutoScaleDeserialize( @@ -2063,33 +2051,30 @@ export function _enablePoolAutoScaleSend( ): StreamableMethod< EnablePoolAutoScale200Response | EnablePoolAutoScaleDefaultResponse > { - return context - .path("/pools/{poolId}/enableautoscale", poolId) - .post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - autoScaleFormula: body["autoScaleFormula"], - autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], - }, - }); + return context.path("/pools/{poolId}/enableautoscale", poolId).post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + autoScaleFormula: body["autoScaleFormula"], + autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], + }, + }); } export async function _enablePoolAutoScaleDeserialize( @@ -2128,16 +2113,13 @@ export function _evaluatePoolAutoScaleSend( ): StreamableMethod< EvaluatePoolAutoScale200Response | EvaluatePoolAutoScaleDefaultResponse > { - return context - .path("/pools/{poolId}/evaluateautoscale", poolId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { autoScaleFormula: body["autoScaleFormula"] }, - }); + return context.path("/pools/{poolId}/evaluateautoscale", poolId).post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { autoScaleFormula: body["autoScaleFormula"] }, + }); } export async function _evaluatePoolAutoScaleDeserialize( @@ -2191,35 +2173,32 @@ export function _resizePoolSend( body: BatchPoolResizeOptions, options: ResizePoolOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}/resize", poolId) - .post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - targetDedicatedNodes: body["targetDedicatedNodes"], - targetLowPriorityNodes: body["targetLowPriorityNodes"], - resizeTimeout: body["resizeTimeout"], - nodeDeallocationOption: body["nodeDeallocationOption"], - }, - }); + return context.path("/pools/{poolId}/resize", poolId).post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + targetDedicatedNodes: body["targetDedicatedNodes"], + targetLowPriorityNodes: body["targetLowPriorityNodes"], + resizeTimeout: body["resizeTimeout"], + nodeDeallocationOption: body["nodeDeallocationOption"], + }, + }); } export async function _resizePoolDeserialize( @@ -2256,26 +2235,24 @@ export function _stopPoolResizeSend( poolId: string, options: StopPoolResizeOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}/stopresize", poolId) - .post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/pools/{poolId}/stopresize", poolId).post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _stopPoolResizeDeserialize( @@ -2314,135 +2291,128 @@ export function _replacePoolPropertiesSend( ): StreamableMethod< ReplacePoolProperties204Response | ReplacePoolPropertiesDefaultResponse > { - return context - .path("/pools/{poolId}/updateproperties", poolId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + return context.path("/pools/{poolId}/updateproperties", poolId).post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + startTask: !body.startTask + ? undefined + : { + commandLine: body.startTask?.["commandLine"], + containerSettings: !body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.startTask?.containerSettings?.["containerRunOptions"], + imageName: body.startTask?.containerSettings?.["imageName"], + registry: !body.startTask?.containerSettings?.registry ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, - certificateReferences: (body["certificateReferences"] ?? []).map( - (p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }) - ), - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, - }); -} - -export async function _replacePoolPropertiesDeserialize( - result: - | ReplacePoolProperties204Response - | ReplacePoolPropertiesDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - poolId: string, - body: BatchPoolReplaceOptions, - options: ReplacePoolPropertiesOptions = { requestOptions: {} } -): Promise { + : { + username: + body.startTask?.containerSettings?.registry?.[ + "username" + ], + password: + body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.startTask?.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !body.startTask?.userIdentity + ? undefined + : { + username: body.startTask?.userIdentity?.["username"], + autoUser: !body.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.startTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], + waitForSuccess: body.startTask?.["waitForSuccess"], + }, + certificateReferences: (body["certificateReferences"] ?? []).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + targetNodeCommunicationMode: body["targetNodeCommunicationMode"], + }, + }); +} + +export async function _replacePoolPropertiesDeserialize( + result: + | ReplacePoolProperties204Response + | ReplacePoolPropertiesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + poolId: string, + body: BatchPoolReplaceOptions, + options: ReplacePoolPropertiesOptions = { requestOptions: {} } +): Promise { const result = await _replacePoolPropertiesSend( context, poolId, @@ -2458,34 +2428,31 @@ export function _removeNodesSend( body: NodeRemoveOptions, options: RemoveNodesOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}/removenodes", poolId) - .post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - nodeList: body["nodeList"], - resizeTimeout: body["resizeTimeout"], - nodeDeallocationOption: body["nodeDeallocationOption"], - }, - }); + return context.path("/pools/{poolId}/removenodes", poolId).post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + nodeList: body["nodeList"], + resizeTimeout: body["resizeTimeout"], + nodeDeallocationOption: body["nodeDeallocationOption"], + }, + }); } export async function _removeNodesDeserialize( @@ -2519,16 +2486,14 @@ export function _listSupportedImagesSend( ): StreamableMethod< ListSupportedImages200Response | ListSupportedImagesDefaultResponse > { - return context - .path("/supportedimages") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - }, - }); + return context.path("/supportedimages").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + }, + }); } export async function _listSupportedImagesDeserialize( @@ -2562,12 +2527,16 @@ export async function _listSupportedImagesDeserialize( } /** Lists all Virtual Machine Images supported by the Azure Batch service. */ -export async function listSupportedImages( +export function listSupportedImages( context: Client, options: ListSupportedImagesOptions = { requestOptions: {} } -): Promise { - const result = await _listSupportedImagesSend(context, options); - return _listSupportedImagesDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listSupportedImagesSend, + _listSupportedImagesDeserialize, + [context, options] + ); } export function _listPoolNodeCountsSend( @@ -2576,16 +2545,14 @@ export function _listPoolNodeCountsSend( ): StreamableMethod< ListPoolNodeCounts200Response | ListPoolNodeCountsDefaultResponse > { - return context - .path("/nodecounts") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - }, - }); + return context.path("/nodecounts").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + }, + }); } export async function _listPoolNodeCountsDeserialize( @@ -2644,12 +2611,16 @@ export async function _listPoolNodeCountsDeserialize( * numbers returned may not always be up to date. If you need exact node counts, * use a list query. */ -export async function listPoolNodeCounts( +export function listPoolNodeCounts( context: Client, options: ListPoolNodeCountsOptions = { requestOptions: {} } -): Promise { - const result = await _listPoolNodeCountsSend(context, options); - return _listPoolNodeCountsDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listPoolNodeCountsSend, + _listPoolNodeCountsDeserialize, + [context, options] + ); } export function _deleteJobSend( @@ -2657,26 +2628,24 @@ export function _deleteJobSend( jobId: string, options: DeleteJobOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}", jobId) - .delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/jobs/{jobId}", jobId).delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _deleteJobDeserialize( @@ -2713,30 +2682,28 @@ export function _getJobSend( jobId: string, options: GetJobOptions = { 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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + 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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _getJobDeserialize( @@ -3693,1379 +3660,632 @@ export function _updateJobSend( body: BatchJobUpdateOptions, options: UpdateJobOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}", jobId) - .patch({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - poolInfo: !body.poolInfo - ? undefined - : { - poolId: body.poolInfo?.["poolId"], - autoPoolSpecification: !body.poolInfo?.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo?.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.poolInfo?.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.poolInfo?.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo?.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - }, - nodeAgentSKUId: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( + return context.path("/jobs/{jobId}", jobId).patch({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + poolInfo: !body.poolInfo + ? undefined + : { + poolId: body.poolInfo?.["poolId"], + autoPoolSpecification: !body.poolInfo?.autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.poolInfo?.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + body.poolInfo?.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.poolInfo?.autoPoolSpecification?.["keepAlive"], + pool: !body.poolInfo?.autoPoolSpecification?.pool + ? undefined + : { + displayName: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "displayName" + ], + vmSize: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "vmSize" + ], + cloudServiceConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.poolInfo?.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.poolInfo?.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + }, + nodeAgentSKUId: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference ? undefined : { - placement: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" + resourceId: + p.identityReference?.[ + "resourceId" ], }, - }, - }, - taskSlotsPerNode: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo - ?.autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo?.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.poolInfo?.autoPoolSpecification - ?.pool?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.poolInfo?.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.poolInfo?.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo?.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - ?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration + })), + }, + diskEncryptionConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration ? undefined : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], + targets: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], }, - })), - metadata: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "metadata" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + nodePlacementConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" + policy: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference + }, + extensions: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings ? undefined : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" + placement: + body.poolInfo?.autoPoolSpecification + ?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" ], }, }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + }, + taskSlotsPerNode: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !body.poolInfo + ?.autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + body.poolInfo?.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], + targetDedicatedNodes: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" + inboundNATPools: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" + ipAddressIds: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" + }, + enableAcceleratedNetworking: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !body.poolInfo?.autoPoolSpecification?.pool + ?.startTask + ? undefined + : { + commandLine: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" + imageName: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" + registry: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "username" + ], + password: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.poolInfo + ?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" ], }, - })), - targetNodeCommunicationMode: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _updateJobDeserialize( - result: UpdateJob200Response | UpdateJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptions = { requestOptions: {} } -): Promise { - const result = await _updateJobSend(context, jobId, body, options); - return _updateJobDeserialize(result); -} - -export function _replaceJobSend( - context: Client, - jobId: string, - body: BatchJob, - options: ReplaceJobOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/jobs/{jobId}", jobId) - .put({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - poolInfo: { - poolId: body.poolInfo["poolId"], - autoPoolSpecification: !body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? - [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference + resourceFiles: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser ? undefined : { - resourceId: - p.identityReference?.["resourceId"], + scope: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration + }, + maxTaskRetryCount: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], + }, + certificateReferences: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "metadata" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration ? undefined : { - targets: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" ], - }, - nodePlacementConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - placement: - body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], }, }, - }, - taskSlotsPerNode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], + source: p.nfsMountConfiguration?.["source"], relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ + p.nfsMountConfiguration?.[ "relativeMountPath" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + cifsMountConfiguration: !p.cifsMountConfiguration ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], + username: + p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], relativeMountPath: - p.azureFileShareConfiguration?.[ + p.cifsMountConfiguration?.[ "relativeMountPath" ], mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], + p.cifsMountConfiguration?.["mountOptions"], + password: + p.cifsMountConfiguration?.["password"], }, - })), - targetNodeCommunicationMode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _replaceJobDeserialize( - result: ReplaceJob200Response | ReplaceJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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, - body: BatchJob, - options: ReplaceJobOptions = { requestOptions: {} } -): Promise { - const result = await _replaceJobSend(context, jobId, body, options); - return _replaceJobDeserialize(result); -} - -export function _disableJobSend( - context: Client, - jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/jobs/{jobId}/disable", jobId) - .post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { disableTasks: body["disableTasks"] }, - }); -} - -export async function _disableJobDeserialize( - result: DisableJob202Response | DisableJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptions = { requestOptions: {} } -): Promise { - const result = await _disableJobSend(context, jobId, body, options); - return _disableJobDeserialize(result); -} - -export function _enableJobSend( - context: Client, - jobId: string, - options: EnableJobOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/jobs/{jobId}/enable", jobId) - .post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + onAllTasksComplete: body["onAllTasksComplete"], + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); } -export async function _enableJobDeserialize( - result: EnableJob202Response | EnableJobDefaultResponse +export async function _updateJobDeserialize( + result: UpdateJob200Response | UpdateJobDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -5075,995 +4295,598 @@ 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. + * 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 enableJob( - context: Client, - jobId: string, - options: EnableJobOptions = { requestOptions: {} } -): Promise { - const result = await _enableJobSend(context, jobId, options); - return _enableJobDeserialize(result); -} - -export function _terminateJobSend( +export async function updateJob( context: Client, jobId: string, - body: BatchJobTerminateOptions, - options: TerminateJobOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/jobs/{jobId}/terminate", jobId) - .post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { terminateReason: body["terminateReason"] }, - }); -} - -export async function _terminateJobDeserialize( - result: TerminateJob202Response | TerminateJobDefaultResponse + body: BatchJobUpdateOptions, + options: UpdateJobOptions = { requestOptions: {} } ): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; + const result = await _updateJobSend(context, jobId, body, options); + return _updateJobDeserialize(result); } -/** - * 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( +export function _replaceJobSend( context: Client, jobId: string, - body: BatchJobTerminateOptions, - options: TerminateJobOptions = { requestOptions: {} } -): Promise { - const result = await _terminateJobSend(context, jobId, body, options); - return _terminateJobDeserialize(result); -} - -export function _createJobSend( - context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/jobs") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - usesTaskDependencies: body["usesTaskDependencies"], - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobManagerTask + body: BatchJob, + options: ReplaceJobOptions = { requestOptions: {} } +): StreamableMethod { + return context.path("/jobs/{jobId}", jobId).put({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + poolInfo: { + poolId: body.poolInfo["poolId"], + autoPoolSpecification: !body.poolInfo.autoPoolSpecification ? undefined : { - id: body.jobManagerTask?.["id"], - displayName: body.jobManagerTask?.["displayName"], - commandLine: body.jobManagerTask?.["commandLine"], - containerSettings: !body.jobManagerTask?.containerSettings + autoPoolIdPrefix: + body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !body.poolInfo.autoPoolSpecification?.pool ? undefined : { - containerRunOptions: - body.jobManagerTask?.containerSettings?.[ - "containerRunOptions" + displayName: + body.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" ], - imageName: - body.jobManagerTask?.containerSettings?.["imageName"], - registry: !body.jobManagerTask?.containerSettings?.registry + vmSize: + body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration ? undefined : { - username: - body.jobManagerTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.jobManagerTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.jobManagerTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobManagerTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobManagerTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, + osFamily: + body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], }, - workingDirectory: - body.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: (body.jobManagerTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - outputFiles: (body.jobManagerTask?.["outputFiles"] ?? []).map( - (p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + virtualMachineConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.virtualMachineConfiguration ? undefined : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference + imageReference: { + publisher: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" + ], + sku: body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + }, + nodeAgentSKUId: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.windowsConfiguration ? undefined : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" + enableAutomaticUpdates: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" ], + containerRegistries: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + }, + diskEncryptionConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], + }, + nodePlacementConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] + extensions: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] ).map((p) => ({ name: p["name"], - value: p["value"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], })), + osDisk: !body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }) - ), - environmentSettings: ( - body.jobManagerTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobManagerTask?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: body.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: body.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobManagerTask?.userIdentity - ? undefined - : { - username: body.jobManagerTask?.userIdentity?.["username"], - autoUser: !body.jobManagerTask?.userIdentity?.autoUser + taskSlotsPerNode: + body.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification + ?.pool?.taskSchedulingPolicy ? undefined : { - scope: - body.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], + nodeFillType: + body.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], }, - }, - runExclusive: body.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobManagerTask?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - body.jobManagerTask?.authenticationTokenSettings?.[ - "access" + resizeTimeout: + body.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" ], - }, - allowLowPriorityNode: - body.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !body.jobPreparationTask - ? undefined - : { - id: body.jobPreparationTask?.["id"], - commandLine: body.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" + targetDedicatedNodes: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" ], - imageName: - body.jobPreparationTask?.containerSettings?.["imageName"], - registry: !body.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - body.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.jobPreparationTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobPreparationTask?.containerSettings?.[ - "workingDirectory" + targetLowPriorityNodes: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" ], - }, - resourceFiles: ( - body.jobPreparationTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobPreparationTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobPreparationTask?.constraints?.[ - "maxWallClockTime" + enableAutoScale: + body.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" ], - retentionTime: - body.jobPreparationTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" + autoScaleFormula: + body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" ], - }, - waitForSuccess: body.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobPreparationTask?.userIdentity - ? undefined - : { - username: - body.jobPreparationTask?.userIdentity?.["username"], - autoUser: !body.jobPreparationTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobPreparationTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobPreparationTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !body.jobReleaseTask - ? undefined - : { - id: body.jobReleaseTask?.["id"], - commandLine: body.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" + autoScaleEvaluationInterval: + body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" ], - imageName: - body.jobReleaseTask?.containerSettings?.["imageName"], - registry: !body.jobReleaseTask?.containerSettings?.registry + enableInterNodeCommunication: + body.poolInfo.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration ? undefined : { - username: - body.jobReleaseTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.jobReleaseTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.jobReleaseTask?.containerSettings?.registry?.[ - "registryServer" + subnetId: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" ], - identityReference: !body.jobReleaseTask - ?.containerSettings?.registry?.identityReference + endpointConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.endpointConfiguration ? undefined : { - resourceId: - body.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" + inboundNATPools: ( + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" ], }, + enableAcceleratedNetworking: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], }, - workingDirectory: - body.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: (body.jobReleaseTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.jobReleaseTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: body.jobReleaseTask?.["maxWallClockTime"], - retentionTime: body.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobReleaseTask?.userIdentity - ? undefined - : { - username: body.jobReleaseTask?.userIdentity?.["username"], - autoUser: !body.jobReleaseTask?.userIdentity?.autoUser + startTask: !body.poolInfo.autoPoolSpecification?.pool + ?.startTask ? undefined : { - scope: - body.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], + commandLine: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings?.registry + ? undefined + : { + username: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ? undefined + : { + username: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], }, - }, - }, - commonEnvironmentSettings: ( - body["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.poolInfo["poolId"], - autoPoolSpecification: !body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration + certificateReferences: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined : { - osFamily: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], }, - virtualMachineConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration + windowsUserConfiguration: !p.windowsUserConfiguration ? undefined : { - imageReference: { - publisher: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" ], - offer: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" ], - sku: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" ], - virtualMachineImageId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" + sasKey: + p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, }, - nodeAgentSKUId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? - [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - nodeFillType: - body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - resizeTimeout: - body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration + cifsMountConfiguration: !p.cifsMountConfiguration ? undefined : { - subnetId: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], }, - startTask: !body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration + azureFileShareConfiguration: + !p.azureFileShareConfiguration ? undefined : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], + accountName: + p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: + p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], + p.azureFileShareConfiguration?.["mountOptions"], }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - onTaskFailure: body["onTaskFailure"], - networkConfiguration: !body.networkConfiguration - ? undefined - : { subnetId: body.networkConfiguration?.["subnetId"] }, - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), + })), + targetNodeCommunicationMode: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, }, - }); + onAllTasksComplete: body["onAllTasksComplete"], + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); } -export async function _createJobDeserialize( - result: CreateJob201Response | CreateJobDefaultResponse +export async function _replaceJobDeserialize( + result: ReplaceJob200Response | ReplaceJobDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -6073,126 +4896,256 @@ export async function _createJobDeserialize( } /** - * 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. + * 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 createJob( +export async function replaceJob( context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptions = { requestOptions: {} } + jobId: string, + body: BatchJob, + options: ReplaceJobOptions = { requestOptions: {} } ): Promise { - const result = await _createJobSend(context, body, options); - return _createJobDeserialize(result); + const result = await _replaceJobSend(context, jobId, body, options); + return _replaceJobDeserialize(result); } -export function _listJobsSend( +export function _disableJobSend( context: Client, - options: ListJobsOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/jobs") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + jobId: string, + body: BatchJobDisableOptions, + options: DisableJobOptions = { requestOptions: {} } +): StreamableMethod { + return context.path("/jobs/{jobId}/disable", jobId).post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { disableTasks: body["disableTasks"] }, + }); } -export async function _listJobsDeserialize( - result: ListJobs200Response | ListJobsDefaultResponse -): Promise { +export async function _disableJobDeserialize( + result: DisableJob202Response | DisableJobDefaultResponse +): Promise { if (isUnexpected(result)) { throw result.body; } - return { - value: (result.body["value"] ?? []).map((p) => ({ - id: p["id"], - displayName: p["displayName"], - usesTaskDependencies: p["usesTaskDependencies"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - priority: p["priority"], - allowTaskPreemption: p["allowTaskPreemption"], - maxParallelTasks: p["maxParallelTasks"], - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobManagerTask - ? undefined - : { - id: p.jobManagerTask?.["id"], - displayName: p.jobManagerTask?.["displayName"], - commandLine: p.jobManagerTask?.["commandLine"], - containerSettings: !p.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobManagerTask?.containerSettings?.[ + 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( + context: Client, + jobId: string, + body: BatchJobDisableOptions, + options: DisableJobOptions = { requestOptions: {} } +): Promise { + const result = await _disableJobSend(context, jobId, body, options); + return _disableJobDeserialize(result); +} + +export function _enableJobSend( + context: Client, + jobId: string, + options: EnableJobOptions = { requestOptions: {} } +): StreamableMethod { + return context.path("/jobs/{jobId}/enable", jobId).post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _enableJobDeserialize( + result: EnableJob202Response | EnableJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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 enableJob( + context: Client, + jobId: string, + options: EnableJobOptions = { requestOptions: {} } +): Promise { + const result = await _enableJobSend(context, jobId, options); + return _enableJobDeserialize(result); +} + +export function _terminateJobSend( + context: Client, + jobId: string, + body: BatchJobTerminateOptions, + options: TerminateJobOptions = { requestOptions: {} } +): StreamableMethod { + return context.path("/jobs/{jobId}/terminate", jobId).post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { terminateReason: body["terminateReason"] }, + }); +} + +export async function _terminateJobDeserialize( + result: TerminateJob202Response | TerminateJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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, + body: BatchJobTerminateOptions, + options: TerminateJobOptions = { requestOptions: {} } +): Promise { + const result = await _terminateJobSend(context, jobId, body, options); + return _terminateJobDeserialize(result); +} + +export function _createJobSend( + context: Client, + body: BatchJobCreateOptions, + options: CreateJobOptions = { requestOptions: {} } +): StreamableMethod { + return context.path("/jobs").post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + usesTaskDependencies: body["usesTaskDependencies"], + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobManagerTask + ? undefined + : { + id: body.jobManagerTask?.["id"], + displayName: body.jobManagerTask?.["displayName"], + commandLine: body.jobManagerTask?.["commandLine"], + containerSettings: !body.jobManagerTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobManagerTask?.containerSettings?.[ "containerRunOptions" ], - imageName: p.jobManagerTask?.containerSettings?.["imageName"], - registry: !p.jobManagerTask?.containerSettings?.registry + imageName: + body.jobManagerTask?.containerSettings?.["imageName"], + registry: !body.jobManagerTask?.containerSettings?.registry ? undefined : { username: - p.jobManagerTask?.containerSettings?.registry?.[ + body.jobManagerTask?.containerSettings?.registry?.[ "username" ], password: - p.jobManagerTask?.containerSettings?.registry?.[ + body.jobManagerTask?.containerSettings?.registry?.[ "password" ], registryServer: - p.jobManagerTask?.containerSettings?.registry?.[ + body.jobManagerTask?.containerSettings?.registry?.[ "registryServer" ], - identityReference: !p.jobManagerTask?.containerSettings - ?.registry?.identityReference + identityReference: !body.jobManagerTask + ?.containerSettings?.registry?.identityReference ? undefined : { resourceId: - p.jobManagerTask?.containerSettings?.registry + body.jobManagerTask?.containerSettings?.registry ?.identityReference?.["resourceId"], }, }, workingDirectory: - p.jobManagerTask?.containerSettings?.["workingDirectory"], + body.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], }, - resourceFiles: (p.jobManagerTask?.["resourceFiles"] ?? []).map( + resourceFiles: (body.jobManagerTask?.["resourceFiles"] ?? []).map( (p) => ({ autoStorageContainerName: p["autoStorageContainerName"], storageContainerUrl: p["storageContainerUrl"], @@ -6205,209 +5158,219 @@ export async function _listJobsDeserialize( : { resourceId: p.identityReference?.["resourceId"] }, }) ), - outputFiles: (p.jobManagerTask?.["outputFiles"] ?? []).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), + outputFiles: (body.jobManagerTask?.["outputFiles"] ?? []).map( + (p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + }) + ), environmentSettings: ( - p.jobManagerTask?.["environmentSettings"] ?? [] + body.jobManagerTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !p.jobManagerTask?.constraints + constraints: !body.jobManagerTask?.constraints ? undefined : { maxWallClockTime: - p.jobManagerTask?.constraints?.["maxWallClockTime"], + body.jobManagerTask?.constraints?.["maxWallClockTime"], retentionTime: - p.jobManagerTask?.constraints?.["retentionTime"], + body.jobManagerTask?.constraints?.["retentionTime"], maxTaskRetryCount: - p.jobManagerTask?.constraints?.["maxTaskRetryCount"], + body.jobManagerTask?.constraints?.["maxTaskRetryCount"], }, - requiredSlots: p.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: p.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !p.jobManagerTask?.userIdentity + requiredSlots: body.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: body.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !body.jobManagerTask?.userIdentity ? undefined : { - username: p.jobManagerTask?.userIdentity?.["username"], - autoUser: !p.jobManagerTask?.userIdentity?.autoUser + username: body.jobManagerTask?.userIdentity?.["username"], + autoUser: !body.jobManagerTask?.userIdentity?.autoUser ? undefined : { scope: - p.jobManagerTask?.userIdentity?.autoUser?.["scope"], + body.jobManagerTask?.userIdentity?.autoUser?.[ + "scope" + ], elevationLevel: - p.jobManagerTask?.userIdentity?.autoUser?.[ + body.jobManagerTask?.userIdentity?.autoUser?.[ "elevationLevel" ], }, }, - runExclusive: p.jobManagerTask?.["runExclusive"], + runExclusive: body.jobManagerTask?.["runExclusive"], applicationPackageReferences: ( - p.jobManagerTask?.["applicationPackageReferences"] ?? [] + body.jobManagerTask?.["applicationPackageReferences"] ?? [] ).map((p) => ({ applicationId: p["applicationId"], version: p["version"], })), - authenticationTokenSettings: !p.jobManagerTask + authenticationTokenSettings: !body.jobManagerTask ?.authenticationTokenSettings ? undefined : { access: - p.jobManagerTask?.authenticationTokenSettings?.["access"], + body.jobManagerTask?.authenticationTokenSettings?.[ + "access" + ], }, - allowLowPriorityNode: p.jobManagerTask?.["allowLowPriorityNode"], + allowLowPriorityNode: body.jobManagerTask?.["allowLowPriorityNode"], }, - jobPreparationTask: !p.jobPreparationTask + jobPreparationTask: !body.jobPreparationTask ? undefined : { - id: p.jobPreparationTask?.["id"], - commandLine: p.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobPreparationTask?.containerSettings + id: body.jobPreparationTask?.["id"], + commandLine: body.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobPreparationTask?.containerSettings ? undefined : { containerRunOptions: - p.jobPreparationTask?.containerSettings?.[ + body.jobPreparationTask?.containerSettings?.[ "containerRunOptions" ], imageName: - p.jobPreparationTask?.containerSettings?.["imageName"], - registry: !p.jobPreparationTask?.containerSettings?.registry + body.jobPreparationTask?.containerSettings?.["imageName"], + registry: !body.jobPreparationTask?.containerSettings + ?.registry ? undefined : { username: - p.jobPreparationTask?.containerSettings?.registry?.[ - "username" - ], + body.jobPreparationTask?.containerSettings + ?.registry?.["username"], password: - p.jobPreparationTask?.containerSettings?.registry?.[ - "password" - ], + body.jobPreparationTask?.containerSettings + ?.registry?.["password"], registryServer: - p.jobPreparationTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobPreparationTask + body.jobPreparationTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body.jobPreparationTask ?.containerSettings?.registry?.identityReference ? undefined : { resourceId: - p.jobPreparationTask?.containerSettings + body.jobPreparationTask?.containerSettings ?.registry?.identityReference?.["resourceId"], }, }, workingDirectory: - p.jobPreparationTask?.containerSettings?.[ + body.jobPreparationTask?.containerSettings?.[ "workingDirectory" ], }, - resourceFiles: (p.jobPreparationTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), + resourceFiles: ( + body.jobPreparationTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), environmentSettings: ( - p.jobPreparationTask?.["environmentSettings"] ?? [] + body.jobPreparationTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !p.jobPreparationTask?.constraints + constraints: !body.jobPreparationTask?.constraints ? undefined : { maxWallClockTime: - p.jobPreparationTask?.constraints?.["maxWallClockTime"], + body.jobPreparationTask?.constraints?.["maxWallClockTime"], retentionTime: - p.jobPreparationTask?.constraints?.["retentionTime"], + body.jobPreparationTask?.constraints?.["retentionTime"], maxTaskRetryCount: - p.jobPreparationTask?.constraints?.["maxTaskRetryCount"], + body.jobPreparationTask?.constraints?.["maxTaskRetryCount"], }, - waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], - userIdentity: !p.jobPreparationTask?.userIdentity + waitForSuccess: body.jobPreparationTask?.["waitForSuccess"], + userIdentity: !body.jobPreparationTask?.userIdentity ? undefined : { - username: p.jobPreparationTask?.userIdentity?.["username"], - autoUser: !p.jobPreparationTask?.userIdentity?.autoUser + username: body.jobPreparationTask?.userIdentity?.["username"], + autoUser: !body.jobPreparationTask?.userIdentity?.autoUser ? undefined : { scope: - p.jobPreparationTask?.userIdentity?.autoUser?.[ + body.jobPreparationTask?.userIdentity?.autoUser?.[ "scope" ], elevationLevel: - p.jobPreparationTask?.userIdentity?.autoUser?.[ + body.jobPreparationTask?.userIdentity?.autoUser?.[ "elevationLevel" ], }, }, rerunOnNodeRebootAfterSuccess: - p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], + body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], }, - jobReleaseTask: !p.jobReleaseTask + jobReleaseTask: !body.jobReleaseTask ? undefined : { - id: p.jobReleaseTask?.["id"], - commandLine: p.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobReleaseTask?.containerSettings + id: body.jobReleaseTask?.["id"], + commandLine: body.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobReleaseTask?.containerSettings ? undefined : { containerRunOptions: - p.jobReleaseTask?.containerSettings?.[ + body.jobReleaseTask?.containerSettings?.[ "containerRunOptions" ], - imageName: p.jobReleaseTask?.containerSettings?.["imageName"], - registry: !p.jobReleaseTask?.containerSettings?.registry + imageName: + body.jobReleaseTask?.containerSettings?.["imageName"], + registry: !body.jobReleaseTask?.containerSettings?.registry ? undefined : { username: - p.jobReleaseTask?.containerSettings?.registry?.[ + body.jobReleaseTask?.containerSettings?.registry?.[ "username" ], password: - p.jobReleaseTask?.containerSettings?.registry?.[ + body.jobReleaseTask?.containerSettings?.registry?.[ "password" ], registryServer: - p.jobReleaseTask?.containerSettings?.registry?.[ + body.jobReleaseTask?.containerSettings?.registry?.[ "registryServer" ], - identityReference: !p.jobReleaseTask?.containerSettings - ?.registry?.identityReference + identityReference: !body.jobReleaseTask + ?.containerSettings?.registry?.identityReference ? undefined : { resourceId: - p.jobReleaseTask?.containerSettings?.registry + body.jobReleaseTask?.containerSettings?.registry ?.identityReference?.["resourceId"], }, }, workingDirectory: - p.jobReleaseTask?.containerSettings?.["workingDirectory"], + body.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], }, - resourceFiles: (p.jobReleaseTask?.["resourceFiles"] ?? []).map( + resourceFiles: (body.jobReleaseTask?.["resourceFiles"] ?? []).map( (p) => ({ autoStorageContainerName: p["autoStorageContainerName"], storageContainerUrl: p["storageContainerUrl"], @@ -6421,108 +5384,108 @@ export async function _listJobsDeserialize( }) ), environmentSettings: ( - p.jobReleaseTask?.["environmentSettings"] ?? [] + body.jobReleaseTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], - retentionTime: p.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobReleaseTask?.userIdentity + maxWallClockTime: body.jobReleaseTask?.["maxWallClockTime"], + retentionTime: body.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobReleaseTask?.userIdentity ? undefined : { - username: p.jobReleaseTask?.userIdentity?.["username"], - autoUser: !p.jobReleaseTask?.userIdentity?.autoUser + username: body.jobReleaseTask?.userIdentity?.["username"], + autoUser: !body.jobReleaseTask?.userIdentity?.autoUser ? undefined : { scope: - p.jobReleaseTask?.userIdentity?.autoUser?.["scope"], + body.jobReleaseTask?.userIdentity?.autoUser?.[ + "scope" + ], elevationLevel: - p.jobReleaseTask?.userIdentity?.autoUser?.[ + body.jobReleaseTask?.userIdentity?.autoUser?.[ "elevationLevel" ], }, }, }, - commonEnvironmentSettings: (p["commonEnvironmentSettings"] ?? []).map( + commonEnvironmentSettings: (body["commonEnvironmentSettings"] ?? []).map( (p) => ({ name: p["name"], value: p["value"] }) ), poolInfo: { - poolId: p.poolInfo["poolId"], - autoPoolSpecification: !p.poolInfo.autoPoolSpecification + poolId: body.poolInfo["poolId"], + autoPoolSpecification: !body.poolInfo.autoPoolSpecification ? undefined : { autoPoolIdPrefix: - p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], poolLifetimeOption: - p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !body.poolInfo.autoPoolSpecification?.pool ? undefined : { displayName: - p.poolInfo.autoPoolSpecification?.pool?.["displayName"], - vmSize: p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !p.poolInfo.autoPoolSpecification - ?.pool?.cloudServiceConfiguration + body.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" + ], + vmSize: + body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration ? undefined : { osFamily: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.cloudServiceConfiguration?.["osFamily"], osVersion: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.cloudServiceConfiguration?.["osVersion"], }, - virtualMachineConfiguration: !p.poolInfo + virtualMachineConfiguration: !body.poolInfo .autoPoolSpecification?.pool?.virtualMachineConfiguration ? undefined : { imageReference: { publisher: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "publisher" ], offer: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "offer" ], - sku: p.poolInfo.autoPoolSpecification?.pool + sku: body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "sku" ], version: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "version" ], virtualMachineImageId: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "virtualMachineImageId" ], - exactVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], }, nodeAgentSKUId: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !p.poolInfo + windowsConfiguration: !body.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.windowsConfiguration ? undefined : { enableAutomaticUpdates: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.windowsConfiguration?.[ "enableAutomaticUpdates" ], }, dataDisks: ( - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["dataDisks"] ?? [] ).map((p) => ({ lun: p["lun"], @@ -6531,25 +5494,25 @@ export async function _listJobsDeserialize( storageAccountType: p["storageAccountType"], })), licenseType: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !p.poolInfo + containerConfiguration: !body.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration ? undefined : { - type: p.poolInfo.autoPoolSpecification?.pool + type: body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.["type"], containerImageNames: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.[ "containerImageNames" ], containerRegistries: ( - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.[ "containerRegistries" @@ -6566,30 +5529,30 @@ export async function _listJobsDeserialize( }, })), }, - diskEncryptionConfiguration: !p.poolInfo + diskEncryptionConfiguration: !body.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.diskEncryptionConfiguration ? undefined : { targets: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.diskEncryptionConfiguration?.["targets"], }, - nodePlacementConfiguration: !p.poolInfo + nodePlacementConfiguration: !body.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.nodePlacementConfiguration ? undefined : { policy: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.nodePlacementConfiguration?.["policy"], }, extensions: ( - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["extensions"] ?? [] ).map((p) => ({ @@ -6605,82 +5568,84 @@ export async function _listJobsDeserialize( provisionAfterExtensions: p["provisionAfterExtensions"], })), - osDisk: !p.poolInfo.autoPoolSpecification?.pool + osDisk: !body.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ? undefined : { - ephemeralOSDiskSettings: !p.poolInfo + ephemeralOSDiskSettings: !body.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ?.ephemeralOSDiskSettings ? undefined : { placement: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.[ + body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ "placement" ], }, }, }, taskSlotsPerNode: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "taskSlotsPerNode" ], - taskSchedulingPolicy: !p.poolInfo.autoPoolSpecification + taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification ?.pool?.taskSchedulingPolicy ? undefined : { nodeFillType: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.taskSchedulingPolicy?.["nodeFillType"], }, resizeTimeout: - p.poolInfo.autoPoolSpecification?.pool?.["resizeTimeout"], + body.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], targetDedicatedNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "targetDedicatedNodes" ], targetLowPriorityNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "targetLowPriorityNodes" ], enableAutoScale: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "enableAutoScale" ], autoScaleFormula: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "autoScaleFormula" ], autoScaleEvaluationInterval: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "autoScaleEvaluationInterval" ], enableInterNodeCommunication: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "enableInterNodeCommunication" ], - networkConfiguration: !p.poolInfo.autoPoolSpecification + networkConfiguration: !body.poolInfo.autoPoolSpecification ?.pool?.networkConfiguration ? undefined : { subnetId: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.["subnetId"], dynamicVNetAssignmentScope: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.[ "dynamicVNetAssignmentScope" ], - endpointConfiguration: !p.poolInfo + endpointConfiguration: !body.poolInfo .autoPoolSpecification?.pool?.networkConfiguration ?.endpointConfiguration ? undefined : { inboundNATPools: ( - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.endpointConfiguration?.[ "inboundNATPools" @@ -6704,93 +5669,92 @@ export async function _listJobsDeserialize( })), })), }, - publicIPAddressConfiguration: !p.poolInfo + publicIPAddressConfiguration: !body.poolInfo .autoPoolSpecification?.pool?.networkConfiguration ?.publicIPAddressConfiguration ? undefined : { provision: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.publicIPAddressConfiguration?.[ "provision" ], ipAddressIds: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.publicIPAddressConfiguration?.[ "ipAddressIds" ], }, enableAcceleratedNetworking: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.[ "enableAcceleratedNetworking" ], }, - startTask: !p.poolInfo.autoPoolSpecification?.pool + startTask: !body.poolInfo.autoPoolSpecification?.pool ?.startTask ? undefined : { commandLine: - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings ? undefined : { containerRunOptions: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings?.[ "containerRunOptions" ], imageName: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings?.[ "imageName" ], - registry: !p.poolInfo.autoPoolSpecification + registry: !body.poolInfo.autoPoolSpecification ?.pool?.startTask?.containerSettings?.registry ? undefined : { username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings ?.registry?.["username"], password: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings ?.registry?.["password"], registryServer: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings ?.registry?.["registryServer"], - identityReference: !p.poolInfo + identityReference: !body.poolInfo .autoPoolSpecification?.pool?.startTask ?.containerSettings?.registry ?.identityReference ? undefined : { resourceId: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference?.[ + body.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference?.[ "resourceId" ], }, }, workingDirectory: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings?.[ "workingDirectory" ], }, resourceFiles: ( - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] ).map((p) => ({ autoStorageContainerName: p["autoStorageContainerName"], @@ -6807,47 +5771,42 @@ export async function _listJobsDeserialize( }, })), environmentSettings: ( - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"], })), - userIdentity: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity + userIdentity: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity ? undefined : { username: - p.poolInfo.autoPoolSpecification?.pool + body.poolInfo.autoPoolSpecification?.pool ?.startTask?.userIdentity?.["username"], - autoUser: !p.poolInfo.autoPoolSpecification + autoUser: !body.poolInfo.autoPoolSpecification ?.pool?.startTask?.userIdentity?.autoUser ? undefined : { scope: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "scope" - ], + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], elevationLevel: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], }, }, maxTaskRetryCount: - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], waitForSuccess: - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], }, certificateReferences: ( - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "certificateReferences" ] ?? [] ).map((p) => ({ @@ -6858,7 +5817,7 @@ export async function _listJobsDeserialize( visibility: p["visibility"], })), applicationPackageReferences: ( - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "applicationPackageReferences" ] ?? [] ).map((p) => ({ @@ -6866,11 +5825,11 @@ export async function _listJobsDeserialize( version: p["version"], })), applicationLicenses: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "applicationLicenses" ], userAccounts: ( - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "userAccounts" ] ?? [] ).map((p) => ({ @@ -6893,10 +5852,11 @@ export async function _listJobsDeserialize( }, })), metadata: ( - p.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? [] + body.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? + [] ).map((p) => ({ name: p["name"], value: p["value"] })), mountConfiguration: ( - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "mountConfiguration" ] ?? [] ).map((p) => ({ @@ -6975,98 +5935,74 @@ export async function _listJobsDeserialize( }, })), targetNodeCommunicationMode: - p.poolInfo.autoPoolSpecification?.pool?.[ + body.poolInfo.autoPoolSpecification?.pool?.[ "targetNodeCommunicationMode" ], }, }, }, - onAllTasksComplete: p["onAllTasksComplete"], - onTaskFailure: p["onTaskFailure"], - networkConfiguration: !p.networkConfiguration + onAllTasksComplete: body["onAllTasksComplete"], + onTaskFailure: body["onTaskFailure"], + networkConfiguration: !body.networkConfiguration ? undefined - : { subnetId: p.networkConfiguration?.["subnetId"] }, - metadata: (p["metadata"] ?? []).map((p) => ({ + : { subnetId: body.networkConfiguration?.["subnetId"] }, + metadata: (body["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: p.executionInfo?.schedulingError?.["message"], - details: ( - p.executionInfo?.schedulingError?.["details"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; + }, + }); } -/** Lists all of the Jobs in the specified Account. */ -export async function listJobs( +export async function _createJobDeserialize( + result: CreateJob201Response | CreateJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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( context: Client, - options: ListJobsOptions = { requestOptions: {} } -): Promise { - const result = await _listJobsSend(context, options); - return _listJobsDeserialize(result); + body: BatchJobCreateOptions, + options: CreateJobOptions = { requestOptions: {} } +): Promise { + const result = await _createJobSend(context, body, options); + return _createJobDeserialize(result); } -export function _listJobsFromScheduleSend( +export function _listJobsSend( context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptions = { requestOptions: {} } -): StreamableMethod< - ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + options: ListJobsOptions = { requestOptions: {} } +): StreamableMethod { + return context.path("/jobs").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } -export async function _listJobsFromScheduleDeserialize( - result: ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse -): Promise { +export async function _listJobsDeserialize( + result: ListJobs200Response | ListJobsDefaultResponse +): Promise { if (isUnexpected(result)) { throw result.body; } @@ -7988,1209 +6924,449 @@ export async function _listJobsFromScheduleDeserialize( }; } -/** Lists the Jobs that have been created under the specified Job Schedule. */ -export async function listJobsFromSchedule( +/** Lists all of the Jobs in the specified Account. */ +export function listJobs( context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _listJobsFromScheduleSend( + options: ListJobsOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator(context, _listJobsSend, _listJobsDeserialize, [ context, - jobScheduleId, - options - ); - return _listJobsFromScheduleDeserialize(result); + options, + ]); } -export function _listJobPreparationAndReleaseTaskStatusSend( +export function _listJobsFromScheduleSend( context: Client, - jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptions = { - requestOptions: {}, - } + jobScheduleId: string, + options: ListJobsFromScheduleOptions = { requestOptions: {} } ): StreamableMethod< - | ListJobPreparationAndReleaseTaskStatus200Response - | ListJobPreparationAndReleaseTaskStatusDefaultResponse + ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse > { - return context - .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - }, - }); + return context.path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } -export async function _listJobPreparationAndReleaseTaskStatusDeserialize( - result: - | ListJobPreparationAndReleaseTaskStatus200Response - | ListJobPreparationAndReleaseTaskStatusDefaultResponse -): Promise { +export async function _listJobsFromScheduleDeserialize( + result: ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse +): Promise { if (isUnexpected(result)) { throw result.body; } return { value: (result.body["value"] ?? []).map((p) => ({ - poolId: p["poolId"], - nodeId: p["nodeId"], - nodeUrl: p["nodeUrl"], - jobPreparationTaskExecutionInfo: !p.jobPreparationTaskExecutionInfo + id: p["id"], + displayName: p["displayName"], + usesTaskDependencies: p["usesTaskDependencies"], + url: p["url"], + eTag: p["eTag"], + lastModified: + p["lastModified"] !== undefined + ? new Date(p["lastModified"]) + : undefined, + creationTime: + p["creationTime"] !== undefined + ? new Date(p["creationTime"]) + : undefined, + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + priority: p["priority"], + allowTaskPreemption: p["allowTaskPreemption"], + maxParallelTasks: p["maxParallelTasks"], + constraints: !p.constraints ? undefined : { - startTime: new Date( - p.jobPreparationTaskExecutionInfo?.["startTime"] - ), - endTime: - p.jobPreparationTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobPreparationTaskExecutionInfo?.["endTime"]) - : undefined, - state: p.jobPreparationTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobPreparationTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobPreparationTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobPreparationTaskExecutionInfo?.containerInfo + maxWallClockTime: p.constraints?.["maxWallClockTime"], + maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !p.jobManagerTask + ? undefined + : { + id: p.jobManagerTask?.["id"], + displayName: p.jobManagerTask?.["displayName"], + commandLine: p.jobManagerTask?.["commandLine"], + containerSettings: !p.jobManagerTask?.containerSettings ? undefined : { - containerId: - p.jobPreparationTaskExecutionInfo?.containerInfo?.[ - "containerId" + containerRunOptions: + p.jobManagerTask?.containerSettings?.[ + "containerRunOptions" ], - state: - p.jobPreparationTaskExecutionInfo?.containerInfo?.["state"], - error: - p.jobPreparationTaskExecutionInfo?.containerInfo?.["error"], + imageName: p.jobManagerTask?.containerSettings?.["imageName"], + registry: !p.jobManagerTask?.containerSettings?.registry + ? undefined + : { + username: + p.jobManagerTask?.containerSettings?.registry?.[ + "username" + ], + password: + p.jobManagerTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + p.jobManagerTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobManagerTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + p.jobManagerTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + p.jobManagerTask?.containerSettings?.["workingDirectory"], }, - failureInfo: !p.jobPreparationTaskExecutionInfo?.failureInfo + resourceFiles: (p.jobManagerTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + outputFiles: (p.jobManagerTask?.["outputFiles"] ?? []).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + p.jobManagerTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !p.jobManagerTask?.constraints ? undefined : { - category: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "category" - ], - code: p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "code" - ], - message: - p.jobPreparationTaskExecutionInfo?.failureInfo?.["message"], - details: ( - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + p.jobManagerTask?.constraints?.["maxWallClockTime"], + retentionTime: + p.jobManagerTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + p.jobManagerTask?.constraints?.["maxTaskRetryCount"], }, - retryCount: p.jobPreparationTaskExecutionInfo?.["retryCount"], - lastRetryTime: - p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== undefined - ? new Date(p.jobPreparationTaskExecutionInfo?.["lastRetryTime"]) - : undefined, - result: p.jobPreparationTaskExecutionInfo?.["result"], - }, - jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo - ? undefined - : { - startTime: new Date(p.jobReleaseTaskExecutionInfo?.["startTime"]), - endTime: - p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) - : undefined, - state: p.jobReleaseTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo + requiredSlots: p.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: p.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !p.jobManagerTask?.userIdentity ? undefined : { - containerId: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.jobReleaseTaskExecutionInfo?.containerInfo?.["state"], - error: - p.jobReleaseTaskExecutionInfo?.containerInfo?.["error"], + username: p.jobManagerTask?.userIdentity?.["username"], + autoUser: !p.jobManagerTask?.userIdentity?.autoUser + ? undefined + : { + scope: + p.jobManagerTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + p.jobManagerTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, }, - failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo + runExclusive: p.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + p.jobManagerTask?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !p.jobManagerTask + ?.authenticationTokenSettings ? undefined : { - category: - p.jobReleaseTaskExecutionInfo?.failureInfo?.["category"], - code: p.jobReleaseTaskExecutionInfo?.failureInfo?.["code"], - message: - p.jobReleaseTaskExecutionInfo?.failureInfo?.["message"], - details: ( - p.jobReleaseTaskExecutionInfo?.failureInfo?.["details"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), + access: + p.jobManagerTask?.authenticationTokenSettings?.["access"], }, - result: p.jobReleaseTaskExecutionInfo?.["result"], + allowLowPriorityNode: p.jobManagerTask?.["allowLowPriorityNode"], }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** - * 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 async function listJobPreparationAndReleaseTaskStatus( - context: Client, - jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptions = { - requestOptions: {}, - } -): Promise { - const result = await _listJobPreparationAndReleaseTaskStatusSend( - context, - jobId, - options - ); - return _listJobPreparationAndReleaseTaskStatusDeserialize(result); -} - -export function _getJobTaskCountsSend( - context: Client, - jobId: string, - options: GetJobTaskCountsOptions = { requestOptions: {} } -): StreamableMethod< - GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse -> { - return context - .path("/jobs/{jobId}/taskcounts", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _getJobTaskCountsDeserialize( - result: GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - taskCounts: { - active: result.body.taskCounts["active"], - running: result.body.taskCounts["running"], - completed: result.body.taskCounts["completed"], - succeeded: result.body.taskCounts["succeeded"], - failed: result.body.taskCounts["failed"], - }, - taskSlotCounts: { - active: result.body.taskSlotCounts["active"], - running: result.body.taskSlotCounts["running"], - completed: result.body.taskSlotCounts["completed"], - succeeded: result.body.taskSlotCounts["succeeded"], - failed: result.body.taskSlotCounts["failed"], - }, - }; -} - -/** - * 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: GetJobTaskCountsOptions = { requestOptions: {} } -): Promise { - const result = await _getJobTaskCountsSend(context, jobId, options); - return _getJobTaskCountsDeserialize(result); -} - -export function _createCertificateSend( - context: Client, - body: BatchCertificate, - options: CreateCertificateOptions = { requestOptions: {} } -): StreamableMethod< - CreateCertificate201Response | CreateCertificateDefaultResponse -> { - return context - .path("/certificates") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - thumbprint: body["thumbprint"], - thumbprintAlgorithm: body["thumbprintAlgorithm"], - data: uint8ArrayToString(body["data"], "base64"), - certificateFormat: body["certificateFormat"], - password: body["password"], - }, - }); -} - -export async function _createCertificateDeserialize( - result: CreateCertificate201Response | CreateCertificateDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** Creates a Certificate to the specified Account. */ -export async function createCertificate( - context: Client, - body: BatchCertificate, - options: CreateCertificateOptions = { requestOptions: {} } -): Promise { - const result = await _createCertificateSend(context, body, options); - return _createCertificateDeserialize(result); -} - -export function _listCertificatesSend( - context: Client, - options: ListCertificatesOptions = { requestOptions: {} } -): StreamableMethod< - ListCertificates200Response | ListCertificatesDefaultResponse -> { - return context - .path("/certificates") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - }, - }); -} - -export async function _listCertificatesDeserialize( - result: ListCertificates200Response | ListCertificatesDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - value: (result.body["value"] ?? []).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - url: p["url"], - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - publicData: - typeof p["publicData"] === "string" - ? stringToUint8Array(p["publicData"], "base64") - : p["publicData"], - deleteCertificateError: !p.deleteCertificateError + jobPreparationTask: !p.jobPreparationTask ? undefined : { - code: p.deleteCertificateError?.["code"], - message: p.deleteCertificateError?.["message"], - values: (p.deleteCertificateError?.["values"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - data: - typeof p["data"] === "string" - ? stringToUint8Array(p["data"], "base64") - : p["data"], - certificateFormat: p["certificateFormat"], - password: p["password"], - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists all of the Certificates that have been added to the specified Account. */ -export async function listCertificates( - context: Client, - options: ListCertificatesOptions = { requestOptions: {} } -): Promise { - const result = await _listCertificatesSend(context, options); - return _listCertificatesDeserialize(result); -} - -export function _cancelCertificateDeletionSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptions = { requestOptions: {} } -): StreamableMethod< - | CancelCertificateDeletion204Response - | CancelCertificateDeletionDefaultResponse -> { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", - thumbprintAlgorithm, - thumbprint - ) - .post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _cancelCertificateDeletionDeserialize( - result: - | CancelCertificateDeletion204Response - | CancelCertificateDeletionDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptions = { requestOptions: {} } -): Promise { - const result = await _cancelCertificateDeletionSend( - context, - thumbprintAlgorithm, - thumbprint, - options - ); - return _cancelCertificateDeletionDeserialize(result); -} - -export function _deleteCertificateSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptions = { requestOptions: {} } -): StreamableMethod< - DeleteCertificate202Response | DeleteCertificateDefaultResponse -> { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint - ) - .delete({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _deleteCertificateDeserialize( - result: DeleteCertificate202Response | DeleteCertificateDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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: DeleteCertificateOptions = { requestOptions: {} } -): Promise { - const result = await _deleteCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options - ); - return _deleteCertificateDeserialize(result); -} - -export function _getCertificateSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint - ) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, - }); -} - -export async function _getCertificateDeserialize( - result: GetCertificate200Response | GetCertificateDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - thumbprint: result.body["thumbprint"], - thumbprintAlgorithm: result.body["thumbprintAlgorithm"], - url: result.body["url"], - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - publicData: - typeof result.body["publicData"] === "string" - ? stringToUint8Array(result.body["publicData"], "base64") - : result.body["publicData"], - deleteCertificateError: !result.body.deleteCertificateError - ? undefined - : { - code: result.body.deleteCertificateError?.["code"], - message: result.body.deleteCertificateError?.["message"], - values: (result.body.deleteCertificateError?.["values"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), - }, - data: - typeof result.body["data"] === "string" - ? stringToUint8Array(result.body["data"], "base64") - : result.body["data"], - certificateFormat: result.body["certificateFormat"], - password: result.body["password"], - }; -} - -/** Gets information about the specified Certificate. */ -export async function getCertificate( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptions = { requestOptions: {} } -): Promise { - const result = await _getCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options - ); - return _getCertificateDeserialize(result); -} - -export function _jobScheduleExistsSend( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptions = { requestOptions: {} } -): StreamableMethod< - | JobScheduleExists200Response - | JobScheduleExists404Response - | JobScheduleExistsDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .head({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _jobScheduleExistsDeserialize( - result: - | JobScheduleExists200Response - | JobScheduleExists404Response - | JobScheduleExistsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** Checks the specified Job Schedule exists. */ -export async function jobScheduleExists( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptions = { requestOptions: {} } -): Promise { - const result = await _jobScheduleExistsSend(context, jobScheduleId, options); - return _jobScheduleExistsDeserialize(result); -} - -export function _deleteJobScheduleSend( - context: Client, - jobScheduleId: string, - options: DeleteJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _deleteJobScheduleDeserialize( - result: DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - jobScheduleId: string, - options: DeleteJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _deleteJobScheduleSend(context, jobScheduleId, options); - return _deleteJobScheduleDeserialize(result); -} - -export function _getJobScheduleSend( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptions = { 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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _getJobScheduleDeserialize( - result: GetJobSchedule200Response | GetJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - schedule: { - doNotRunUntil: - result.body.schedule["doNotRunUntil"] !== undefined - ? new Date(result.body.schedule["doNotRunUntil"]) - : undefined, - doNotRunAfter: - result.body.schedule["doNotRunAfter"] !== undefined - ? new Date(result.body.schedule["doNotRunAfter"]) - : undefined, - startWindow: result.body.schedule["startWindow"], - recurrenceInterval: result.body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: result.body.jobSpecification["priority"], - allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], - displayName: result.body.jobSpecification["displayName"], - usesTaskDependencies: - result.body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], - onTaskFailure: result.body.jobSpecification["onTaskFailure"], - networkConfiguration: !result.body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - result.body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !result.body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - result.body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !result.body.jobSpecification.jobManagerTask - ? undefined - : { - id: result.body.jobSpecification.jobManagerTask?.["id"], - displayName: - result.body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - result.body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - result.body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - result.body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobSpecification.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - result.body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - result.body.jobSpecification.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !result.body.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - result.body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - result.body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !result.body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - result.body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - result.body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !result.body.jobSpecification.jobPreparationTask - ? undefined - : { - id: result.body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - result.body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings + id: p.jobPreparationTask?.["id"], + commandLine: p.jobPreparationTask?.["commandLine"], + containerSettings: !p.jobPreparationTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], + p.jobPreparationTask?.containerSettings?.[ + "containerRunOptions" + ], imageName: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry + p.jobPreparationTask?.containerSettings?.["imageName"], + registry: !p.jobPreparationTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], + p.jobPreparationTask?.containerSettings?.registry?.[ + "username" + ], password: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], + p.jobPreparationTask?.containerSettings?.registry?.[ + "password" + ], registryServer: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference + p.jobPreparationTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobPreparationTask + ?.containerSettings?.registry?.identityReference ? undefined : { resourceId: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + p.jobPreparationTask?.containerSettings + ?.registry?.identityReference?.["resourceId"], }, }, workingDirectory: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], + p.jobPreparationTask?.containerSettings?.[ + "workingDirectory" + ], }, - resourceFiles: ( - result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), + resourceFiles: (p.jobPreparationTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), environmentSettings: ( - result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] + p.jobPreparationTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobSpecification.jobPreparationTask - ?.constraints + constraints: !p.jobPreparationTask?.constraints ? undefined : { maxWallClockTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxWallClockTime"], + p.jobPreparationTask?.constraints?.["maxWallClockTime"], retentionTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["retentionTime"], + p.jobPreparationTask?.constraints?.["retentionTime"], maxTaskRetryCount: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], + p.jobPreparationTask?.constraints?.["maxTaskRetryCount"], }, - waitForSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity + waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], + userIdentity: !p.jobPreparationTask?.userIdentity ? undefined : { - username: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser + username: p.jobPreparationTask?.userIdentity?.["username"], + autoUser: !p.jobPreparationTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "scope" + ], elevationLevel: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, }, rerunOnNodeRebootAfterSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], + p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], }, - jobReleaseTask: !result.body.jobSpecification.jobReleaseTask + jobReleaseTask: !p.jobReleaseTask ? undefined : { - id: result.body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - result.body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings + id: p.jobReleaseTask?.["id"], + commandLine: p.jobReleaseTask?.["commandLine"], + containerSettings: !p.jobReleaseTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + p.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: p.jobReleaseTask?.containerSettings?.["imageName"], + registry: !p.jobReleaseTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], + p.jobReleaseTask?.containerSettings?.registry?.[ + "username" + ], password: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], + p.jobReleaseTask?.containerSettings?.registry?.[ + "password" + ], registryServer: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference + p.jobReleaseTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobReleaseTask?.containerSettings + ?.registry?.identityReference ? undefined : { resourceId: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + p.jobReleaseTask?.containerSettings?.registry ?.identityReference?.["resourceId"], }, }, workingDirectory: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], + p.jobReleaseTask?.containerSettings?.["workingDirectory"], }, - resourceFiles: ( - result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), + resourceFiles: (p.jobReleaseTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), environmentSettings: ( - result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] ?? [] + p.jobReleaseTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - result.body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity + maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], + retentionTime: p.jobReleaseTask?.["retentionTime"], + userIdentity: !p.jobReleaseTask?.userIdentity ? undefined : { - username: - result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser + username: p.jobReleaseTask?.userIdentity?.["username"], + autoUser: !p.jobReleaseTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], + p.jobReleaseTask?.userIdentity?.autoUser?.["scope"], elevationLevel: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["elevationLevel"], + p.jobReleaseTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, }, }, - commonEnvironmentSettings: ( - result.body.jobSpecification["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), + commonEnvironmentSettings: (p["commonEnvironmentSettings"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), poolInfo: { - poolId: result.body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !result.body.jobSpecification.poolInfo - .autoPoolSpecification + poolId: p.poolInfo["poolId"], + autoPoolSpecification: !p.poolInfo.autoPoolSpecification ? undefined : { autoPoolIdPrefix: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], + p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], poolLifetimeOption: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool + p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !p.poolInfo.autoPoolSpecification?.pool ? undefined : { displayName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration + p.poolInfo.autoPoolSpecification?.pool?.["displayName"], + vmSize: p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !p.poolInfo.autoPoolSpecification + ?.pool?.cloudServiceConfiguration ? undefined : { osFamily: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.cloudServiceConfiguration?.["osFamily"], osVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.cloudServiceConfiguration?.["osVersion"], }, - virtualMachineConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration + virtualMachineConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.virtualMachineConfiguration ? undefined : { imageReference: { publisher: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "publisher" ], offer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "offer" ], - sku: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + sku: p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "sku" ], version: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "version" ], virtualMachineImageId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "virtualMachineImageId" ], exactVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "exactVersion" ], }, nodeAgentSKUId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool + windowsConfiguration: !p.poolInfo + .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.windowsConfiguration ? undefined : { enableAutomaticUpdates: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.windowsConfiguration?.[ "enableAutomaticUpdates" ], }, dataDisks: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["dataDisks"] ?? [] ).map((p) => ({ lun: p["lun"], @@ -9199,29 +7375,25 @@ export async function _getJobScheduleDeserialize( storageAccountType: p["storageAccountType"], })), licenseType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool + containerConfiguration: !p.poolInfo + .autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration ? undefined : { - type: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + type: p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.["type"], containerImageNames: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.[ "containerImageNames" ], containerRegistries: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.[ "containerRegistries" @@ -9238,33 +7410,30 @@ export async function _getJobScheduleDeserialize( }, })), }, - diskEncryptionConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration + diskEncryptionConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration ?.diskEncryptionConfiguration ? undefined : { targets: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.diskEncryptionConfiguration?.["targets"], }, - nodePlacementConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration + nodePlacementConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration ?.nodePlacementConfiguration ? undefined : { policy: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.nodePlacementConfiguration?.["policy"], }, extensions: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["extensions"] ?? [] ).map((p) => ({ @@ -9280,21 +7449,18 @@ export async function _getJobScheduleDeserialize( provisionAfterExtensions: p["provisionAfterExtensions"], })), - osDisk: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + osDisk: !p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ? undefined : { - ephemeralOSDiskSettings: !result.body - .jobSpecification.poolInfo + ephemeralOSDiskSettings: !p.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ?.ephemeralOSDiskSettings ? undefined : { placement: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ?.ephemeralOSDiskSettings?.[ "placement" @@ -9303,66 +7469,62 @@ export async function _getJobScheduleDeserialize( }, }, taskSlotsPerNode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy + p.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !p.poolInfo.autoPoolSpecification + ?.pool?.taskSchedulingPolicy ? undefined : { nodeFillType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.taskSchedulingPolicy?.["nodeFillType"], }, resizeTimeout: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], + p.poolInfo.autoPoolSpecification?.pool?.["resizeTimeout"], targetDedicatedNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["targetDedicatedNodes"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], targetLowPriorityNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "targetLowPriorityNodes" ], enableAutoScale: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["enableAutoScale"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], autoScaleFormula: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["autoScaleFormula"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], autoScaleEvaluationInterval: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "autoScaleEvaluationInterval" ], enableInterNodeCommunication: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "enableInterNodeCommunication" ], - networkConfiguration: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration + networkConfiguration: !p.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration ? undefined : { subnetId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.["subnetId"], dynamicVNetAssignmentScope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.[ "dynamicVNetAssignmentScope" ], - endpointConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration + endpointConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.endpointConfiguration ? undefined : { inboundNATPools: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.endpointConfiguration?.[ "inboundNATPools" @@ -9386,88 +7548,76 @@ export async function _getJobScheduleDeserialize( })), })), }, - publicIPAddressConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration + publicIPAddressConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration ?.publicIPAddressConfiguration ? undefined : { provision: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.publicIPAddressConfiguration?.[ "provision" ], - ipAddressIds: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + ipAddressIds: + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.publicIPAddressConfiguration?.[ "ipAddressIds" ], }, enableAcceleratedNetworking: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.[ "enableAcceleratedNetworking" ], }, - startTask: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask + startTask: !p.poolInfo.autoPoolSpecification?.pool + ?.startTask ? undefined : { commandLine: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "commandLine" ], - containerSettings: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool?.startTask - ?.containerSettings + containerSettings: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ "containerRunOptions" ], imageName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings ?.registry?.["username"], password: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings ?.registry?.["password"], registryServer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings ?.registry?.["registryServer"], - identityReference: !result.body - .jobSpecification.poolInfo + identityReference: !p.poolInfo .autoPoolSpecification?.pool?.startTask ?.containerSettings?.registry ?.identityReference ? undefined : { resourceId: - result.body.jobSpecification - .poolInfo.autoPoolSpecification + p.poolInfo.autoPoolSpecification ?.pool?.startTask ?.containerSettings?.registry ?.identityReference?.[ @@ -9476,13 +7626,13 @@ export async function _getJobScheduleDeserialize( }, }, workingDirectory: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["workingDirectory"], + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], }, resourceFiles: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "resourceFiles" ] ?? [] ).map((p) => ({ @@ -9501,56 +7651,47 @@ export async function _getJobScheduleDeserialize( }, })), environmentSettings: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "environmentSettings" ] ?? [] ).map((p) => ({ name: p["name"], value: p["value"], })), - userIdentity: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity + userIdentity: !p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity ? undefined : { username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.userIdentity?.autoUser?.[ "scope" ], elevationLevel: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.userIdentity?.autoUser?.[ "elevationLevel" ], }, }, maxTaskRetryCount: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "maxTaskRetryCount" ], waitForSuccess: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "waitForSuccess" ], }, certificateReferences: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "certificateReferences" ] ?? [] ).map((p) => ({ @@ -9561,8 +7702,7 @@ export async function _getJobScheduleDeserialize( visibility: p["visibility"], })), applicationPackageReferences: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "applicationPackageReferences" ] ?? [] ).map((p) => ({ @@ -9570,11 +7710,13 @@ export async function _getJobScheduleDeserialize( version: p["version"], })), applicationLicenses: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["applicationLicenses"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], userAccounts: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] ?? [] + p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] ).map((p) => ({ name: p["name"], password: p["password"], @@ -9595,2508 +7737,2979 @@ export async function _getJobScheduleDeserialize( }, })), metadata: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] ?? [] + p.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), mountConfiguration: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["mountConfiguration"] ?? - [] + p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] ).map((p) => ({ azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: + p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.["mountOptions"], + }, + })), + targetNodeCommunicationMode: + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + onAllTasksComplete: p["onAllTasksComplete"], + onTaskFailure: p["onTaskFailure"], + networkConfiguration: !p.networkConfiguration + ? undefined + : { subnetId: p.networkConfiguration?.["subnetId"] }, + metadata: (p["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + executionInfo: !p.executionInfo + ? undefined + : { + startTime: new Date(p.executionInfo?.["startTime"]), + endTime: + p.executionInfo?.["endTime"] !== undefined + ? new Date(p.executionInfo?.["endTime"]) + : undefined, + poolId: p.executionInfo?.["poolId"], + schedulingError: !p.executionInfo?.schedulingError + ? undefined + : { + category: p.executionInfo?.schedulingError?.["category"], + code: p.executionInfo?.schedulingError?.["code"], + message: p.executionInfo?.schedulingError?.["message"], + details: ( + p.executionInfo?.schedulingError?.["details"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + terminateReason: p.executionInfo?.["terminateReason"], + }, + stats: !p.stats + ? undefined + : { + url: p.stats?.["url"], + startTime: new Date(p.stats?.["startTime"]), + lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), + userCPUTime: p.stats?.["userCPUTime"], + kernelCPUTime: p.stats?.["kernelCPUTime"], + wallClockTime: p.stats?.["wallClockTime"], + readIOps: p.stats?.["readIOps"], + writeIOps: p.stats?.["writeIOps"], + readIOGiB: p.stats?.["readIOGiB"], + writeIOGiB: p.stats?.["writeIOGiB"], + numSucceededTasks: p.stats?.["numSucceededTasks"], + numFailedTasks: p.stats?.["numFailedTasks"], + numTaskRetries: p.stats?.["numTaskRetries"], + waitTime: p.stats?.["waitTime"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists the Jobs that have been created under the specified Job Schedule. */ +export function listJobsFromSchedule( + context: Client, + jobScheduleId: string, + options: ListJobsFromScheduleOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listJobsFromScheduleSend, + _listJobsFromScheduleDeserialize, + [context, jobScheduleId, options] + ); +} + +export function _listJobPreparationAndReleaseTaskStatusSend( + context: Client, + jobId: string, + options: ListJobPreparationAndReleaseTaskStatusOptions = { + requestOptions: {}, + } +): StreamableMethod< + | ListJobPreparationAndReleaseTaskStatus200Response + | ListJobPreparationAndReleaseTaskStatusDefaultResponse +> { + return context + .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + }, + }); +} + +export async function _listJobPreparationAndReleaseTaskStatusDeserialize( + result: + | ListJobPreparationAndReleaseTaskStatus200Response + | ListJobPreparationAndReleaseTaskStatusDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + poolId: p["poolId"], + nodeId: p["nodeId"], + nodeUrl: p["nodeUrl"], + jobPreparationTaskExecutionInfo: !p.jobPreparationTaskExecutionInfo + ? undefined + : { + startTime: new Date( + p.jobPreparationTaskExecutionInfo?.["startTime"] + ), + endTime: + p.jobPreparationTaskExecutionInfo?.["endTime"] !== undefined + ? new Date(p.jobPreparationTaskExecutionInfo?.["endTime"]) + : undefined, + state: p.jobPreparationTaskExecutionInfo?.["state"], + taskRootDirectory: + p.jobPreparationTaskExecutionInfo?.["taskRootDirectory"], + taskRootDirectoryUrl: + p.jobPreparationTaskExecutionInfo?.["taskRootDirectoryUrl"], + exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], + containerInfo: !p.jobPreparationTaskExecutionInfo?.containerInfo + ? undefined + : { + containerId: + p.jobPreparationTaskExecutionInfo?.containerInfo?.[ + "containerId" + ], + state: + p.jobPreparationTaskExecutionInfo?.containerInfo?.["state"], + error: + p.jobPreparationTaskExecutionInfo?.containerInfo?.["error"], + }, + failureInfo: !p.jobPreparationTaskExecutionInfo?.failureInfo + ? undefined + : { + category: + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "category" + ], + code: p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "code" + ], + message: + p.jobPreparationTaskExecutionInfo?.failureInfo?.["message"], + details: ( + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "details" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + retryCount: p.jobPreparationTaskExecutionInfo?.["retryCount"], + lastRetryTime: + p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== undefined + ? new Date(p.jobPreparationTaskExecutionInfo?.["lastRetryTime"]) + : undefined, + result: p.jobPreparationTaskExecutionInfo?.["result"], + }, + jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo + ? undefined + : { + startTime: new Date(p.jobReleaseTaskExecutionInfo?.["startTime"]), + endTime: + p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined + ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) + : undefined, + state: p.jobReleaseTaskExecutionInfo?.["state"], + taskRootDirectory: + p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], + taskRootDirectoryUrl: + p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], + exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], + containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo + ? undefined + : { + containerId: + p.jobReleaseTaskExecutionInfo?.containerInfo?.[ + "containerId" + ], + state: + p.jobReleaseTaskExecutionInfo?.containerInfo?.["state"], + error: + p.jobReleaseTaskExecutionInfo?.containerInfo?.["error"], + }, + failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo + ? undefined + : { + category: + p.jobReleaseTaskExecutionInfo?.failureInfo?.["category"], + code: p.jobReleaseTaskExecutionInfo?.failureInfo?.["code"], + message: + p.jobReleaseTaskExecutionInfo?.failureInfo?.["message"], + details: ( + p.jobReleaseTaskExecutionInfo?.failureInfo?.["details"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + result: p.jobReleaseTaskExecutionInfo?.["result"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** + * 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: ListJobPreparationAndReleaseTaskStatusOptions = { + requestOptions: {}, + } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listJobPreparationAndReleaseTaskStatusSend, + _listJobPreparationAndReleaseTaskStatusDeserialize, + [context, jobId, options] + ); +} + +export function _getJobTaskCountsSend( + context: Client, + jobId: string, + options: GetJobTaskCountsOptions = { requestOptions: {} } +): StreamableMethod< + GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse +> { + return context.path("/jobs/{jobId}/taskcounts", jobId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _getJobTaskCountsDeserialize( + result: GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + taskCounts: { + active: result.body.taskCounts["active"], + running: result.body.taskCounts["running"], + completed: result.body.taskCounts["completed"], + succeeded: result.body.taskCounts["succeeded"], + failed: result.body.taskCounts["failed"], + }, + taskSlotCounts: { + active: result.body.taskSlotCounts["active"], + running: result.body.taskSlotCounts["running"], + completed: result.body.taskSlotCounts["completed"], + succeeded: result.body.taskSlotCounts["succeeded"], + failed: result.body.taskSlotCounts["failed"], + }, + }; +} + +/** + * 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: GetJobTaskCountsOptions = { requestOptions: {} } +): Promise { + const result = await _getJobTaskCountsSend(context, jobId, options); + return _getJobTaskCountsDeserialize(result); +} + +export function _createCertificateSend( + context: Client, + body: BatchCertificate, + options: CreateCertificateOptions = { requestOptions: {} } +): StreamableMethod< + CreateCertificate201Response | CreateCertificateDefaultResponse +> { + return context.path("/certificates").post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + thumbprint: body["thumbprint"], + thumbprintAlgorithm: body["thumbprintAlgorithm"], + data: uint8ArrayToString(body["data"], "base64"), + certificateFormat: body["certificateFormat"], + password: body["password"], + }, + }); +} + +export async function _createCertificateDeserialize( + result: CreateCertificate201Response | CreateCertificateDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Creates a Certificate to the specified Account. */ +export async function createCertificate( + context: Client, + body: BatchCertificate, + options: CreateCertificateOptions = { requestOptions: {} } +): Promise { + const result = await _createCertificateSend(context, body, options); + return _createCertificateDeserialize(result); +} + +export function _listCertificatesSend( + context: Client, + options: ListCertificatesOptions = { requestOptions: {} } +): StreamableMethod< + ListCertificates200Response | ListCertificatesDefaultResponse +> { + return context.path("/certificates").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + }, + }); +} + +export async function _listCertificatesDeserialize( + result: ListCertificates200Response | ListCertificatesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + url: p["url"], + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + publicData: + typeof p["publicData"] === "string" + ? stringToUint8Array(p["publicData"], "base64") + : p["publicData"], + deleteCertificateError: !p.deleteCertificateError + ? undefined + : { + code: p.deleteCertificateError?.["code"], + message: p.deleteCertificateError?.["message"], + values: (p.deleteCertificateError?.["values"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + data: + typeof p["data"] === "string" + ? stringToUint8Array(p["data"], "base64") + : p["data"], + certificateFormat: p["certificateFormat"], + password: p["password"], + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists all of the Certificates that have been added to the specified Account. */ +export function listCertificates( + context: Client, + options: ListCertificatesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listCertificatesSend, + _listCertificatesDeserialize, + [context, options] + ); +} + +export function _cancelCertificateDeletionSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptions = { requestOptions: {} } +): StreamableMethod< + | CancelCertificateDeletion204Response + | CancelCertificateDeletionDefaultResponse +> { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", + thumbprintAlgorithm, + thumbprint + ) + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _cancelCertificateDeletionDeserialize( + result: + | CancelCertificateDeletion204Response + | CancelCertificateDeletionDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptions = { requestOptions: {} } +): Promise { + const result = await _cancelCertificateDeletionSend( + context, + thumbprintAlgorithm, + thumbprint, + options + ); + return _cancelCertificateDeletionDeserialize(result); +} + +export function _deleteCertificateSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptions = { requestOptions: {} } +): StreamableMethod< + DeleteCertificate202Response | DeleteCertificateDefaultResponse +> { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint + ) + .delete({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _deleteCertificateDeserialize( + result: DeleteCertificate202Response | DeleteCertificateDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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: DeleteCertificateOptions = { requestOptions: {} } +): Promise { + const result = await _deleteCertificateSend( + context, + thumbprintAlgorithm, + thumbprint, + options + ); + return _deleteCertificateDeserialize(result); +} + +export function _getCertificateSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint + ) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, + }); +} + +export async function _getCertificateDeserialize( + result: GetCertificate200Response | GetCertificateDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + thumbprint: result.body["thumbprint"], + thumbprintAlgorithm: result.body["thumbprintAlgorithm"], + url: result.body["url"], + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + publicData: + typeof result.body["publicData"] === "string" + ? stringToUint8Array(result.body["publicData"], "base64") + : result.body["publicData"], + deleteCertificateError: !result.body.deleteCertificateError + ? undefined + : { + code: result.body.deleteCertificateError?.["code"], + message: result.body.deleteCertificateError?.["message"], + values: (result.body.deleteCertificateError?.["values"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), + }, + data: + typeof result.body["data"] === "string" + ? stringToUint8Array(result.body["data"], "base64") + : result.body["data"], + certificateFormat: result.body["certificateFormat"], + password: result.body["password"], + }; +} + +/** Gets information about the specified Certificate. */ +export async function getCertificate( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptions = { requestOptions: {} } +): Promise { + const result = await _getCertificateSend( + context, + thumbprintAlgorithm, + thumbprint, + options + ); + return _getCertificateDeserialize(result); +} + +export function _jobScheduleExistsSend( + context: Client, + jobScheduleId: string, + options: JobScheduleExistsOptions = { requestOptions: {} } +): StreamableMethod< + | JobScheduleExists200Response + | JobScheduleExists404Response + | JobScheduleExistsDefaultResponse +> { + return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).head({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _jobScheduleExistsDeserialize( + result: + | JobScheduleExists200Response + | JobScheduleExists404Response + | JobScheduleExistsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Checks the specified Job Schedule exists. */ +export async function jobScheduleExists( + context: Client, + jobScheduleId: string, + options: JobScheduleExistsOptions = { requestOptions: {} } +): Promise { + const result = await _jobScheduleExistsSend(context, jobScheduleId, options); + return _jobScheduleExistsDeserialize(result); +} + +export function _deleteJobScheduleSend( + context: Client, + jobScheduleId: string, + options: DeleteJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse +> { + return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _deleteJobScheduleDeserialize( + result: DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + jobScheduleId: string, + options: DeleteJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _deleteJobScheduleSend(context, jobScheduleId, options); + return _deleteJobScheduleDeserialize(result); +} + +export function _getJobScheduleSend( + context: Client, + jobScheduleId: string, + options: GetJobScheduleOptions = { 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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); +} + +export async function _getJobScheduleDeserialize( + result: GetJobSchedule200Response | GetJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + id: result.body["id"], + displayName: result.body["displayName"], + url: result.body["url"], + eTag: result.body["eTag"], + lastModified: + result.body["lastModified"] !== undefined + ? new Date(result.body["lastModified"]) + : undefined, + creationTime: + result.body["creationTime"] !== undefined + ? new Date(result.body["creationTime"]) + : undefined, + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + schedule: { + doNotRunUntil: + result.body.schedule["doNotRunUntil"] !== undefined + ? new Date(result.body.schedule["doNotRunUntil"]) + : undefined, + doNotRunAfter: + result.body.schedule["doNotRunAfter"] !== undefined + ? new Date(result.body.schedule["doNotRunAfter"]) + : undefined, + startWindow: result.body.schedule["startWindow"], + recurrenceInterval: result.body.schedule["recurrenceInterval"], + }, + jobSpecification: { + priority: result.body.jobSpecification["priority"], + allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], + displayName: result.body.jobSpecification["displayName"], + usesTaskDependencies: + result.body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], + onTaskFailure: result.body.jobSpecification["onTaskFailure"], + networkConfiguration: !result.body.jobSpecification.networkConfiguration + ? undefined + : { + subnetId: + result.body.jobSpecification.networkConfiguration?.["subnetId"], + }, + constraints: !result.body.jobSpecification.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + result.body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !result.body.jobSpecification.jobManagerTask + ? undefined + : { + id: result.body.jobSpecification.jobManagerTask?.["id"], + displayName: + result.body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + result.body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobManagerTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration + }, + workingDirectory: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + result.body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + result.body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference ? undefined : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + result.body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobSpecification.jobManagerTask + ?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + result.body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + result.body.jobSpecification.jobManagerTask?.[ + "killJobOnCompletion" + ], + userIdentity: !result.body.jobSpecification.jobManagerTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + runExclusive: + result.body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + result.body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !result.body.jobSpecification + .jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + result.body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + result.body.jobSpecification.jobManagerTask?.[ + "allowLowPriorityNode" + ], + }, + jobPreparationTask: !result.body.jobSpecification.jobPreparationTask + ? undefined + : { + id: result.body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + result.body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference ? undefined : { - accountName: - p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], + resourceId: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - })), - targetNodeCommunicationMode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - metadata: (result.body.jobSpecification["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - executionInfo: !result.body.executionInfo - ? undefined - : { - nextRunTime: - result.body.executionInfo?.["nextRunTime"] !== undefined - ? new Date(result.body.executionInfo?.["nextRunTime"]) - : undefined, - recentJob: !result.body.executionInfo?.recentJob - ? undefined - : { - id: result.body.executionInfo?.recentJob?.["id"], - url: result.body.executionInfo?.recentJob?.["url"], - }, - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - }, - metadata: (result.body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - numSucceededTasks: result.body.stats?.["numSucceededTasks"], - numFailedTasks: result.body.stats?.["numFailedTasks"], - numTaskRetries: result.body.stats?.["numTaskRetries"], - waitTime: result.body.stats?.["waitTime"], - }, - }; -} - -/** Gets information about the specified Job Schedule. */ -export async function getJobSchedule( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _getJobScheduleSend(context, jobScheduleId, options); - return _getJobScheduleDeserialize(result); -} - -export function _updateJobScheduleSend( - context: Client, - jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .patch({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - schedule: !body.schedule - ? undefined - : { - doNotRunUntil: body.schedule?.["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule?.["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule?.["startWindow"], - recurrenceInterval: body.schedule?.["recurrenceInterval"], - }, - jobSpecification: !body.jobSpecification - ? undefined - : { - priority: body.jobSpecification?.["priority"], - allowTaskPreemption: - body.jobSpecification?.["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification?.["maxParallelTasks"], - displayName: body.jobSpecification?.["displayName"], - usesTaskDependencies: - body.jobSpecification?.["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification?.["onAllTasksComplete"], - onTaskFailure: body.jobSpecification?.["onTaskFailure"], - networkConfiguration: !body.jobSpecification?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification?.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification?.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification?.jobManagerTask - ? undefined - : { - id: body.jobSpecification?.jobManagerTask?.["id"], - displayName: - body.jobSpecification?.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification?.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification?.jobManagerTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - body.jobSpecification?.jobManagerTask?.["outputFiles"] ?? - [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + }, + workingDirectory: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + result.body.jobSpecification.jobPreparationTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + result.body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["maxWallClockTime"], + retentionTime: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["retentionTime"], + maxTaskRetryCount: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["maxTaskRetryCount"], + }, + waitForSuccess: + result.body.jobSpecification.jobPreparationTask?.[ + "waitForSuccess" + ], + userIdentity: !result.body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + result.body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !result.body.jobSpecification.jobReleaseTask + ? undefined + : { + id: result.body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + result.body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobReleaseTask?.containerSettings?.registry + ?.identityReference ? undefined : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), + resourceId: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - body.jobSpecification?.jobManagerTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification?.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.jobManagerTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobSpecification?.jobManagerTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobSpecification?.jobManagerTask - ?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: - body.jobSpecification?.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification?.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !body.jobSpecification?.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: - body.jobSpecification?.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobSpecification?.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - ?.jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification?.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification?.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !body.jobSpecification?.jobPreparationTask - ? undefined - : { - id: body.jobSpecification?.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification?.jobPreparationTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification - ?.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobPreparationTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification - ?.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification?.jobPreparationTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification?.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification?.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: - body.jobSpecification?.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !body.jobSpecification?.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification?.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification?.jobReleaseTask + workingDirectory: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined - : { - id: body.jobSpecification?.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification?.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification?.jobReleaseTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification?.jobReleaseTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification?.jobReleaseTask?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification?.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification?.jobReleaseTask - ?.userIdentity + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + result.body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + result.body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !result.body.jobSpecification.jobReleaseTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: ( + result.body.jobSpecification["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: result.body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !result.body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool + ? undefined + : { + displayName: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["displayName"], + vmSize: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration ? undefined : { - username: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, + osFamily: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], }, - }, - commonEnvironmentSettings: ( - body.jobSpecification?.["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.jobSpecification?.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification?.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.[ - "osVersion" - ], - }, - virtualMachineConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: - !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" + virtualMachineConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" ], - enableAutoScale: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "enableAutoScale" + offer: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" ], - autoScaleFormula: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleFormula" + sku: result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" ], - autoScaleEvaluationInterval: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" + virtualMachineImageId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" ], - enableInterNodeCommunication: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" + exactVersion: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "exactVersion" ], - networkConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ? undefined - : { - username: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.[ - "registryServer" - ], - identityReference: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification - ?.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: - p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity + }, + nodeAgentSKUId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference ? undefined : { - username: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.[ - "elevationLevel" - ], - }, + resourceId: + p.identityReference?.["resourceId"], }, - maxTaskRetryCount: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.[ - "sshPrivateKey" - ], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration + })), + }, + diskEncryptionConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], + }, + nodePlacementConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !result.body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings ? undefined : { - loginMode: - p.windowsUserConfiguration?.[ - "loginMode" + placement: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" ], }, - })), - metadata: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["metadata"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + }, + }, + taskSlotsPerNode: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["resizeTimeout"], + targetDedicatedNodes: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["enableAutoScale"], + autoScaleFormula: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration + username: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry ?.identityReference ? undefined : { resourceId: - p.azureBlobFileSystemConfiguration + result.body.jobSpecification + .poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry ?.identityReference?.[ "resourceId" ], }, }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: - p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.[ - "mountOptions" - ], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + workingDirectory: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" + scope: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser?.[ + "scope" ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" + elevationLevel: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" ], }, - })), - targetNodeCommunicationMode: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], + }, + maxTaskRetryCount: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" + ], + }, + certificateReferences: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["applicationLicenses"], + userAccounts: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["userAccounts"] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["metadata"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["mountConfiguration"] ?? + [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - }, - }, - metadata: (body.jobSpecification?.["metadata"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: + p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.["mountOptions"], + }, + })), + targetNodeCommunicationMode: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, }, - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), }, - }); -} - -export async function _updateJobScheduleDeserialize( - result: UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; + metadata: (result.body.jobSpecification["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + executionInfo: !result.body.executionInfo + ? undefined + : { + nextRunTime: + result.body.executionInfo?.["nextRunTime"] !== undefined + ? new Date(result.body.executionInfo?.["nextRunTime"]) + : undefined, + recentJob: !result.body.executionInfo?.recentJob + ? undefined + : { + id: result.body.executionInfo?.recentJob?.["id"], + url: result.body.executionInfo?.recentJob?.["url"], + }, + endTime: + result.body.executionInfo?.["endTime"] !== undefined + ? new Date(result.body.executionInfo?.["endTime"]) + : undefined, + }, + metadata: (result.body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + stats: !result.body.stats + ? undefined + : { + url: result.body.stats?.["url"], + startTime: new Date(result.body.stats?.["startTime"]), + lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), + userCPUTime: result.body.stats?.["userCPUTime"], + kernelCPUTime: result.body.stats?.["kernelCPUTime"], + wallClockTime: result.body.stats?.["wallClockTime"], + readIOps: result.body.stats?.["readIOps"], + writeIOps: result.body.stats?.["writeIOps"], + readIOGiB: result.body.stats?.["readIOGiB"], + writeIOGiB: result.body.stats?.["writeIOGiB"], + numSucceededTasks: result.body.stats?.["numSucceededTasks"], + numFailedTasks: result.body.stats?.["numFailedTasks"], + numTaskRetries: result.body.stats?.["numTaskRetries"], + waitTime: result.body.stats?.["waitTime"], + }, + }; } -/** - * 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( +/** Gets information about the specified Job Schedule. */ +export async function getJobSchedule( context: Client, jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _updateJobScheduleSend( - context, - jobScheduleId, - body, - options - ); - return _updateJobScheduleDeserialize(result); + options: GetJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _getJobScheduleSend(context, jobScheduleId, options); + return _getJobScheduleDeserialize(result); } -export function _replaceJobScheduleSend( +export function _updateJobScheduleSend( context: Client, jobScheduleId: string, - body: BatchJobSchedule, - options: ReplaceJobScheduleOptions = { requestOptions: {} } + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptions = { requestOptions: {} } ): StreamableMethod< - ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse + UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse > { - return context - .path("/jobschedules/{jobScheduleId}", jobScheduleId) - .put({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - schedule: { - doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule["startWindow"], - recurrenceInterval: body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: body.jobSpecification["priority"], - allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification["maxParallelTasks"], - displayName: body.jobSpecification["displayName"], - usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], - onTaskFailure: body.jobSpecification["onTaskFailure"], - networkConfiguration: !body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification.jobManagerTask - ? undefined - : { - id: body.jobSpecification.jobManagerTask?.["id"], - displayName: - body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobSpecification.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !body.jobSpecification.jobPreparationTask - ? undefined - : { - id: body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).patch({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + schedule: !body.schedule + ? undefined + : { + doNotRunUntil: body.schedule?.["doNotRunUntil"]?.toISOString(), + doNotRunAfter: body.schedule?.["doNotRunAfter"]?.toISOString(), + startWindow: body.schedule?.["startWindow"], + recurrenceInterval: body.schedule?.["recurrenceInterval"], + }, + jobSpecification: !body.jobSpecification + ? undefined + : { + priority: body.jobSpecification?.["priority"], + allowTaskPreemption: body.jobSpecification?.["allowTaskPreemption"], + maxParallelTasks: body.jobSpecification?.["maxParallelTasks"], + displayName: body.jobSpecification?.["displayName"], + usesTaskDependencies: + body.jobSpecification?.["usesTaskDependencies"], + onAllTasksComplete: body.jobSpecification?.["onAllTasksComplete"], + onTaskFailure: body.jobSpecification?.["onTaskFailure"], + networkConfiguration: !body.jobSpecification?.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification?.networkConfiguration?.["subnetId"], + }, + constraints: !body.jobSpecification?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification?.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + body.jobSpecification?.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobSpecification?.jobManagerTask + ? undefined + : { + id: body.jobSpecification?.jobManagerTask?.["id"], + displayName: + body.jobSpecification?.jobManagerTask?.["displayName"], + commandLine: + body.jobSpecification?.jobManagerTask?.["commandLine"], + containerSettings: !body.jobSpecification?.jobManagerTask + ?.containerSettings ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: - body.jobSpecification.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification.jobReleaseTask - ? undefined - : { - id: body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + : { + containerRunOptions: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + ?.jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification?.jobManagerTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + body.jobSpecification?.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined : { - username: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobReleaseTask?.containerSettings?.registry + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container ?.identityReference ? undefined : { resourceId: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + p.destination.container ?.identityReference?.["resourceId"], }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), }, - workingDirectory: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], }, - resourceFiles: ( - body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], }, - }, - commonEnvironmentSettings: ( - body.jobSpecification["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" + })), + environmentSettings: ( + body.jobSpecification?.jobManagerTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification?.jobManagerTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification?.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification?.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification?.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + body.jobSpecification?.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + body.jobSpecification?.jobManagerTask?.[ + "killJobOnCompletion" ], - pool: !body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool + userIdentity: !body.jobSpecification?.jobManagerTask + ?.userIdentity ? undefined : { - displayName: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["displayName"], - vmSize: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration + username: + body.jobSpecification?.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification?.jobManagerTask + ?.userIdentity?.autoUser ? undefined : { - osFamily: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + scope: + body.jobSpecification?.jobManagerTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.jobManagerTask + ?.userIdentity?.autoUser?.["elevationLevel"], }, - virtualMachineConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - }, - nodeAgentSKUId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk + }, + runExclusive: + body.jobSpecification?.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobSpecification?.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobSpecification + ?.jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + body.jobSpecification?.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + body.jobSpecification?.jobManagerTask?.[ + "allowLowPriorityNode" + ], + }, + jobPreparationTask: !body.jobSpecification?.jobPreparationTask + ? undefined + : { + id: body.jobSpecification?.jobPreparationTask?.["id"], + commandLine: + body.jobSpecification?.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobSpecification?.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + ?.jobPreparationTask?.containerSettings + ?.registry?.identityReference ? undefined : { - ephemeralOSDiskSettings: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, + resourceId: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, }, - taskSlotsPerNode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy + workingDirectory: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification?.jobPreparationTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification?.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification?.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification?.jobPreparationTask + ?.constraints?.["maxWallClockTime"], + retentionTime: + body.jobSpecification?.jobPreparationTask + ?.constraints?.["retentionTime"], + maxTaskRetryCount: + body.jobSpecification?.jobPreparationTask + ?.constraints?.["maxTaskRetryCount"], + }, + waitForSuccess: + body.jobSpecification?.jobPreparationTask?.[ + "waitForSuccess" + ], + userIdentity: !body.jobSpecification?.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification?.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification?.jobPreparationTask + ?.userIdentity?.autoUser ? undefined : { - nodeFillType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + scope: + body.jobSpecification?.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], }, - resizeTimeout: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetLowPriorityNodes"], - enableAutoScale: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleEvaluationInterval"], - enableInterNodeCommunication: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableInterNodeCommunication"], - networkConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration + }, + rerunOnNodeRebootAfterSuccess: + body.jobSpecification?.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !body.jobSpecification?.jobReleaseTask + ? undefined + : { + id: body.jobSpecification?.jobReleaseTask?.["id"], + commandLine: + body.jobSpecification?.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobSpecification?.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry ? undefined : { - subnetId: - body.jobSpecification.poolInfo + username: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + ?.jobReleaseTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification?.jobReleaseTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification?.jobReleaseTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + body.jobSpecification?.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + body.jobSpecification?.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobSpecification?.jobReleaseTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification?.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification?.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification?.jobReleaseTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.jobReleaseTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: ( + body.jobSpecification?.["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.jobSpecification?.poolInfo["poolId"], + autoPoolSpecification: !body.jobSpecification?.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.jobSpecification?.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + body.jobSpecification?.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.jobSpecification?.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !body.jobSpecification?.poolInfo.autoPoolSpecification + ?.pool + ? undefined + : { + displayName: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["displayName"], + vmSize: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["sku"], + version: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + }, + nodeAgentSKUId: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !body + .jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification.poolInfo + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.jobSpecification.poolInfo + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body + .jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["resizeTimeout"], + targetDedicatedNodes: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["enableAutoScale"], + autoScaleFormula: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: + p["sourcePortRanges"], + })), })), - })), - }, - publicIPAddressConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.jobSpecification.poolInfo + }, + publicIPAddressConfiguration: !body + .jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + ?.networkConfiguration + ?.publicIPAddressConfiguration ? undefined : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["certificateReferences"] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationLicenses"], - userAccounts: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["userAccounts"] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], + provision: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], }, - windowsUserConfiguration: !p.windowsUserConfiguration + startTask: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask ? undefined : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["metadata"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["mountConfiguration"] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference + commandLine: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification + ?.poolInfo + .autoPoolSpecification + ?.pool?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined : { resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], + p.identityReference?.["resourceId"], }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" + })), + environmentSettings: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" + waitForSuccess: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" ], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + certificateReferences: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["userAccounts"] ?? + [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: + !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["metadata"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.[ + "resourceId" + ], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], + source: p.nfsMountConfiguration?.["source"], relativeMountPath: - p.azureFileShareConfiguration?.[ + p.nfsMountConfiguration?.[ "relativeMountPath" ], mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: + p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.[ + "relativeMountPath" ], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: + p.cifsMountConfiguration?.["password"], }, - })), - targetNodeCommunicationMode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetNodeCommunicationMode"], - }, - }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + metadata: (body.jobSpecification?.["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), }, - metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _replaceJobScheduleDeserialize( - result: ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * This fully replaces all the updatable properties of the Job Schedule. For - * example, if the schedule property is not specified with this request, then the - * Batch service will remove 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 replaceJobSchedule( - context: Client, - jobScheduleId: string, - body: BatchJobSchedule, - options: ReplaceJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _replaceJobScheduleSend( - context, - jobScheduleId, - body, - options - ); - return _replaceJobScheduleDeserialize(result); -} - -export function _disableJobScheduleSend( - context: Client, - jobScheduleId: string, - options: DisableJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - DisableJobSchedule204Response | DisableJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}/disable", jobScheduleId) - .post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _disableJobScheduleDeserialize( - result: DisableJobSchedule204Response | DisableJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** No new Jobs will be created until the Job Schedule is enabled again. */ -export async function disableJobSchedule( - context: Client, - jobScheduleId: string, - options: DisableJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _disableJobScheduleSend(context, jobScheduleId, options); - return _disableJobScheduleDeserialize(result); -} - -export function _enableJobScheduleSend( - context: Client, - jobScheduleId: string, - options: EnableJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - EnableJobSchedule204Response | EnableJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}/enable", jobScheduleId) - .post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _enableJobScheduleDeserialize( - result: EnableJobSchedule204Response | EnableJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** Enables a Job Schedule. */ -export async function enableJobSchedule( - context: Client, - jobScheduleId: string, - options: EnableJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _enableJobScheduleSend(context, jobScheduleId, options); - return _enableJobScheduleDeserialize(result); -} - -export function _terminateJobScheduleSend( - context: Client, - jobScheduleId: string, - options: TerminateJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse -> { - return context - .path("/jobschedules/{jobScheduleId}/terminate", jobScheduleId) - .post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); } -export async function _terminateJobScheduleDeserialize( - result: TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse +export async function _updateJobScheduleDeserialize( + result: UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -12105,1046 +10718,2226 @@ export async function _terminateJobScheduleDeserialize( return; } -/** Terminates a Job Schedule. */ -export async function terminateJobSchedule( +/** + * 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: TerminateJobScheduleOptions = { requestOptions: {} } + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptions = { requestOptions: {} } ): Promise { - const result = await _terminateJobScheduleSend( + const result = await _updateJobScheduleSend( context, jobScheduleId, + body, options ); - return _terminateJobScheduleDeserialize(result); + return _updateJobScheduleDeserialize(result); } -export function _createJobScheduleSend( +export function _replaceJobScheduleSend( context: Client, - body: BatchJobScheduleCreateOptions, - options: CreateJobScheduleOptions = { requestOptions: {} } + jobScheduleId: string, + body: BatchJobSchedule, + options: ReplaceJobScheduleOptions = { requestOptions: {} } ): StreamableMethod< - CreateJobSchedule201Response | CreateJobScheduleDefaultResponse + ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse > { - return context - .path("/jobschedules") - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - schedule: { - doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule["startWindow"], - recurrenceInterval: body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: body.jobSpecification["priority"], - allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification["maxParallelTasks"], - displayName: body.jobSpecification["displayName"], - usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], - onTaskFailure: body.jobSpecification["onTaskFailure"], - networkConfiguration: !body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification.jobManagerTask - ? undefined - : { - id: body.jobSpecification.jobManagerTask?.["id"], - displayName: - body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobManagerTask - ?.containerSettings + return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).put({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + schedule: { + doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), + doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), + startWindow: body.schedule["startWindow"], + recurrenceInterval: body.schedule["recurrenceInterval"], + }, + jobSpecification: { + priority: body.jobSpecification["priority"], + allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: body.jobSpecification["maxParallelTasks"], + displayName: body.jobSpecification["displayName"], + usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], + onTaskFailure: body.jobSpecification["onTaskFailure"], + networkConfiguration: !body.jobSpecification.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification.networkConfiguration?.["subnetId"], + }, + constraints: !body.jobSpecification.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobSpecification.jobManagerTask + ? undefined + : { + id: body.jobSpecification.jobManagerTask?.["id"], + displayName: + body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobManagerTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.jobManagerTask?.containerSettings?.[ + "imageName" + ], + registry: !body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined - : { - containerRunOptions: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + body.jobSpecification.jobManagerTask?.["environmentSettings"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !body.jobSpecification.jobManagerTask?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + runExclusive: + body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings + ? undefined + : { + access: + body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + body.jobSpecification.jobManagerTask?.["allowLowPriorityNode"], + }, + jobPreparationTask: !body.jobSpecification.jobPreparationTask + ? undefined + : { + id: body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: + body.jobSpecification.jobPreparationTask?.["waitForSuccess"], + userIdentity: !body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !body.jobSpecification.jobReleaseTask + ? undefined + : { + id: body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.jobReleaseTask?.containerSettings?.[ + "imageName" + ], + registry: !body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry ? undefined : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container + username: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !body.jobSpecification + .jobReleaseTask?.containerSettings?.registry ?.identityReference ? undefined : { resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), }, + workingDirectory: + body.jobSpecification.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobManagerTask?.constraints + resourceFiles: ( + body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobSpecification.jobManagerTask - ?.userIdentity + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobReleaseTask?.["environmentSettings"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobSpecification.jobReleaseTask?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: ( + body.jobSpecification["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool ? undefined : { - username: - body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser + displayName: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["displayName"], + vmSize: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["vmSize"], + cloudServiceConfiguration: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration ? undefined : { - scope: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["elevationLevel"], + osFamily: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], }, - }, - runExclusive: - body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - .jobManagerTask?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], - }, - jobPreparationTask: !body.jobSpecification.jobPreparationTask - ? undefined - : { - id: body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry + virtualMachineConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration ? undefined : { - username: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" + imageReference: { + publisher: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" + ], + sku: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" ], - identityReference: !body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference + version: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + }, + nodeAgentSKUId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? + [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + }, + diskEncryptionConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk ? undefined : { - resourceId: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + ephemeralOSDiskSettings: !body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, }, }, - workingDirectory: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: - body.jobSpecification.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser + taskSlotsPerNode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy ? undefined : { - scope: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], + nodeFillType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification.jobReleaseTask - ? undefined - : { - id: body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + resizeTimeout: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["resizeTimeout"], + targetDedicatedNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetLowPriorityNodes"], + enableAutoScale: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableAutoScale"], + autoScaleFormula: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleEvaluationInterval"], + enableInterNodeCommunication: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableInterNodeCommunication"], + networkConfiguration: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration ? undefined : { - username: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" + subnetId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" ], - identityReference: !body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference + endpointConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration ? undefined : { - resourceId: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + inboundNATPools: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), }, + publicIPAddressConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], }, - workingDirectory: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification.jobReleaseTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser + startTask: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask ? undefined : { - scope: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["elevationLevel"], + commandLine: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" + ], }, - }, - }, - commonEnvironmentSettings: ( - body.jobSpecification["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool - ? undefined - : { - displayName: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["displayName"], - vmSize: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration + certificateReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["certificateReferences"] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationLicenses"], + userAccounts: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["userAccounts"] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined : { - osFamily: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], }, - virtualMachineConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration + windowsUserConfiguration: !p.windowsUserConfiguration ? undefined : { - imageReference: { - publisher: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["metadata"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["mountConfiguration"] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, }, - nodeAgentSKUId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - taskSlotsPerNode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetNodeCommunicationMode"], + }, + }, + }, + metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); +} + +export async function _replaceJobScheduleDeserialize( + result: ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * This fully replaces all the updatable properties of the Job Schedule. For + * example, if the schedule property is not specified with this request, then the + * Batch service will remove 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 replaceJobSchedule( + context: Client, + jobScheduleId: string, + body: BatchJobSchedule, + options: ReplaceJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _replaceJobScheduleSend( + context, + jobScheduleId, + body, + options + ); + return _replaceJobScheduleDeserialize(result); +} + +export function _disableJobScheduleSend( + context: Client, + jobScheduleId: string, + options: DisableJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + DisableJobSchedule204Response | DisableJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/disable", jobScheduleId) + .post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _disableJobScheduleDeserialize( + result: DisableJobSchedule204Response | DisableJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** No new Jobs will be created until the Job Schedule is enabled again. */ +export async function disableJobSchedule( + context: Client, + jobScheduleId: string, + options: DisableJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _disableJobScheduleSend(context, jobScheduleId, options); + return _disableJobScheduleDeserialize(result); +} + +export function _enableJobScheduleSend( + context: Client, + jobScheduleId: string, + options: EnableJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + EnableJobSchedule204Response | EnableJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/enable", jobScheduleId) + .post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _enableJobScheduleDeserialize( + result: EnableJobSchedule204Response | EnableJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Enables a Job Schedule. */ +export async function enableJobSchedule( + context: Client, + jobScheduleId: string, + options: EnableJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _enableJobScheduleSend(context, jobScheduleId, options); + return _enableJobScheduleDeserialize(result); +} + +export function _terminateJobScheduleSend( + context: Client, + jobScheduleId: string, + options: TerminateJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}/terminate", jobScheduleId) + .post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _terminateJobScheduleDeserialize( + result: TerminateJobSchedule202Response | TerminateJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Terminates a Job Schedule. */ +export async function terminateJobSchedule( + context: Client, + jobScheduleId: string, + options: TerminateJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _terminateJobScheduleSend( + context, + jobScheduleId, + options + ); + return _terminateJobScheduleDeserialize(result); +} + +export function _createJobScheduleSend( + context: Client, + body: BatchJobScheduleCreateOptions, + options: CreateJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + CreateJobSchedule201Response | CreateJobScheduleDefaultResponse +> { + return context.path("/jobschedules").post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + schedule: { + doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), + doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), + startWindow: body.schedule["startWindow"], + recurrenceInterval: body.schedule["recurrenceInterval"], + }, + jobSpecification: { + priority: body.jobSpecification["priority"], + allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: body.jobSpecification["maxParallelTasks"], + displayName: body.jobSpecification["displayName"], + usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], + onTaskFailure: body.jobSpecification["onTaskFailure"], + networkConfiguration: !body.jobSpecification.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification.networkConfiguration?.["subnetId"], + }, + constraints: !body.jobSpecification.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobSpecification.jobManagerTask + ? undefined + : { + id: body.jobSpecification.jobManagerTask?.["id"], + displayName: + body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobManagerTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.jobManagerTask?.containerSettings?.[ + "imageName" + ], + registry: !body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference ? undefined : { - nodeFillType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], }, - resizeTimeout: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetLowPriorityNodes"], - enableAutoScale: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleEvaluationInterval"], - enableInterNodeCommunication: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableInterNodeCommunication"], - networkConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + body.jobSpecification.jobManagerTask?.["environmentSettings"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !body.jobSpecification.jobManagerTask?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + runExclusive: + body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings + ? undefined + : { + access: + body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + body.jobSpecification.jobManagerTask?.["allowLowPriorityNode"], + }, + jobPreparationTask: !body.jobSpecification.jobPreparationTask + ? undefined + : { + id: body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: + body.jobSpecification.jobPreparationTask?.["waitForSuccess"], + userIdentity: !body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !body.jobSpecification.jobReleaseTask + ? undefined + : { + id: body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.jobReleaseTask?.containerSettings?.[ + "imageName" + ], + registry: !body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !body.jobSpecification + .jobReleaseTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobReleaseTask?.["environmentSettings"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobSpecification.jobReleaseTask?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: ( + body.jobSpecification["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool + ? undefined + : { + displayName: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["displayName"], + vmSize: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["vmSize"], + cloudServiceConfiguration: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" + ?.virtualMachineConfiguration?.imageReference[ + "publisher" ], - endpointConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: + offer: body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" + ?.virtualMachineConfiguration?.imageReference[ + "offer" ], - containerSettings: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: + sku: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" ], - waitForSuccess: + virtualMachineImageId: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" ], }, - certificateReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["certificateReferences"] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationLicenses"], - userAccounts: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["userAccounts"] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["metadata"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["mountConfiguration"] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + nodeAgentSKUId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? + [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" + type: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" + containerRegistries: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + }, + diskEncryptionConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" + }, + nodePlacementConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["resizeTimeout"], + targetDedicatedNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetLowPriorityNodes"], + enableAutoScale: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableAutoScale"], + autoScaleFormula: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleEvaluationInterval"], + enableInterNodeCommunication: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableInterNodeCommunication"], + networkConfiguration: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" + ipAddressIds: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" + }, + enableAcceleratedNetworking: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference + imageName: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser ? undefined : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], + scope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], }, }, - nfsMountConfiguration: !p.nfsMountConfiguration + maxTaskRetryCount: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" + ], + }, + certificateReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["certificateReferences"] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationLicenses"], + userAccounts: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["userAccounts"] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["metadata"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["mountConfiguration"] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration ? undefined : { - source: p.nfsMountConfiguration?.["source"], + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], relativeMountPath: - p.nfsMountConfiguration?.[ + p.azureBlobFileSystemConfiguration?.[ "relativeMountPath" ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, }, - cifsMountConfiguration: !p.cifsMountConfiguration + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration ? undefined : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], relativeMountPath: - p.cifsMountConfiguration?.[ + p.azureFileShareConfiguration?.[ "relativeMountPath" ], mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], + p.azureFileShareConfiguration?.[ + "mountOptions" + ], }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetNodeCommunicationMode"], - }, - }, - }, - metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), + })), + targetNodeCommunicationMode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetNodeCommunicationMode"], + }, + }, }, - metadata: (body["metadata"] ?? []).map((p) => ({ + metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), }, - }); + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); } export async function _createJobScheduleDeserialize( @@ -13173,18 +12966,16 @@ export function _listJobSchedulesSend( ): StreamableMethod< ListJobSchedules200Response | ListJobSchedulesDefaultResponse > { - return context - .path("/jobschedules") - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobschedules").get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _listJobSchedulesDeserialize( @@ -14221,12 +14012,16 @@ export async function _listJobSchedulesDeserialize( } /** Lists all of the Job Schedules in the specified Account. */ -export async function listJobSchedules( +export function listJobSchedules( context: Client, options: ListJobSchedulesOptions = { requestOptions: {} } -): Promise { - const result = await _listJobSchedulesSend(context, options); - return _listJobSchedulesDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listJobSchedulesSend, + _listJobSchedulesDeserialize, + [context, options] + ); } export function _createTaskSend( @@ -14235,195 +14030,190 @@ export function _createTaskSend( body: BatchTaskCreateOptions, options: CreateTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks", jobId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - exitConditions: !body.exitConditions - ? undefined - : { - exitCodes: (body.exitConditions?.["exitCodes"] ?? []).map( - (p) => ({ - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - }) - ), - exitCodeRanges: ( - body.exitConditions?.["exitCodeRanges"] ?? [] - ).map((p) => ({ + return context.path("/jobs/{jobId}/tasks", jobId).post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + exitConditions: !body.exitConditions + ? undefined + : { + exitCodes: (body.exitConditions?.["exitCodes"] ?? []).map((p) => ({ + code: p["code"], + exitOptions: { + jobAction: p.exitOptions["jobAction"], + dependencyAction: p.exitOptions["dependencyAction"], + }, + })), + exitCodeRanges: (body.exitConditions?.["exitCodeRanges"] ?? []).map( + (p) => ({ start: p["start"], end: p["end"], exitOptions: { jobAction: p.exitOptions["jobAction"], dependencyAction: p.exitOptions["dependencyAction"], }, - })), - preProcessingError: !body.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - body.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - body.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !body.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - body.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - body.exitConditions?.fileUploadError?.[ - "dependencyAction" - ], - }, - default: !body.exitConditions?.default - ? undefined - : { - jobAction: body.exitConditions?.default?.["jobAction"], - dependencyAction: - body.exitConditions?.default?.["dependencyAction"], - }, - }, - commandLine: body["commandLine"], - containerSettings: !body.containerSettings - ? undefined - : { - containerRunOptions: - body.containerSettings?.["containerRunOptions"], - imageName: body.containerSettings?.["imageName"], - registry: !body.containerSettings?.registry - ? undefined - : { - username: body.containerSettings?.registry?.["username"], - password: body.containerSettings?.registry?.["password"], - registryServer: - body.containerSettings?.registry?.["registryServer"], - identityReference: !body.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: body.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body["resourceFiles"] ?? []).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: (body["outputFiles"] ?? []).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + }) + ), + preProcessingError: !body.exitConditions?.preProcessingError + ? undefined + : { + jobAction: + body.exitConditions?.preProcessingError?.["jobAction"], + dependencyAction: + body.exitConditions?.preProcessingError?.[ + "dependencyAction" + ], + }, + fileUploadError: !body.exitConditions?.fileUploadError + ? undefined + : { + jobAction: + body.exitConditions?.fileUploadError?.["jobAction"], + dependencyAction: + body.exitConditions?.fileUploadError?.["dependencyAction"], + }, + default: !body.exitConditions?.default ? undefined : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container?.identityReference + jobAction: body.exitConditions?.default?.["jobAction"], + dependencyAction: + body.exitConditions?.default?.["dependencyAction"], + }, + }, + commandLine: body["commandLine"], + containerSettings: !body.containerSettings + ? undefined + : { + containerRunOptions: + body.containerSettings?.["containerRunOptions"], + imageName: body.containerSettings?.["imageName"], + registry: !body.containerSettings?.registry + ? undefined + : { + username: body.containerSettings?.registry?.["username"], + password: body.containerSettings?.registry?.["password"], + registryServer: + body.containerSettings?.registry?.["registryServer"], + identityReference: !body.containerSettings?.registry + ?.identityReference ? undefined : { resourceId: - p.destination.container?.identityReference?.[ + body.containerSettings?.registry?.identityReference?.[ "resourceId" ], }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), }, + workingDirectory: body.containerSettings?.["workingDirectory"], }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: (body["environmentSettings"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - affinityInfo: !body.affinityInfo - ? undefined - : { affinityId: body.affinityInfo?.["affinityId"] }, - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - retentionTime: body.constraints?.["retentionTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: body["requiredSlots"], - userIdentity: !body.userIdentity - ? undefined - : { - username: body.userIdentity?.["username"], - autoUser: !body.userIdentity?.autoUser - ? undefined - : { - scope: body.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - multiInstanceSettings: !body.multiInstanceSettings + resourceFiles: (body["resourceFiles"] ?? []).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined - : { - numberOfInstances: - body.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - body.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: ( - body.multiInstanceSettings?.["commonResourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: (body["outputFiles"] ?? []).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container?.identityReference ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - dependsOn: !body.dependsOn - ? undefined - : { - taskIds: body.dependsOn?.["taskIds"], - taskIdRanges: (body.dependsOn?.["taskIdRanges"] ?? []).map( - (p) => ({ start: p["start"], end: p["end"] }) - ), - }, - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.authenticationTokenSettings - ? undefined - : { access: body.authenticationTokenSettings?.["access"] }, - }, - }); + : { + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: (body["environmentSettings"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + affinityInfo: !body.affinityInfo + ? undefined + : { affinityId: body.affinityInfo?.["affinityId"] }, + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + retentionTime: body.constraints?.["retentionTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: body["requiredSlots"], + userIdentity: !body.userIdentity + ? undefined + : { + username: body.userIdentity?.["username"], + autoUser: !body.userIdentity?.autoUser + ? undefined + : { + scope: body.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + multiInstanceSettings: !body.multiInstanceSettings + ? undefined + : { + numberOfInstances: + body.multiInstanceSettings?.["numberOfInstances"], + coordinationCommandLine: + body.multiInstanceSettings?.["coordinationCommandLine"], + commonResourceFiles: ( + body.multiInstanceSettings?.["commonResourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + dependsOn: !body.dependsOn + ? undefined + : { + taskIds: body.dependsOn?.["taskIds"], + taskIdRanges: (body.dependsOn?.["taskIdRanges"] ?? []).map((p) => ({ + start: p["start"], + end: p["end"], + })), + }, + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.authenticationTokenSettings + ? undefined + : { access: body.authenticationTokenSettings?.["access"] }, + }, + }); } export async function _createTaskDeserialize( @@ -14456,18 +14246,16 @@ export function _listTasksSend( jobId: string, options: ListTasksOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobs/{jobId}/tasks", jobId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _listTasksDeserialize( @@ -14743,13 +14531,17 @@ export async function _listTasksDeserialize( * nodeInfo refer to the primary Task. Use the list subtasks API to retrieve * information about subtasks. */ -export async function listTasks( +export function listTasks( context: Client, jobId: string, options: ListTasksOptions = { requestOptions: {} } -): Promise { - const result = await _listTasksSend(context, jobId, options); - return _listTasksDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listTasksSend, + _listTasksDeserialize, + [context, jobId, options] + ); } export function _createTaskCollectionSend( @@ -14760,194 +14552,189 @@ export function _createTaskCollectionSend( ): StreamableMethod< CreateTaskCollection200Response | CreateTaskCollectionDefaultResponse > { - return context - .path("/jobs/{jobId}/addtaskcollection", jobId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? - "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - value: (collection["value"] ?? []).map((p) => ({ - id: p["id"], - displayName: p["displayName"], - exitConditions: !p.exitConditions - ? undefined - : { - exitCodes: (p.exitConditions?.["exitCodes"] ?? []).map((p) => ({ - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - exitCodeRanges: ( - p.exitConditions?.["exitCodeRanges"] ?? [] - ).map((p) => ({ - start: p["start"], - end: p["end"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - preProcessingError: !p.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - p.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - p.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !p.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - p.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - p.exitConditions?.fileUploadError?.["dependencyAction"], - }, - default: !p.exitConditions?.default - ? undefined - : { - jobAction: p.exitConditions?.default?.["jobAction"], - dependencyAction: - p.exitConditions?.default?.["dependencyAction"], - }, - }, - commandLine: p["commandLine"], - containerSettings: !p.containerSettings - ? undefined - : { - containerRunOptions: - p.containerSettings?.["containerRunOptions"], - imageName: p.containerSettings?.["imageName"], - registry: !p.containerSettings?.registry - ? undefined - : { - username: p.containerSettings?.registry?.["username"], - password: p.containerSettings?.registry?.["password"], - registryServer: - p.containerSettings?.registry?.["registryServer"], - identityReference: !p.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: p.containerSettings?.["workingDirectory"], - }, - resourceFiles: (p["resourceFiles"] ?? []).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: (p["outputFiles"] ?? []).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + return context.path("/jobs/{jobId}/addtaskcollection", jobId).post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + value: (collection["value"] ?? []).map((p) => ({ + id: p["id"], + displayName: p["displayName"], + exitConditions: !p.exitConditions + ? undefined + : { + exitCodes: (p.exitConditions?.["exitCodes"] ?? []).map((p) => ({ + code: p["code"], + exitOptions: { + jobAction: p.exitOptions["jobAction"], + dependencyAction: p.exitOptions["dependencyAction"], + }, + })), + exitCodeRanges: (p.exitConditions?.["exitCodeRanges"] ?? []).map( + (p) => ({ + start: p["start"], + end: p["end"], + exitOptions: { + jobAction: p.exitOptions["jobAction"], + dependencyAction: p.exitOptions["dependencyAction"], + }, + }) + ), + preProcessingError: !p.exitConditions?.preProcessingError + ? undefined + : { + jobAction: + p.exitConditions?.preProcessingError?.["jobAction"], + dependencyAction: + p.exitConditions?.preProcessingError?.[ + "dependencyAction" + ], + }, + fileUploadError: !p.exitConditions?.fileUploadError + ? undefined + : { + jobAction: p.exitConditions?.fileUploadError?.["jobAction"], + dependencyAction: + p.exitConditions?.fileUploadError?.["dependencyAction"], + }, + default: !p.exitConditions?.default + ? undefined + : { + jobAction: p.exitConditions?.default?.["jobAction"], + dependencyAction: + p.exitConditions?.default?.["dependencyAction"], + }, + }, + commandLine: p["commandLine"], + containerSettings: !p.containerSettings + ? undefined + : { + containerRunOptions: p.containerSettings?.["containerRunOptions"], + imageName: p.containerSettings?.["imageName"], + registry: !p.containerSettings?.registry ? undefined : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container + username: p.containerSettings?.registry?.["username"], + password: p.containerSettings?.registry?.["password"], + registryServer: + p.containerSettings?.registry?.["registryServer"], + identityReference: !p.containerSettings?.registry ?.identityReference ? undefined : { resourceId: - p.destination.container?.identityReference?.[ + p.containerSettings?.registry?.identityReference?.[ "resourceId" ], }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), }, + workingDirectory: p.containerSettings?.["workingDirectory"], }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: (p["environmentSettings"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - affinityInfo: !p.affinityInfo - ? undefined - : { affinityId: p.affinityInfo?.["affinityId"] }, - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - retentionTime: p.constraints?.["retentionTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: p["requiredSlots"], - userIdentity: !p.userIdentity - ? undefined - : { - username: p.userIdentity?.["username"], - autoUser: !p.userIdentity?.autoUser - ? undefined - : { - scope: p.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - multiInstanceSettings: !p.multiInstanceSettings + resourceFiles: (p["resourceFiles"] ?? []).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined - : { - numberOfInstances: - p.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - p.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: ( - p.multiInstanceSettings?.["commonResourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: (p["outputFiles"] ?? []).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container?.identityReference ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - dependsOn: !p.dependsOn - ? undefined - : { - taskIds: p.dependsOn?.["taskIds"], - taskIdRanges: (p.dependsOn?.["taskIdRanges"] ?? []).map( - (p) => ({ start: p["start"], end: p["end"] }) - ), - }, - applicationPackageReferences: ( - p["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !p.authenticationTokenSettings - ? undefined - : { access: p.authenticationTokenSettings?.["access"] }, + : { + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, })), - }, - }); + environmentSettings: (p["environmentSettings"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + affinityInfo: !p.affinityInfo + ? undefined + : { affinityId: p.affinityInfo?.["affinityId"] }, + constraints: !p.constraints + ? undefined + : { + maxWallClockTime: p.constraints?.["maxWallClockTime"], + retentionTime: p.constraints?.["retentionTime"], + maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: p["requiredSlots"], + userIdentity: !p.userIdentity + ? undefined + : { + username: p.userIdentity?.["username"], + autoUser: !p.userIdentity?.autoUser + ? undefined + : { + scope: p.userIdentity?.autoUser?.["scope"], + elevationLevel: + p.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + multiInstanceSettings: !p.multiInstanceSettings + ? undefined + : { + numberOfInstances: p.multiInstanceSettings?.["numberOfInstances"], + coordinationCommandLine: + p.multiInstanceSettings?.["coordinationCommandLine"], + commonResourceFiles: ( + p.multiInstanceSettings?.["commonResourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + dependsOn: !p.dependsOn + ? undefined + : { + taskIds: p.dependsOn?.["taskIds"], + taskIdRanges: (p.dependsOn?.["taskIdRanges"] ?? []).map((p) => ({ + start: p["start"], + end: p["end"], + })), + }, + applicationPackageReferences: ( + p["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !p.authenticationTokenSettings + ? undefined + : { access: p.authenticationTokenSettings?.["access"] }, + })), + }, + }); } export async function _createTaskCollectionDeserialize( @@ -15023,26 +14810,24 @@ export function _deleteTaskSend( taskId: string, options: DeleteTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) - .delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _deleteTaskDeserialize( @@ -15078,30 +14863,28 @@ export function _getTaskSend( taskId: string, options: GetTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) - .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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _getTaskDeserialize( @@ -15399,38 +15182,35 @@ export function _replaceTaskSend( body: BatchTask, options: ReplaceTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) - .put({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - retentionTime: body.constraints?.["retentionTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - }, - }); + return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).put({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + retentionTime: body.constraints?.["retentionTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + }, + }); } export async function _replaceTaskDeserialize( @@ -15823,17 +15603,15 @@ export function _listTaskFilesSend( taskId: string, options: ListTaskFilesOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/jobs/{jobId}/tasks/{taskId}/files", jobId, taskId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - recursive: options?.recursive, - }, - }); + return context.path("/jobs/{jobId}/tasks/{taskId}/files", jobId, taskId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + recursive: options?.recursive, + }, + }); } export async function _listTaskFilesDeserialize( @@ -15866,14 +15644,18 @@ export async function _listTaskFilesDeserialize( } /** Lists the files in a Task's directory on its Compute Node. */ -export async function listTaskFiles( +export function listTaskFiles( context: Client, jobId: string, taskId: string, options: ListTaskFilesOptions = { requestOptions: {} } -): Promise { - const result = await _listTaskFilesSend(context, jobId, taskId, options); - return _listTaskFilesDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listTaskFilesSend, + _listTaskFilesDeserialize, + [context, jobId, taskId, options] + ); } export function _createNodeUserSend( @@ -16055,12 +15837,10 @@ export function _getNodeSend( nodeId: string, options: GetNodeOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, - }); + return context.path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, + }); } export async function _getNodeDeserialize( @@ -16695,17 +16475,15 @@ export function _listNodesSend( poolId: string, options: ListNodesOptions = { requestOptions: {} } ): StreamableMethod { - return context - .path("/pools/{poolId}/nodes", poolId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - }, - }); + return context.path("/pools/{poolId}/nodes", poolId).get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + }, + }); } export async function _listNodesDeserialize( @@ -16952,13 +16730,17 @@ export async function _listNodesDeserialize( } /** Lists the Compute Nodes in the specified Pool. */ -export async function listNodes( +export function listNodes( context: Client, poolId: string, options: ListNodesOptions = { requestOptions: {} } -): Promise { - const result = await _listNodesSend(context, poolId, options); - return _listNodesDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listNodesSend, + _listNodesDeserialize, + [context, poolId, options] + ); } export function _getNodeExtensionSend( @@ -17119,19 +16901,18 @@ export async function _listNodeExtensionsDeserialize( } /** Lists the Compute Nodes Extensions in the specified Pool. */ -export async function listNodeExtensions( +export function listNodeExtensions( context: Client, poolId: string, nodeId: string, options: ListNodeExtensionsOptions = { requestOptions: {} } -): Promise { - const result = await _listNodeExtensionsSend( +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( context, - poolId, - nodeId, - options + _listNodeExtensionsSend, + _listNodeExtensionsDeserialize, + [context, poolId, nodeId, options] ); - return _listNodeExtensionsDeserialize(result); } export function _deleteNodeFileSend( @@ -17355,12 +17136,16 @@ export async function _listNodeFilesDeserialize( } /** Lists all of the files in Task directories on the specified Compute Node. */ -export async function listNodeFiles( +export function listNodeFiles( context: Client, poolId: string, nodeId: string, options: ListNodeFilesOptions = { requestOptions: {} } -): Promise { - const result = await _listNodeFilesSend(context, poolId, nodeId, options); - return _listNodeFilesDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listNodeFilesSend, + _listNodeFilesDeserialize, + [context, poolId, nodeId, options] + ); } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts new file mode 100644 index 0000000000..0d1e5efb7f --- /dev/null +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, + PagedResult, + PageSettings as CorePageSettings, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +import { PageSettings, PagedAsyncIterableIterator } from "../models/index.js"; + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: (result: TResponse) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string) => { + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }) as any; + }, + }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); + + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + }, + }; +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + } +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} 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 5b094b02a1..ff17438ca3 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 @@ -283,4 +283,6 @@ export { GetNodeFileOptions, GetNodeFilePropertiesOptions, ListNodeFilesOptions, + PagedAsyncIterableIterator, + PageSettings, } from "./models/index.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts index f76889ad81..66e204e8d3 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts @@ -285,3 +285,5 @@ export { GetNodeFilePropertiesOptions, ListNodeFilesOptions, } from "./options.js"; + +export { PagedAsyncIterableIterator, PageSettings } from "./pagings.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagings.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagings.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagings.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/pagingUtil.ts similarity index 100% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/util/pagingUtil.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/pagingUtil.ts From 28afe2141817d972aabd515bf7fa8bdc6c5483ff Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 18:36:20 +0800 Subject: [PATCH 20/60] Update paging types --- .../src/models/{pagings.ts => pagingTypes.ts} | 0 packages/typespec-ts/src/index.ts | 14 +++++--- ...uildPagingUtils.ts => buildPagingFiles.ts} | 20 ++++++++++- .../{pagingUtil.ts => pagingHelpers.ts} | 32 +----------------- .../src/modular/static/pagingTypes.ts | 33 +++++++++++++++++++ 5 files changed, 62 insertions(+), 37 deletions(-) rename packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/{pagings.ts => pagingTypes.ts} (100%) rename packages/typespec-ts/src/modular/{buildPagingUtils.ts => buildPagingFiles.ts} (69%) rename packages/typespec-ts/src/modular/static/{pagingUtil.ts => pagingHelpers.ts} (88%) create mode 100644 packages/typespec-ts/src/modular/static/pagingTypes.ts diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagings.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts similarity index 100% rename from packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagings.ts rename to packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 9ab1a1b385..59efbb8d33 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -17,7 +17,7 @@ import { buildApiExtractorConfig, buildPackageFile, buildPollingHelper, - buildPaginateHelper, + buildPaginateHelper as buildRLCPaginateHelper, buildEsLintConfig, buildKarmaConfigFile, buildEnvFile, @@ -54,7 +54,10 @@ import { GenerationDirDetail, SdkContext } from "./utils/interfaces.js"; import { transformRLCOptions } from "./transform/transfromRLCOptions.js"; import { ModularCodeModel } from "./modular/modularCodeModel.js"; import { getClientName } from "@azure-tools/rlc-common"; -import { buildPagingUtils } from "./modular/buildPagingUtils.js"; +import { + buildPagingTypes, + buildPaginateHelper as buildModularPaginateHelper +} from "./modular/buildPagingTypesAndHelper.js"; export * from "./lib.js"; @@ -137,7 +140,7 @@ export async function $onEmit(context: EmitContext) { await emitContentByBuilder(program, buildIndexFile, rlcModels); await emitContentByBuilder(program, buildLogger, rlcModels); await emitContentByBuilder(program, buildTopLevelIndex, rlcModels); - await emitContentByBuilder(program, buildPaginateHelper, rlcModels); + await emitContentByBuilder(program, buildRLCPaginateHelper, rlcModels); await emitContentByBuilder(program, buildPollingHelper, rlcModels); await emitContentByBuilder(program, buildSerializeHelper, rlcModels); await emitContentByBuilder( @@ -171,13 +174,14 @@ export async function $onEmit(context: EmitContext) { overwrite: true } ); - // Build the shared paging utils - await buildPagingUtils(modularCodeModel, rlcCodeModels); + for (const subClient of modularCodeModel.clients) { buildModels(modularCodeModel, subClient); buildModelsOptions(modularCodeModel, subClient); const hasClientUnexpectedHelper = needUnexpectedHelper.get(subClient.rlcClientName) ?? false; + buildPagingTypes(modularCodeModel, subClient); + buildModularPaginateHelper(modularCodeModel, subClient); buildOperationFiles( dpgContext, modularCodeModel, diff --git a/packages/typespec-ts/src/modular/buildPagingUtils.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts similarity index 69% rename from packages/typespec-ts/src/modular/buildPagingUtils.ts rename to packages/typespec-ts/src/modular/buildPagingFiles.ts index 53a8eb6d22..5dd4b0d869 100644 --- a/packages/typespec-ts/src/modular/buildPagingUtils.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -1,7 +1,7 @@ import { RLCModel } from "@azure-tools/rlc-common"; import { dirname, join as joinPath } from "path"; import { promises } from "fs"; -import { ModularCodeModel } from "./modularCodeModel.js"; +import { Client, ModularCodeModel } from "./modularCodeModel.js"; import { fileURLToPath } from "url"; export async function buildPagingUtils( @@ -41,3 +41,21 @@ export async function buildPagingUtils( } ); } + +export async function buildPagingTypes( + _codeModel: ModularCodeModel, + _client: Client +) { + // const _hasPaging = rlcCodeModels.some( + // (codeModel) => codeModel.helperDetails?.hasPaging + // ); +} + +export async function buildPagingHelper( + _codeModel: ModularCodeModel, + _client: Client +) { + // const _hasPaging = rlcCodeModels.some( + // (codeModel) => codeModel.helperDetails?.hasPaging + // ); +} diff --git a/packages/typespec-ts/src/modular/static/pagingUtil.ts b/packages/typespec-ts/src/modular/static/pagingHelpers.ts similarity index 88% rename from packages/typespec-ts/src/modular/static/pagingUtil.ts rename to packages/typespec-ts/src/modular/static/pagingHelpers.ts index b5058ac15e..1ffff07c6c 100644 --- a/packages/typespec-ts/src/modular/static/pagingUtil.ts +++ b/packages/typespec-ts/src/modular/static/pagingHelpers.ts @@ -9,6 +9,7 @@ import { createRestError, PathUncheckedResponse } from "@azure-rest/core-client"; +import { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; export interface PageInfo { continuationToken?: string; @@ -36,37 +37,6 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; -export interface PageSettings { - /** - * 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 = PageSettings -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings - ) => AsyncIterableIterator; -} - export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse diff --git a/packages/typespec-ts/src/modular/static/pagingTypes.ts b/packages/typespec-ts/src/modular/static/pagingTypes.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-ts/src/modular/static/pagingTypes.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} From 33363f2dab7b01f3f1739181c1257cfea89828df Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 19:51:17 +0800 Subject: [PATCH 21/60] Update the batch generations --- .../generated/typespec-ts/package.json | 2 + .../generated/typespec-ts/src/BatchClient.ts | 2 +- .../generated/typespec-ts/src/api/index.ts | 5 + .../typespec-ts/src/api/operations.ts | 21163 ++++++++-------- .../{pagingHelper.ts => paginateHelper.ts} | 19 +- .../generated/typespec-ts/src/index.ts | 2 +- .../generated/typespec-ts/src/models/index.ts | 3 +- packages/typespec-ts/src/index.ts | 2 +- .../src/modular/buildPagingFiles.ts | 367 +- .../src/modular/helpers/operationHelpers.ts | 32 +- .../src/modular/static/pagingHelpers.ts | 229 - .../src/modular/static/pagingTypes.ts | 33 - 12 files changed, 11079 insertions(+), 10780 deletions(-) rename packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/{pagingHelper.ts => paginateHelper.ts} (94%) delete mode 100644 packages/typespec-ts/src/modular/static/pagingHelpers.ts delete mode 100644 packages/typespec-ts/src/modular/static/pagingTypes.ts diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json index f0bce94891..9630571769 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json @@ -73,6 +73,8 @@ "@azure/logger": "^1.0.0", "tslib": "^2.2.0", "@azure/core-paging": "^1.5.0", + "@azure/core-lro": "^2.5.4", + "@azure/abort-controller": "^1.0.0", "@azure/core-util": "^1.4.0" }, "devDependencies": { 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 3d4c790c80..a58a644ac3 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 @@ -204,7 +204,7 @@ import { getNodeFileProperties, listNodeFiles, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "./models/index.js"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; export { BatchClientOptions } from "./api/BatchContext.js"; 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 cfc770d76f..a2efb424a3 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 @@ -84,3 +84,8 @@ export { getNodeFileProperties, listNodeFiles, } from "./operations.js"; +export { + buildPagedAsyncIterator, + GetArrayType, + PaginateReturn, +} from "./paginateHelper.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 8985c94e31..6130410ad6 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 @@ -219,7 +219,10 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; -import { buildPagedAsyncIterator } from "./pagingHelper.js"; +import { + PagedAsyncIterableIterator, + buildPagedAsyncIterator, +} from "../util/pagingUtil.js"; import { ListApplicationsOptions, GetApplicationOptions, @@ -298,7 +301,6 @@ import { GetNodeFilePropertiesOptions, ListNodeFilesOptions, } from "../models/options.js"; -import { PagedAsyncIterableIterator } from "../models/index.js"; export function _listApplicationsSend( context: Client, @@ -306,13 +308,15 @@ export function _listApplicationsSend( ): StreamableMethod< ListApplications200Response | ListApplicationsDefaultResponse > { - return context.path("/applications").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - }, - }); + return context + .path("/applications") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + }, + }); } export async function _listApplicationsDeserialize( @@ -356,10 +360,12 @@ export function _getApplicationSend( applicationId: string, options: GetApplicationOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/applications/{applicationId}", applicationId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); + return context + .path("/applications/{applicationId}", applicationId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _getApplicationDeserialize( @@ -398,16 +404,18 @@ export function _listPoolUsageMetricsSend( ): StreamableMethod< ListPoolUsageMetrics200Response | ListPoolUsageMetricsDefaultResponse > { - return context.path("/poolusagemetrics").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - starttime: options?.starttime?.toISOString(), - endtime: options?.endtime?.toISOString(), - $filter: options?.$filter, - }, - }); + return context + .path("/poolusagemetrics") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + starttime: options?.starttime?.toISOString(), + endtime: options?.endtime?.toISOString(), + $filter: options?.$filter, + }, + }); } export async function _listPoolUsageMetricsDeserialize( @@ -454,68 +462,474 @@ export function _createPoolSend( body: BatchPoolCreateOptions, options: CreatePoolOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/pools").post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - vmSize: body["vmSize"], - cloudServiceConfiguration: !body.cloudServiceConfiguration + return context + .path("/pools") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + vmSize: body["vmSize"], + cloudServiceConfiguration: !body.cloudServiceConfiguration + ? undefined + : { + osFamily: body.cloudServiceConfiguration?.["osFamily"], + osVersion: body.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.virtualMachineConfiguration?.imageReference["publisher"], + offer: + body.virtualMachineConfiguration?.imageReference["offer"], + sku: body.virtualMachineConfiguration?.imageReference["sku"], + version: + body.virtualMachineConfiguration?.imageReference["version"], + virtualMachineImageId: + body.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + }, + nodeAgentSKUId: + body.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !body.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.virtualMachineConfiguration?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: body.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.virtualMachineConfiguration + ?.containerConfiguration?.["containerImageNames"], + containerRegistries: ( + body.virtualMachineConfiguration + ?.containerConfiguration?.["containerRegistries"] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + diskEncryptionConfiguration: !body.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], + }, + nodePlacementConfiguration: !body.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + body.virtualMachineConfiguration?.["extensions"] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: p["provisionAfterExtensions"], + })), + osDisk: !body.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings?.["placement"], + }, + }, + }, + resizeTimeout: body["resizeTimeout"], + targetDedicatedNodes: body["targetDedicatedNodes"], + targetLowPriorityNodes: body["targetLowPriorityNodes"], + enableAutoScale: body["enableAutoScale"], + autoScaleFormula: body["autoScaleFormula"], + autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], + enableInterNodeCommunication: body["enableInterNodeCommunication"], + networkConfiguration: !body.networkConfiguration + ? undefined + : { + subnetId: body.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.networkConfiguration?.["dynamicVNetAssignmentScope"], + endpointConfiguration: !body.networkConfiguration + ?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.networkConfiguration?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: p["frontendPortRangeStart"], + frontendPortRangeEnd: p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.networkConfiguration?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.networkConfiguration?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.networkConfiguration?.["enableAcceleratedNetworking"], + }, + startTask: !body.startTask + ? undefined + : { + commandLine: body.startTask?.["commandLine"], + containerSettings: !body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: body.startTask?.containerSettings?.["imageName"], + registry: !body.startTask?.containerSettings?.registry + ? undefined + : { + username: + body.startTask?.containerSettings?.registry?.[ + "username" + ], + password: + body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.startTask?.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !body.startTask?.userIdentity + ? undefined + : { + username: body.startTask?.userIdentity?.["username"], + autoUser: !body.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.startTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], + waitForSuccess: body.startTask?.["waitForSuccess"], + }, + certificateReferences: (body["certificateReferences"] ?? []).map( + (p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + }) + ), + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: body["applicationLicenses"], + taskSlotsPerNode: body["taskSlotsPerNode"], + taskSchedulingPolicy: !body.taskSchedulingPolicy + ? undefined + : { nodeFillType: body.taskSchedulingPolicy?.["nodeFillType"] }, + userAccounts: (body["userAccounts"] ?? []).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, + })), + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: (body["mountConfiguration"] ?? []).map((p) => ({ + azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.["accountName"], + containerName: + p.azureBlobFileSystemConfiguration?.["containerName"], + accountKey: p.azureBlobFileSystemConfiguration?.["accountKey"], + sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.["relativeMountPath"], + identityReference: !p.azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration?.identityReference?.[ + "resourceId" + ], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: !p.azureFileShareConfiguration + ? undefined + : { + accountName: p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.["relativeMountPath"], + mountOptions: p.azureFileShareConfiguration?.["mountOptions"], + }, + })), + targetNodeCommunicationMode: body["targetNodeCommunicationMode"], + }, + }); +} + +export async function _createPoolDeserialize( + result: CreatePool201Response | CreatePoolDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + body: BatchPoolCreateOptions, + options: CreatePoolOptions = { requestOptions: {} } +): Promise { + const result = await _createPoolSend(context, body, options); + return _createPoolDeserialize(result); +} + +export function _listPoolsSend( + context: Client, + options: ListPoolsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); +} + +export async function _listPoolsDeserialize( + result: ListPools200Response | ListPoolsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + id: p["id"], + displayName: p["displayName"], + url: p["url"], + eTag: p["eTag"], + lastModified: + p["lastModified"] !== undefined + ? new Date(p["lastModified"]) + : undefined, + creationTime: + p["creationTime"] !== undefined + ? new Date(p["creationTime"]) + : undefined, + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + allocationState: p["allocationState"], + allocationStateTransitionTime: + p["allocationStateTransitionTime"] !== undefined + ? new Date(p["allocationStateTransitionTime"]) + : undefined, + vmSize: p["vmSize"], + cloudServiceConfiguration: !p.cloudServiceConfiguration ? undefined : { - osFamily: body.cloudServiceConfiguration?.["osFamily"], - osVersion: body.cloudServiceConfiguration?.["osVersion"], + osFamily: p.cloudServiceConfiguration?.["osFamily"], + osVersion: p.cloudServiceConfiguration?.["osVersion"], }, - virtualMachineConfiguration: !body.virtualMachineConfiguration + virtualMachineConfiguration: !p.virtualMachineConfiguration ? undefined : { imageReference: { publisher: - body.virtualMachineConfiguration?.imageReference["publisher"], - offer: body.virtualMachineConfiguration?.imageReference["offer"], - sku: body.virtualMachineConfiguration?.imageReference["sku"], - version: - body.virtualMachineConfiguration?.imageReference["version"], + p.virtualMachineConfiguration?.imageReference["publisher"], + offer: p.virtualMachineConfiguration?.imageReference["offer"], + sku: p.virtualMachineConfiguration?.imageReference["sku"], + version: p.virtualMachineConfiguration?.imageReference["version"], virtualMachineImageId: - body.virtualMachineConfiguration?.imageReference[ + p.virtualMachineConfiguration?.imageReference[ "virtualMachineImageId" ], - }, - nodeAgentSKUId: - body.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !body.virtualMachineConfiguration + exactVersion: + p.virtualMachineConfiguration?.imageReference["exactVersion"], + }, + nodeAgentSKUId: p.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !p.virtualMachineConfiguration ?.windowsConfiguration ? undefined : { enableAutomaticUpdates: - body.virtualMachineConfiguration?.windowsConfiguration?.[ + p.virtualMachineConfiguration?.windowsConfiguration?.[ "enableAutomaticUpdates" ], }, - dataDisks: ( - body.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: body.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.virtualMachineConfiguration + dataDisks: (p.virtualMachineConfiguration?.["dataDisks"] ?? []).map( + (p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + }) + ), + licenseType: p.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !p.virtualMachineConfiguration ?.containerConfiguration ? undefined : { - type: body.virtualMachineConfiguration - ?.containerConfiguration?.["type"], + type: p.virtualMachineConfiguration?.containerConfiguration?.[ + "type" + ], containerImageNames: - body.virtualMachineConfiguration?.containerConfiguration?.[ + p.virtualMachineConfiguration?.containerConfiguration?.[ "containerImageNames" ], containerRegistries: ( - body.virtualMachineConfiguration?.containerConfiguration?.[ + p.virtualMachineConfiguration?.containerConfiguration?.[ "containerRegistries" ] ?? [] ).map((p) => ({ @@ -527,24 +941,25 @@ export function _createPoolSend( : { resourceId: p.identityReference?.["resourceId"] }, })), }, - diskEncryptionConfiguration: !body.virtualMachineConfiguration + diskEncryptionConfiguration: !p.virtualMachineConfiguration ?.diskEncryptionConfiguration ? undefined : { targets: - body.virtualMachineConfiguration + p.virtualMachineConfiguration ?.diskEncryptionConfiguration?.["targets"], }, - nodePlacementConfiguration: !body.virtualMachineConfiguration + nodePlacementConfiguration: !p.virtualMachineConfiguration ?.nodePlacementConfiguration ? undefined : { policy: - body.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], + p.virtualMachineConfiguration?.nodePlacementConfiguration?.[ + "policy" + ], }, extensions: ( - body.virtualMachineConfiguration?.["extensions"] ?? [] + p.virtualMachineConfiguration?.["extensions"] ?? [] ).map((p) => ({ name: p["name"], publisher: p["publisher"], @@ -556,38 +971,63 @@ export function _createPoolSend( protectedSettings: p["protectedSettings"], provisionAfterExtensions: p["provisionAfterExtensions"], })), - osDisk: !body.virtualMachineConfiguration?.osDisk + osDisk: !p.virtualMachineConfiguration?.osDisk ? undefined : { - ephemeralOSDiskSettings: !body.virtualMachineConfiguration + ephemeralOSDiskSettings: !p.virtualMachineConfiguration ?.osDisk?.ephemeralOSDiskSettings ? undefined : { placement: - body.virtualMachineConfiguration?.osDisk + p.virtualMachineConfiguration?.osDisk ?.ephemeralOSDiskSettings?.["placement"], }, }, }, - resizeTimeout: body["resizeTimeout"], - targetDedicatedNodes: body["targetDedicatedNodes"], - targetLowPriorityNodes: body["targetLowPriorityNodes"], - enableAutoScale: body["enableAutoScale"], - autoScaleFormula: body["autoScaleFormula"], - autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], - enableInterNodeCommunication: body["enableInterNodeCommunication"], - networkConfiguration: !body.networkConfiguration + resizeTimeout: p["resizeTimeout"], + resizeErrors: (p["resizeErrors"] ?? []).map((p) => ({ + code: p["code"], + message: p["message"], + values: (p["values"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + })), + currentDedicatedNodes: p["currentDedicatedNodes"], + currentLowPriorityNodes: p["currentLowPriorityNodes"], + targetDedicatedNodes: p["targetDedicatedNodes"], + targetLowPriorityNodes: p["targetLowPriorityNodes"], + enableAutoScale: p["enableAutoScale"], + autoScaleFormula: p["autoScaleFormula"], + autoScaleEvaluationInterval: p["autoScaleEvaluationInterval"], + autoScaleRun: !p.autoScaleRun + ? undefined + : { + timestamp: new Date(p.autoScaleRun?.["timestamp"]), + results: p.autoScaleRun?.["results"], + error: !p.autoScaleRun?.error + ? undefined + : { + code: p.autoScaleRun?.error?.["code"], + message: p.autoScaleRun?.error?.["message"], + values: (p.autoScaleRun?.error?.["values"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), + }, + }, + enableInterNodeCommunication: p["enableInterNodeCommunication"], + networkConfiguration: !p.networkConfiguration ? undefined : { - subnetId: body.networkConfiguration?.["subnetId"], + subnetId: p.networkConfiguration?.["subnetId"], dynamicVNetAssignmentScope: - body.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !body.networkConfiguration + p.networkConfiguration?.["dynamicVNetAssignmentScope"], + endpointConfiguration: !p.networkConfiguration ?.endpointConfiguration ? undefined : { inboundNATPools: ( - body.networkConfiguration?.endpointConfiguration?.[ + p.networkConfiguration?.endpointConfiguration?.[ "inboundNATPools" ] ?? [] ).map((p) => ({ @@ -606,94 +1046,91 @@ export function _createPoolSend( })), })), }, - publicIPAddressConfiguration: !body.networkConfiguration + publicIPAddressConfiguration: !p.networkConfiguration ?.publicIPAddressConfiguration ? undefined : { provision: - body.networkConfiguration?.publicIPAddressConfiguration?.[ + p.networkConfiguration?.publicIPAddressConfiguration?.[ "provision" ], ipAddressIds: - body.networkConfiguration?.publicIPAddressConfiguration?.[ + p.networkConfiguration?.publicIPAddressConfiguration?.[ "ipAddressIds" ], }, enableAcceleratedNetworking: - body.networkConfiguration?.["enableAcceleratedNetworking"], + p.networkConfiguration?.["enableAcceleratedNetworking"], }, - startTask: !body.startTask + startTask: !p.startTask ? undefined : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings + commandLine: p.startTask?.["commandLine"], + containerSettings: !p.startTask?.containerSettings ? undefined : { containerRunOptions: - body.startTask?.containerSettings?.["containerRunOptions"], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry + p.startTask?.containerSettings?.["containerRunOptions"], + imageName: p.startTask?.containerSettings?.["imageName"], + registry: !p.startTask?.containerSettings?.registry ? undefined : { username: - body.startTask?.containerSettings?.registry?.[ + p.startTask?.containerSettings?.registry?.[ "username" ], password: - body.startTask?.containerSettings?.registry?.[ + p.startTask?.containerSettings?.registry?.[ "password" ], registryServer: - body.startTask?.containerSettings?.registry?.[ + p.startTask?.containerSettings?.registry?.[ "registryServer" ], - identityReference: !body.startTask?.containerSettings + identityReference: !p.startTask?.containerSettings ?.registry?.identityReference ? undefined : { resourceId: - body.startTask?.containerSettings?.registry + p.startTask?.containerSettings?.registry ?.identityReference?.["resourceId"], }, }, workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], + p.startTask?.containerSettings?.["workingDirectory"], }, - resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), + resourceFiles: (p.startTask?.["resourceFiles"] ?? []).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), environmentSettings: ( - body.startTask?.["environmentSettings"] ?? [] + p.startTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !body.startTask?.userIdentity + userIdentity: !p.startTask?.userIdentity ? undefined : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser + username: p.startTask?.userIdentity?.["username"], + autoUser: !p.startTask?.userIdentity?.autoUser ? undefined : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], + scope: p.startTask?.userIdentity?.autoUser?.["scope"], elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ + p.startTask?.userIdentity?.autoUser?.[ "elevationLevel" ], }, }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], + maxTaskRetryCount: p.startTask?.["maxTaskRetryCount"], + waitForSuccess: p.startTask?.["waitForSuccess"], }, - certificateReferences: (body["certificateReferences"] ?? []).map((p) => ({ + certificateReferences: (p["certificateReferences"] ?? []).map((p) => ({ thumbprint: p["thumbprint"], thumbprintAlgorithm: p["thumbprintAlgorithm"], storeLocation: p["storeLocation"], @@ -701,17 +1138,17 @@ export function _createPoolSend( visibility: p["visibility"], })), applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] + p["applicationPackageReferences"] ?? [] ).map((p) => ({ applicationId: p["applicationId"], version: p["version"], })), - applicationLicenses: body["applicationLicenses"], - taskSlotsPerNode: body["taskSlotsPerNode"], - taskSchedulingPolicy: !body.taskSchedulingPolicy + applicationLicenses: p["applicationLicenses"], + taskSlotsPerNode: p["taskSlotsPerNode"], + taskSchedulingPolicy: !p.taskSchedulingPolicy ? undefined - : { nodeFillType: body.taskSchedulingPolicy?.["nodeFillType"] }, - userAccounts: (body["userAccounts"] ?? []).map((p) => ({ + : { nodeFillType: p.taskSchedulingPolicy?.["nodeFillType"] }, + userAccounts: (p["userAccounts"] ?? []).map((p) => ({ name: p["name"], password: p["password"], elevationLevel: p["elevationLevel"], @@ -726,11 +1163,47 @@ export function _createPoolSend( ? undefined : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, })), - metadata: (body["metadata"] ?? []).map((p) => ({ + metadata: (p["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), - mountConfiguration: (body["mountConfiguration"] ?? []).map((p) => ({ + stats: !p.stats + ? undefined + : { + url: p.stats?.["url"], + startTime: new Date(p.stats?.["startTime"]), + lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), + usageStats: !p.stats?.usageStats + ? undefined + : { + startTime: new Date(p.stats?.usageStats?.["startTime"]), + lastUpdateTime: new Date( + p.stats?.usageStats?.["lastUpdateTime"] + ), + dedicatedCoreTime: p.stats?.usageStats?.["dedicatedCoreTime"], + }, + resourceStats: !p.stats?.resourceStats + ? undefined + : { + startTime: new Date(p.stats?.resourceStats?.["startTime"]), + lastUpdateTime: new Date( + p.stats?.resourceStats?.["lastUpdateTime"] + ), + avgCPUPercentage: + p.stats?.resourceStats?.["avgCPUPercentage"], + avgMemoryGiB: p.stats?.resourceStats?.["avgMemoryGiB"], + peakMemoryGiB: p.stats?.resourceStats?.["peakMemoryGiB"], + avgDiskGiB: p.stats?.resourceStats?.["avgDiskGiB"], + peakDiskGiB: p.stats?.resourceStats?.["peakDiskGiB"], + diskReadIOps: p.stats?.resourceStats?.["diskReadIOps"], + diskWriteIOps: p.stats?.resourceStats?.["diskWriteIOps"], + diskReadGiB: p.stats?.resourceStats?.["diskReadGiB"], + diskWriteGiB: p.stats?.resourceStats?.["diskWriteGiB"], + networkReadGiB: p.stats?.resourceStats?.["networkReadGiB"], + networkWriteGiB: p.stats?.resourceStats?.["networkWriteGiB"], + }, + }, + mountConfiguration: (p["mountConfiguration"] ?? []).map((p) => ({ azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration ? undefined : { @@ -781,13 +1254,67 @@ export function _createPoolSend( mountOptions: p.azureFileShareConfiguration?.["mountOptions"], }, })), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, - }); + identity: !p.identity + ? undefined + : { + type: p.identity?.["type"], + userAssignedIdentities: ( + p.identity?.["userAssignedIdentities"] ?? [] + ).map((p) => ({ + resourceId: p["resourceId"], + clientId: p["clientId"], + principalId: p["principalId"], + })), + }, + targetNodeCommunicationMode: p["targetNodeCommunicationMode"], + currentNodeCommunicationMode: p["currentNodeCommunicationMode"], + })), + "odata.nextLink": result.body["odata.nextLink"], + }; } -export async function _createPoolDeserialize( - result: CreatePool201Response | CreatePoolDefaultResponse +/** Lists all of the Pools in the specified Account. */ +export function listPools( + context: Client, + options: ListPoolsOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listPoolsSend, + _listPoolsDeserialize, + [context, options] + ); +} + +export function _deletePoolSend( + context: Client, + poolId: string, + options: DeletePoolOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools/{poolId}", poolId) + .delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _deletePoolDeserialize( + result: DeletePool202Response | DeletePoolDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -797,291 +1324,374 @@ export async function _createPoolDeserialize( } /** - * 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. + * 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 createPool( +export async function deletePool( context: Client, - body: BatchPoolCreateOptions, - options: CreatePoolOptions = { requestOptions: {} } + poolId: string, + options: DeletePoolOptions = { requestOptions: {} } ): Promise { - const result = await _createPoolSend(context, body, options); - return _createPoolDeserialize(result); + const result = await _deletePoolSend(context, poolId, options); + return _deletePoolDeserialize(result); } -export function _listPoolsSend( +export function _poolExistsSend( context: Client, - options: ListPoolsOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _listPoolsDeserialize( - result: ListPools200Response | ListPoolsDefaultResponse -): Promise { + poolId: string, + options: PoolExistsOptions = { requestOptions: {} } +): StreamableMethod< + PoolExists200Response | PoolExists404Response | PoolExistsDefaultResponse +> { + return context + .path("/pools/{poolId}", poolId) + .head({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _poolExistsDeserialize( + result: + | PoolExists200Response + | PoolExists404Response + | PoolExistsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Gets basic properties of a Pool. */ +export async function poolExists( + context: Client, + poolId: string, + options: PoolExistsOptions = { requestOptions: {} } +): Promise { + const result = await _poolExistsSend(context, poolId, options); + return _poolExistsDeserialize(result); +} + +export function _getPoolSend( + context: Client, + poolId: string, + options: GetPoolOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools/{poolId}", poolId) + .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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); +} + +export async function _getPoolDeserialize( + result: GetPool200Response | GetPoolDefaultResponse +): Promise { if (isUnexpected(result)) { throw result.body; } return { - value: (result.body["value"] ?? []).map((p) => ({ - id: p["id"], - displayName: p["displayName"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - allocationState: p["allocationState"], - allocationStateTransitionTime: - p["allocationStateTransitionTime"] !== undefined - ? new Date(p["allocationStateTransitionTime"]) - : undefined, - vmSize: p["vmSize"], - cloudServiceConfiguration: !p.cloudServiceConfiguration - ? undefined - : { - osFamily: p.cloudServiceConfiguration?.["osFamily"], - osVersion: p.cloudServiceConfiguration?.["osVersion"], + id: result.body["id"], + displayName: result.body["displayName"], + url: result.body["url"], + eTag: result.body["eTag"], + lastModified: + result.body["lastModified"] !== undefined + ? new Date(result.body["lastModified"]) + : undefined, + creationTime: + result.body["creationTime"] !== undefined + ? new Date(result.body["creationTime"]) + : undefined, + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + allocationState: result.body["allocationState"], + allocationStateTransitionTime: + result.body["allocationStateTransitionTime"] !== undefined + ? new Date(result.body["allocationStateTransitionTime"]) + : undefined, + vmSize: result.body["vmSize"], + cloudServiceConfiguration: !result.body.cloudServiceConfiguration + ? undefined + : { + osFamily: result.body.cloudServiceConfiguration?.["osFamily"], + osVersion: result.body.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !result.body.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + result.body.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + result.body.virtualMachineConfiguration?.imageReference["offer"], + sku: result.body.virtualMachineConfiguration?.imageReference["sku"], + version: + result.body.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + result.body.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + exactVersion: + result.body.virtualMachineConfiguration?.imageReference[ + "exactVersion" + ], }, - virtualMachineConfiguration: !p.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.virtualMachineConfiguration?.imageReference["publisher"], - offer: p.virtualMachineConfiguration?.imageReference["offer"], - sku: p.virtualMachineConfiguration?.imageReference["sku"], - version: p.virtualMachineConfiguration?.imageReference["version"], - virtualMachineImageId: - p.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - p.virtualMachineConfiguration?.imageReference["exactVersion"], - }, - nodeAgentSKUId: p.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !p.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - p.virtualMachineConfiguration?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: (p.virtualMachineConfiguration?.["dataDisks"] ?? []).map( - (p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - }) - ), - licenseType: p.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !p.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: p.virtualMachineConfiguration?.containerConfiguration?.[ - "type" - ], - containerImageNames: - p.virtualMachineConfiguration?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - p.virtualMachineConfiguration?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - diskEncryptionConfiguration: !p.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !p.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.virtualMachineConfiguration?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( - p.virtualMachineConfiguration?.["extensions"] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: p["provisionAfterExtensions"], - })), - osDisk: !p.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings + nodeAgentSKUId: + result.body.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !result.body.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + result.body.virtualMachineConfiguration + ?.windowsConfiguration?.["enableAutomaticUpdates"], + }, + dataDisks: ( + result.body.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: result.body.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !result.body.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: result.body.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + result.body.virtualMachineConfiguration + ?.containerConfiguration?.["containerImageNames"], + containerRegistries: ( + result.body.virtualMachineConfiguration + ?.containerConfiguration?.["containerRegistries"] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference ? undefined - : { - placement: - p.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.["placement"], - }, - }, - }, - resizeTimeout: p["resizeTimeout"], - resizeErrors: (p["resizeErrors"] ?? []).map((p) => ({ - code: p["code"], - message: p["message"], - values: (p["values"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + diskEncryptionConfiguration: !result.body.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + result.body.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], + }, + nodePlacementConfiguration: !result.body.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + result.body.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + result.body.virtualMachineConfiguration?.["extensions"] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: p["provisionAfterExtensions"], + })), + osDisk: !result.body.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !result.body + .virtualMachineConfiguration?.osDisk?.ephemeralOSDiskSettings + ? undefined + : { + placement: + result.body.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings?.["placement"], + }, + }, + }, + resizeTimeout: result.body["resizeTimeout"], + resizeErrors: (result.body["resizeErrors"] ?? []).map((p) => ({ + code: p["code"], + message: p["message"], + values: (p["values"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], })), - currentDedicatedNodes: p["currentDedicatedNodes"], - currentLowPriorityNodes: p["currentLowPriorityNodes"], - targetDedicatedNodes: p["targetDedicatedNodes"], - targetLowPriorityNodes: p["targetLowPriorityNodes"], - enableAutoScale: p["enableAutoScale"], - autoScaleFormula: p["autoScaleFormula"], - autoScaleEvaluationInterval: p["autoScaleEvaluationInterval"], - autoScaleRun: !p.autoScaleRun - ? undefined - : { - timestamp: new Date(p.autoScaleRun?.["timestamp"]), - results: p.autoScaleRun?.["results"], - error: !p.autoScaleRun?.error - ? undefined - : { - code: p.autoScaleRun?.error?.["code"], - message: p.autoScaleRun?.error?.["message"], - values: (p.autoScaleRun?.error?.["values"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), - }, - }, - enableInterNodeCommunication: p["enableInterNodeCommunication"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { - subnetId: p.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !p.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - p.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] + })), + currentDedicatedNodes: result.body["currentDedicatedNodes"], + currentLowPriorityNodes: result.body["currentLowPriorityNodes"], + targetDedicatedNodes: result.body["targetDedicatedNodes"], + targetLowPriorityNodes: result.body["targetLowPriorityNodes"], + enableAutoScale: result.body["enableAutoScale"], + autoScaleFormula: result.body["autoScaleFormula"], + autoScaleEvaluationInterval: result.body["autoScaleEvaluationInterval"], + autoScaleRun: !result.body.autoScaleRun + ? undefined + : { + timestamp: new Date(result.body.autoScaleRun?.["timestamp"]), + results: result.body.autoScaleRun?.["results"], + error: !result.body.autoScaleRun?.error + ? undefined + : { + code: result.body.autoScaleRun?.error?.["code"], + message: result.body.autoScaleRun?.error?.["message"], + values: (result.body.autoScaleRun?.error?.["values"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), + }, + }, + enableInterNodeCommunication: result.body["enableInterNodeCommunication"], + networkConfiguration: !result.body.networkConfiguration + ? undefined + : { + subnetId: result.body.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + result.body.networkConfiguration?.["dynamicVNetAssignmentScope"], + endpointConfiguration: !result.body.networkConfiguration + ?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + result.body.networkConfiguration?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: p["frontendPortRangeStart"], + frontendPortRangeEnd: p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], })), - }, - publicIPAddressConfiguration: !p.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - p.networkConfiguration?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.networkConfiguration?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.networkConfiguration?.["enableAcceleratedNetworking"], - }, - startTask: !p.startTask - ? undefined - : { - commandLine: p.startTask?.["commandLine"], - containerSettings: !p.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.startTask?.containerSettings?.["containerRunOptions"], - imageName: p.startTask?.containerSettings?.["imageName"], - registry: !p.startTask?.containerSettings?.registry - ? undefined - : { - username: - p.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (p.startTask?.["resourceFiles"] ?? []).map((p) => ({ + })), + }, + publicIPAddressConfiguration: !result.body.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + result.body.networkConfiguration + ?.publicIPAddressConfiguration?.["provision"], + ipAddressIds: + result.body.networkConfiguration + ?.publicIPAddressConfiguration?.["ipAddressIds"], + }, + enableAcceleratedNetworking: + result.body.networkConfiguration?.["enableAcceleratedNetworking"], + }, + startTask: !result.body.startTask + ? undefined + : { + commandLine: result.body.startTask?.["commandLine"], + containerSettings: !result.body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.startTask?.containerSettings?.["imageName"], + registry: !result.body.startTask?.containerSettings?.registry + ? undefined + : { + username: + result.body.startTask?.containerSettings?.registry?.[ + "username" + ], + password: + result.body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + result.body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !result.body.startTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + result.body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + result.body.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: (result.body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ autoStorageContainerName: p["autoStorageContainerName"], storageContainerUrl: p["storageContainerUrl"], httpUrl: p["httpUrl"], @@ -1091,210 +1701,323 @@ export async function _listPoolsDeserialize( identityReference: !p.identityReference ? undefined : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - p.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !p.startTask?.userIdentity - ? undefined - : { - username: p.startTask?.userIdentity?.["username"], - autoUser: !p.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: p.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: p.startTask?.["maxTaskRetryCount"], - waitForSuccess: p.startTask?.["waitForSuccess"], - }, - certificateReferences: (p["certificateReferences"] ?? []).map((p) => ({ + }) + ), + environmentSettings: ( + result.body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !result.body.startTask?.userIdentity + ? undefined + : { + username: result.body.startTask?.userIdentity?.["username"], + autoUser: !result.body.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.startTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + result.body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: result.body.startTask?.["maxTaskRetryCount"], + waitForSuccess: result.body.startTask?.["waitForSuccess"], + }, + certificateReferences: (result.body["certificateReferences"] ?? []).map( + (p) => ({ thumbprint: p["thumbprint"], thumbprintAlgorithm: p["thumbprintAlgorithm"], storeLocation: p["storeLocation"], storeName: p["storeName"], visibility: p["visibility"], - })), - applicationPackageReferences: ( - p["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: p["applicationLicenses"], - taskSlotsPerNode: p["taskSlotsPerNode"], - taskSchedulingPolicy: !p.taskSchedulingPolicy + }) + ), + applicationPackageReferences: ( + result.body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: result.body["applicationLicenses"], + taskSlotsPerNode: result.body["taskSlotsPerNode"], + taskSchedulingPolicy: !result.body.taskSchedulingPolicy + ? undefined + : { nodeFillType: result.body.taskSchedulingPolicy?.["nodeFillType"] }, + userAccounts: (result.body["userAccounts"] ?? []).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined - : { nodeFillType: p.taskSchedulingPolicy?.["nodeFillType"] }, - userAccounts: (p["userAccounts"] ?? []).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, - })), - metadata: (p["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - stats: !p.stats + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, + })), + metadata: (result.body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + stats: !result.body.stats + ? undefined + : { + url: result.body.stats?.["url"], + startTime: new Date(result.body.stats?.["startTime"]), + lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), + usageStats: !result.body.stats?.usageStats + ? undefined + : { + startTime: new Date( + result.body.stats?.usageStats?.["startTime"] + ), + lastUpdateTime: new Date( + result.body.stats?.usageStats?.["lastUpdateTime"] + ), + dedicatedCoreTime: + result.body.stats?.usageStats?.["dedicatedCoreTime"], + }, + resourceStats: !result.body.stats?.resourceStats + ? undefined + : { + startTime: new Date( + result.body.stats?.resourceStats?.["startTime"] + ), + lastUpdateTime: new Date( + result.body.stats?.resourceStats?.["lastUpdateTime"] + ), + avgCPUPercentage: + result.body.stats?.resourceStats?.["avgCPUPercentage"], + avgMemoryGiB: + result.body.stats?.resourceStats?.["avgMemoryGiB"], + peakMemoryGiB: + result.body.stats?.resourceStats?.["peakMemoryGiB"], + avgDiskGiB: result.body.stats?.resourceStats?.["avgDiskGiB"], + peakDiskGiB: result.body.stats?.resourceStats?.["peakDiskGiB"], + diskReadIOps: + result.body.stats?.resourceStats?.["diskReadIOps"], + diskWriteIOps: + result.body.stats?.resourceStats?.["diskWriteIOps"], + diskReadGiB: result.body.stats?.resourceStats?.["diskReadGiB"], + diskWriteGiB: + result.body.stats?.resourceStats?.["diskWriteGiB"], + networkReadGiB: + result.body.stats?.resourceStats?.["networkReadGiB"], + networkWriteGiB: + result.body.stats?.resourceStats?.["networkWriteGiB"], + }, + }, + mountConfiguration: (result.body["mountConfiguration"] ?? []).map((p) => ({ + azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration ? undefined : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - usageStats: !p.stats?.usageStats + accountName: p.azureBlobFileSystemConfiguration?.["accountName"], + containerName: + p.azureBlobFileSystemConfiguration?.["containerName"], + accountKey: p.azureBlobFileSystemConfiguration?.["accountKey"], + sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.["relativeMountPath"], + identityReference: !p.azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - startTime: new Date(p.stats?.usageStats?.["startTime"]), - lastUpdateTime: new Date( - p.stats?.usageStats?.["lastUpdateTime"] - ), - dedicatedCoreTime: p.stats?.usageStats?.["dedicatedCoreTime"], - }, - resourceStats: !p.stats?.resourceStats - ? undefined - : { - startTime: new Date(p.stats?.resourceStats?.["startTime"]), - lastUpdateTime: new Date( - p.stats?.resourceStats?.["lastUpdateTime"] - ), - avgCPUPercentage: - p.stats?.resourceStats?.["avgCPUPercentage"], - avgMemoryGiB: p.stats?.resourceStats?.["avgMemoryGiB"], - peakMemoryGiB: p.stats?.resourceStats?.["peakMemoryGiB"], - avgDiskGiB: p.stats?.resourceStats?.["avgDiskGiB"], - peakDiskGiB: p.stats?.resourceStats?.["peakDiskGiB"], - diskReadIOps: p.stats?.resourceStats?.["diskReadIOps"], - diskWriteIOps: p.stats?.resourceStats?.["diskWriteIOps"], - diskReadGiB: p.stats?.resourceStats?.["diskReadGiB"], - diskWriteGiB: p.stats?.resourceStats?.["diskWriteGiB"], - networkReadGiB: p.stats?.resourceStats?.["networkReadGiB"], - networkWriteGiB: p.stats?.resourceStats?.["networkWriteGiB"], + resourceId: + p.azureBlobFileSystemConfiguration?.identityReference?.[ + "resourceId" + ], }, }, - mountConfiguration: (p["mountConfiguration"] ?? []).map((p) => ({ - azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: p.azureBlobFileSystemConfiguration?.["accountName"], - containerName: - p.azureBlobFileSystemConfiguration?.["containerName"], - accountKey: p.azureBlobFileSystemConfiguration?.["accountKey"], - sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.["relativeMountPath"], - identityReference: !p.azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: !p.azureFileShareConfiguration - ? undefined - : { - accountName: p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.["relativeMountPath"], - mountOptions: p.azureFileShareConfiguration?.["mountOptions"], - }, - })), - identity: !p.identity + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - type: p.identity?.["type"], - userAssignedIdentities: ( - p.identity?.["userAssignedIdentities"] ?? [] - ).map((p) => ({ - resourceId: p["resourceId"], - clientId: p["clientId"], - principalId: p["principalId"], - })), + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: !p.azureFileShareConfiguration + ? undefined + : { + accountName: p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.["relativeMountPath"], + mountOptions: p.azureFileShareConfiguration?.["mountOptions"], }, - targetNodeCommunicationMode: p["targetNodeCommunicationMode"], - currentNodeCommunicationMode: p["currentNodeCommunicationMode"], })), - "odata.nextLink": result.body["odata.nextLink"], + identity: !result.body.identity + ? undefined + : { + type: result.body.identity?.["type"], + userAssignedIdentities: ( + result.body.identity?.["userAssignedIdentities"] ?? [] + ).map((p) => ({ + resourceId: p["resourceId"], + clientId: p["clientId"], + principalId: p["principalId"], + })), + }, + targetNodeCommunicationMode: result.body["targetNodeCommunicationMode"], + currentNodeCommunicationMode: result.body["currentNodeCommunicationMode"], }; } -/** Lists all of the Pools in the specified Account. */ -export function listPools( +/** Gets information about the specified Pool. */ +export async function getPool( context: Client, - options: ListPoolsOptions = { requestOptions: {} } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - _listPoolsSend, - _listPoolsDeserialize, - [context, options] - ); + poolId: string, + options: GetPoolOptions = { requestOptions: {} } +): Promise { + const result = await _getPoolSend(context, poolId, options); + return _getPoolDeserialize(result); } -export function _deletePoolSend( +export function _updatePoolSend( context: Client, poolId: string, - options: DeletePoolOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools/{poolId}", poolId).delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + body: BatchPoolUpdateOptions, + options: UpdatePoolOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools/{poolId}", poolId) + .patch({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + startTask: !body.startTask + ? undefined + : { + commandLine: body.startTask?.["commandLine"], + containerSettings: !body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: body.startTask?.containerSettings?.["imageName"], + registry: !body.startTask?.containerSettings?.registry + ? undefined + : { + username: + body.startTask?.containerSettings?.registry?.[ + "username" + ], + password: + body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.startTask?.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !body.startTask?.userIdentity + ? undefined + : { + username: body.startTask?.userIdentity?.["username"], + autoUser: !body.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.startTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], + waitForSuccess: body.startTask?.["waitForSuccess"], + }, + certificateReferences: (body["certificateReferences"] ?? []).map( + (p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + }) + ), + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + targetNodeCommunicationMode: body["targetNodeCommunicationMode"], + }, + }); } -export async function _deletePoolDeserialize( - result: DeletePool202Response | DeletePoolDefaultResponse +export async function _updatePoolDeserialize( + result: UpdatePool200Response | UpdatePoolDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -1304,60 +2027,37 @@ export async function _deletePoolDeserialize( } /** - * 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. + * 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 deletePool( +export async function updatePool( context: Client, poolId: string, - options: DeletePoolOptions = { requestOptions: {} } + body: BatchPoolUpdateOptions, + options: UpdatePoolOptions = { requestOptions: {} } ): Promise { - const result = await _deletePoolSend(context, poolId, options); - return _deletePoolDeserialize(result); + const result = await _updatePoolSend(context, poolId, body, options); + return _updatePoolDeserialize(result); } -export function _poolExistsSend( +export function _disablePoolAutoScaleSend( context: Client, poolId: string, - options: PoolExistsOptions = { requestOptions: {} } + options: DisablePoolAutoScaleOptions = { requestOptions: {} } ): StreamableMethod< - PoolExists200Response | PoolExists404Response | PoolExistsDefaultResponse + DisablePoolAutoScale200Response | DisablePoolAutoScaleDefaultResponse > { - return context.path("/pools/{poolId}", poolId).head({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context + .path("/pools/{poolId}/disableautoscale", poolId) + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); } -export async function _poolExistsDeserialize( - result: - | PoolExists200Response - | PoolExists404Response - | PoolExistsDefaultResponse +export async function _disablePoolAutoScaleDeserialize( + result: DisablePoolAutoScale200Response | DisablePoolAutoScaleDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -1366,2926 +2066,185 @@ export async function _poolExistsDeserialize( return; } -/** Gets basic properties of a Pool. */ -export async function poolExists( +/** Disables automatic scaling for a Pool. */ +export async function disablePoolAutoScale( context: Client, poolId: string, - options: PoolExistsOptions = { requestOptions: {} } + options: DisablePoolAutoScaleOptions = { requestOptions: {} } ): Promise { - const result = await _poolExistsSend(context, poolId, options); - return _poolExistsDeserialize(result); + const result = await _disablePoolAutoScaleSend(context, poolId, options); + return _disablePoolAutoScaleDeserialize(result); } -export function _getPoolSend( +export function _enablePoolAutoScaleSend( context: Client, poolId: string, - options: GetPoolOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools/{poolId}", poolId).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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + body: BatchPoolEnableAutoScaleOptions, + options: EnablePoolAutoScaleOptions = { requestOptions: {} } +): StreamableMethod< + EnablePoolAutoScale200Response | EnablePoolAutoScaleDefaultResponse +> { + return context + .path("/pools/{poolId}/enableautoscale", poolId) + .post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + autoScaleFormula: body["autoScaleFormula"], + autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], + }, + }); } -export async function _getPoolDeserialize( - result: GetPool200Response | GetPoolDefaultResponse -): Promise { +export async function _enablePoolAutoScaleDeserialize( + result: EnablePoolAutoScale200Response | EnablePoolAutoScaleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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 enablePoolAutoScale( + context: Client, + poolId: string, + body: BatchPoolEnableAutoScaleOptions, + options: EnablePoolAutoScaleOptions = { requestOptions: {} } +): Promise { + const result = await _enablePoolAutoScaleSend(context, poolId, body, options); + return _enablePoolAutoScaleDeserialize(result); +} + +export function _evaluatePoolAutoScaleSend( + context: Client, + poolId: string, + body: BatchPoolEvaluateAutoScaleOptions, + options: EvaluatePoolAutoScaleOptions = { requestOptions: {} } +): StreamableMethod< + EvaluatePoolAutoScale200Response | EvaluatePoolAutoScaleDefaultResponse +> { + return context + .path("/pools/{poolId}/evaluateautoscale", poolId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { autoScaleFormula: body["autoScaleFormula"] }, + }); +} + +export async function _evaluatePoolAutoScaleDeserialize( + result: + | EvaluatePoolAutoScale200Response + | EvaluatePoolAutoScaleDefaultResponse +): Promise { if (isUnexpected(result)) { throw result.body; } return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - allocationState: result.body["allocationState"], - allocationStateTransitionTime: - result.body["allocationStateTransitionTime"] !== undefined - ? new Date(result.body["allocationStateTransitionTime"]) - : undefined, - vmSize: result.body["vmSize"], - cloudServiceConfiguration: !result.body.cloudServiceConfiguration - ? undefined - : { - osFamily: result.body.cloudServiceConfiguration?.["osFamily"], - osVersion: result.body.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !result.body.virtualMachineConfiguration + timestamp: new Date(result.body["timestamp"]), + results: result.body["results"], + error: !result.body.error ? undefined : { - imageReference: { - publisher: - result.body.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - result.body.virtualMachineConfiguration?.imageReference["offer"], - sku: result.body.virtualMachineConfiguration?.imageReference["sku"], - version: - result.body.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - result.body.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - result.body.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSKUId: - result.body.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - result.body.virtualMachineConfiguration - ?.windowsConfiguration?.["enableAutomaticUpdates"], - }, - dataDisks: ( - result.body.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: result.body.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: result.body.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - result.body.virtualMachineConfiguration - ?.containerConfiguration?.["containerImageNames"], - containerRegistries: ( - result.body.virtualMachineConfiguration - ?.containerConfiguration?.["containerRegistries"] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - diskEncryptionConfiguration: !result.body.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - result.body.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !result.body.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - result.body.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - result.body.virtualMachineConfiguration?.["extensions"] ?? [] - ).map((p) => ({ + code: result.body.error?.["code"], + message: result.body.error?.["message"], + values: (result.body.error?.["values"] ?? []).map((p) => ({ name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: p["provisionAfterExtensions"], + value: p["value"], })), - osDisk: !result.body.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !result.body - .virtualMachineConfiguration?.osDisk?.ephemeralOSDiskSettings - ? undefined - : { - placement: - result.body.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.["placement"], - }, - }, }, - resizeTimeout: result.body["resizeTimeout"], - resizeErrors: (result.body["resizeErrors"] ?? []).map((p) => ({ - code: p["code"], - message: p["message"], - values: (p["values"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - })), - currentDedicatedNodes: result.body["currentDedicatedNodes"], - currentLowPriorityNodes: result.body["currentLowPriorityNodes"], - targetDedicatedNodes: result.body["targetDedicatedNodes"], - targetLowPriorityNodes: result.body["targetLowPriorityNodes"], - enableAutoScale: result.body["enableAutoScale"], - autoScaleFormula: result.body["autoScaleFormula"], - autoScaleEvaluationInterval: result.body["autoScaleEvaluationInterval"], - autoScaleRun: !result.body.autoScaleRun - ? undefined - : { - timestamp: new Date(result.body.autoScaleRun?.["timestamp"]), - results: result.body.autoScaleRun?.["results"], - error: !result.body.autoScaleRun?.error - ? undefined - : { - code: result.body.autoScaleRun?.error?.["code"], - message: result.body.autoScaleRun?.error?.["message"], - values: (result.body.autoScaleRun?.error?.["values"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), - }, - }, - enableInterNodeCommunication: result.body["enableInterNodeCommunication"], - networkConfiguration: !result.body.networkConfiguration - ? undefined - : { - subnetId: result.body.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - result.body.networkConfiguration?.["dynamicVNetAssignmentScope"], - endpointConfiguration: !result.body.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - result.body.networkConfiguration?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !result.body.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - result.body.networkConfiguration - ?.publicIPAddressConfiguration?.["provision"], - ipAddressIds: - result.body.networkConfiguration - ?.publicIPAddressConfiguration?.["ipAddressIds"], - }, - enableAcceleratedNetworking: - result.body.networkConfiguration?.["enableAcceleratedNetworking"], - }, - startTask: !result.body.startTask - ? undefined - : { - commandLine: result.body.startTask?.["commandLine"], - containerSettings: !result.body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.startTask?.containerSettings?.["imageName"], - registry: !result.body.startTask?.containerSettings?.registry - ? undefined - : { - username: - result.body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - result.body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - result.body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !result.body.startTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: (result.body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - result.body.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !result.body.startTask?.userIdentity - ? undefined - : { - username: result.body.startTask?.userIdentity?.["username"], - autoUser: !result.body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: result.body.startTask?.["maxTaskRetryCount"], - waitForSuccess: result.body.startTask?.["waitForSuccess"], - }, - certificateReferences: (result.body["certificateReferences"] ?? []).map( - (p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - }) - ), - applicationPackageReferences: ( - result.body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: result.body["applicationLicenses"], - taskSlotsPerNode: result.body["taskSlotsPerNode"], - taskSchedulingPolicy: !result.body.taskSchedulingPolicy - ? undefined - : { nodeFillType: result.body.taskSchedulingPolicy?.["nodeFillType"] }, - userAccounts: (result.body["userAccounts"] ?? []).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { loginMode: p.windowsUserConfiguration?.["loginMode"] }, - })), - metadata: (result.body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - usageStats: !result.body.stats?.usageStats - ? undefined - : { - startTime: new Date( - result.body.stats?.usageStats?.["startTime"] - ), - lastUpdateTime: new Date( - result.body.stats?.usageStats?.["lastUpdateTime"] - ), - dedicatedCoreTime: - result.body.stats?.usageStats?.["dedicatedCoreTime"], - }, - resourceStats: !result.body.stats?.resourceStats - ? undefined - : { - startTime: new Date( - result.body.stats?.resourceStats?.["startTime"] - ), - lastUpdateTime: new Date( - result.body.stats?.resourceStats?.["lastUpdateTime"] - ), - avgCPUPercentage: - result.body.stats?.resourceStats?.["avgCPUPercentage"], - avgMemoryGiB: - result.body.stats?.resourceStats?.["avgMemoryGiB"], - peakMemoryGiB: - result.body.stats?.resourceStats?.["peakMemoryGiB"], - avgDiskGiB: result.body.stats?.resourceStats?.["avgDiskGiB"], - peakDiskGiB: result.body.stats?.resourceStats?.["peakDiskGiB"], - diskReadIOps: - result.body.stats?.resourceStats?.["diskReadIOps"], - diskWriteIOps: - result.body.stats?.resourceStats?.["diskWriteIOps"], - diskReadGiB: result.body.stats?.resourceStats?.["diskReadGiB"], - diskWriteGiB: - result.body.stats?.resourceStats?.["diskWriteGiB"], - networkReadGiB: - result.body.stats?.resourceStats?.["networkReadGiB"], - networkWriteGiB: - result.body.stats?.resourceStats?.["networkWriteGiB"], - }, - }, - mountConfiguration: (result.body["mountConfiguration"] ?? []).map((p) => ({ - azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: p.azureBlobFileSystemConfiguration?.["accountName"], - containerName: - p.azureBlobFileSystemConfiguration?.["containerName"], - accountKey: p.azureBlobFileSystemConfiguration?.["accountKey"], - sasKey: p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.["blobfuseOptions"], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.["relativeMountPath"], - identityReference: !p.azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: !p.azureFileShareConfiguration - ? undefined - : { - accountName: p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.["relativeMountPath"], - mountOptions: p.azureFileShareConfiguration?.["mountOptions"], - }, - })), - identity: !result.body.identity - ? undefined - : { - type: result.body.identity?.["type"], - userAssignedIdentities: ( - result.body.identity?.["userAssignedIdentities"] ?? [] - ).map((p) => ({ - resourceId: p["resourceId"], - clientId: p["clientId"], - principalId: p["principalId"], - })), - }, - targetNodeCommunicationMode: result.body["targetNodeCommunicationMode"], - currentNodeCommunicationMode: result.body["currentNodeCommunicationMode"], - }; -} - -/** Gets information about the specified Pool. */ -export async function getPool( - context: Client, - poolId: string, - options: GetPoolOptions = { requestOptions: {} } -): Promise { - const result = await _getPoolSend(context, poolId, options); - return _getPoolDeserialize(result); -} - -export function _updatePoolSend( - context: Client, - poolId: string, - body: BatchPoolUpdateOptions, - options: UpdatePoolOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools/{poolId}", poolId).patch({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.["containerRunOptions"], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, - certificateReferences: (body["certificateReferences"] ?? []).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, - }); -} - -export async function _updatePoolDeserialize( - result: UpdatePool200Response | UpdatePoolDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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 updatePool( - context: Client, - poolId: string, - body: BatchPoolUpdateOptions, - options: UpdatePoolOptions = { requestOptions: {} } -): Promise { - const result = await _updatePoolSend(context, poolId, body, options); - return _updatePoolDeserialize(result); -} - -export function _disablePoolAutoScaleSend( - context: Client, - poolId: string, - options: DisablePoolAutoScaleOptions = { requestOptions: {} } -): StreamableMethod< - DisablePoolAutoScale200Response | DisablePoolAutoScaleDefaultResponse -> { - return context.path("/pools/{poolId}/disableautoscale", poolId).post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _disablePoolAutoScaleDeserialize( - result: DisablePoolAutoScale200Response | DisablePoolAutoScaleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** Disables automatic scaling for a Pool. */ -export async function disablePoolAutoScale( - context: Client, - poolId: string, - options: DisablePoolAutoScaleOptions = { requestOptions: {} } -): Promise { - const result = await _disablePoolAutoScaleSend(context, poolId, options); - return _disablePoolAutoScaleDeserialize(result); -} - -export function _enablePoolAutoScaleSend( - context: Client, - poolId: string, - body: BatchPoolEnableAutoScaleOptions, - options: EnablePoolAutoScaleOptions = { requestOptions: {} } -): StreamableMethod< - EnablePoolAutoScale200Response | EnablePoolAutoScaleDefaultResponse -> { - return context.path("/pools/{poolId}/enableautoscale", poolId).post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - autoScaleFormula: body["autoScaleFormula"], - autoScaleEvaluationInterval: body["autoScaleEvaluationInterval"], - }, - }); -} - -export async function _enablePoolAutoScaleDeserialize( - result: EnablePoolAutoScale200Response | EnablePoolAutoScaleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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 enablePoolAutoScale( - context: Client, - poolId: string, - body: BatchPoolEnableAutoScaleOptions, - options: EnablePoolAutoScaleOptions = { requestOptions: {} } -): Promise { - const result = await _enablePoolAutoScaleSend(context, poolId, body, options); - return _enablePoolAutoScaleDeserialize(result); -} - -export function _evaluatePoolAutoScaleSend( - context: Client, - poolId: string, - body: BatchPoolEvaluateAutoScaleOptions, - options: EvaluatePoolAutoScaleOptions = { requestOptions: {} } -): StreamableMethod< - EvaluatePoolAutoScale200Response | EvaluatePoolAutoScaleDefaultResponse -> { - return context.path("/pools/{poolId}/evaluateautoscale", poolId).post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { autoScaleFormula: body["autoScaleFormula"] }, - }); -} - -export async function _evaluatePoolAutoScaleDeserialize( - result: - | EvaluatePoolAutoScale200Response - | EvaluatePoolAutoScaleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - timestamp: new Date(result.body["timestamp"]), - results: result.body["results"], - error: !result.body.error - ? undefined - : { - code: result.body.error?.["code"], - message: result.body.error?.["message"], - values: (result.body.error?.["values"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }; -} - -/** - * 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 evaluatePoolAutoScale( - context: Client, - poolId: string, - body: BatchPoolEvaluateAutoScaleOptions, - options: EvaluatePoolAutoScaleOptions = { requestOptions: {} } -): Promise { - const result = await _evaluatePoolAutoScaleSend( - context, - poolId, - body, - options - ); - return _evaluatePoolAutoScaleDeserialize(result); -} - -export function _resizePoolSend( - context: Client, - poolId: string, - body: BatchPoolResizeOptions, - options: ResizePoolOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools/{poolId}/resize", poolId).post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - targetDedicatedNodes: body["targetDedicatedNodes"], - targetLowPriorityNodes: body["targetLowPriorityNodes"], - resizeTimeout: body["resizeTimeout"], - nodeDeallocationOption: body["nodeDeallocationOption"], - }, - }); -} - -export async function _resizePoolDeserialize( - result: ResizePool202Response | ResizePoolDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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 resizePool( - context: Client, - poolId: string, - body: BatchPoolResizeOptions, - options: ResizePoolOptions = { requestOptions: {} } -): Promise { - const result = await _resizePoolSend(context, poolId, body, options); - return _resizePoolDeserialize(result); -} - -export function _stopPoolResizeSend( - context: Client, - poolId: string, - options: StopPoolResizeOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools/{poolId}/stopresize", poolId).post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _stopPoolResizeDeserialize( - result: StopPoolResize202Response | StopPoolResizeDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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, - options: StopPoolResizeOptions = { requestOptions: {} } -): Promise { - const result = await _stopPoolResizeSend(context, poolId, options); - return _stopPoolResizeDeserialize(result); -} - -export function _replacePoolPropertiesSend( - context: Client, - poolId: string, - body: BatchPoolReplaceOptions, - options: ReplacePoolPropertiesOptions = { requestOptions: {} } -): StreamableMethod< - ReplacePoolProperties204Response | ReplacePoolPropertiesDefaultResponse -> { - return context.path("/pools/{poolId}/updateproperties", poolId).post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - startTask: !body.startTask - ? undefined - : { - commandLine: body.startTask?.["commandLine"], - containerSettings: !body.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.startTask?.containerSettings?.["containerRunOptions"], - imageName: body.startTask?.containerSettings?.["imageName"], - registry: !body.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.startTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.startTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.startTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.startTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.startTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !body.startTask?.userIdentity - ? undefined - : { - username: body.startTask?.userIdentity?.["username"], - autoUser: !body.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.startTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], - waitForSuccess: body.startTask?.["waitForSuccess"], - }, - certificateReferences: (body["certificateReferences"] ?? []).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - targetNodeCommunicationMode: body["targetNodeCommunicationMode"], - }, - }); -} - -export async function _replacePoolPropertiesDeserialize( - result: - | ReplacePoolProperties204Response - | ReplacePoolPropertiesDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - poolId: string, - body: BatchPoolReplaceOptions, - options: ReplacePoolPropertiesOptions = { requestOptions: {} } -): Promise { - const result = await _replacePoolPropertiesSend( - context, - poolId, - body, - options - ); - return _replacePoolPropertiesDeserialize(result); -} - -export function _removeNodesSend( - context: Client, - poolId: string, - body: NodeRemoveOptions, - options: RemoveNodesOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/pools/{poolId}/removenodes", poolId).post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - nodeList: body["nodeList"], - resizeTimeout: body["resizeTimeout"], - nodeDeallocationOption: body["nodeDeallocationOption"], - }, - }); -} - -export async function _removeNodesDeserialize( - result: RemoveNodes202Response | RemoveNodesDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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 removeNodes( - context: Client, - poolId: string, - body: NodeRemoveOptions, - options: RemoveNodesOptions = { requestOptions: {} } -): Promise { - const result = await _removeNodesSend(context, poolId, body, options); - return _removeNodesDeserialize(result); -} - -export function _listSupportedImagesSend( - context: Client, - options: ListSupportedImagesOptions = { requestOptions: {} } -): StreamableMethod< - ListSupportedImages200Response | ListSupportedImagesDefaultResponse -> { - return context.path("/supportedimages").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - }, - }); -} - -export async function _listSupportedImagesDeserialize( - result: ListSupportedImages200Response | ListSupportedImagesDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - value: (result.body["value"] ?? []).map((p) => ({ - nodeAgentSKUId: p["nodeAgentSKUId"], - imageReference: { - publisher: p.imageReference["publisher"], - offer: p.imageReference["offer"], - sku: p.imageReference["sku"], - version: p.imageReference["version"], - virtualMachineImageId: p.imageReference["virtualMachineImageId"], - exactVersion: p.imageReference["exactVersion"], - }, - osType: p["osType"], - capabilities: p["capabilities"], - batchSupportEndOfLife: - p["batchSupportEndOfLife"] !== undefined - ? new Date(p["batchSupportEndOfLife"]) - : undefined, - verificationType: p["verificationType"], - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists all Virtual Machine Images supported by the Azure Batch service. */ -export function listSupportedImages( - context: Client, - options: ListSupportedImagesOptions = { requestOptions: {} } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - _listSupportedImagesSend, - _listSupportedImagesDeserialize, - [context, options] - ); -} - -export function _listPoolNodeCountsSend( - context: Client, - options: ListPoolNodeCountsOptions = { requestOptions: {} } -): StreamableMethod< - ListPoolNodeCounts200Response | ListPoolNodeCountsDefaultResponse -> { - return context.path("/nodecounts").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - }, - }); -} - -export async function _listPoolNodeCountsDeserialize( - result: ListPoolNodeCounts200Response | ListPoolNodeCountsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - value: (result.body["value"] ?? []).map((p) => ({ - poolId: p["poolId"], - dedicated: !p.dedicated - ? undefined - : { - creating: p.dedicated?.["creating"], - idle: p.dedicated?.["idle"], - offline: p.dedicated?.["offline"], - preempted: p.dedicated?.["preempted"], - rebooting: p.dedicated?.["rebooting"], - reimaging: p.dedicated?.["reimaging"], - running: p.dedicated?.["running"], - starting: p.dedicated?.["starting"], - startTaskFailed: p.dedicated?.["startTaskFailed"], - leavingPool: p.dedicated?.["leavingPool"], - unknown: p.dedicated?.["unknown"], - unusable: p.dedicated?.["unusable"], - waitingForStartTask: p.dedicated?.["waitingForStartTask"], - total: p.dedicated?.["total"], - }, - lowPriority: !p.lowPriority - ? undefined - : { - creating: p.lowPriority?.["creating"], - idle: p.lowPriority?.["idle"], - offline: p.lowPriority?.["offline"], - preempted: p.lowPriority?.["preempted"], - rebooting: p.lowPriority?.["rebooting"], - reimaging: p.lowPriority?.["reimaging"], - running: p.lowPriority?.["running"], - starting: p.lowPriority?.["starting"], - startTaskFailed: p.lowPriority?.["startTaskFailed"], - leavingPool: p.lowPriority?.["leavingPool"], - unknown: p.lowPriority?.["unknown"], - unusable: p.lowPriority?.["unusable"], - waitingForStartTask: p.lowPriority?.["waitingForStartTask"], - total: p.lowPriority?.["total"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** - * 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, - options: ListPoolNodeCountsOptions = { requestOptions: {} } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - _listPoolNodeCountsSend, - _listPoolNodeCountsDeserialize, - [context, options] - ); -} - -export function _deleteJobSend( - context: Client, - jobId: string, - options: DeleteJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs/{jobId}", jobId).delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _deleteJobDeserialize( - result: DeleteJob202Response | DeleteJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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: DeleteJobOptions = { requestOptions: {} } -): Promise { - const result = await _deleteJobSend(context, jobId, options); - return _deleteJobDeserialize(result); -} - -export function _getJobSend( - context: Client, - jobId: string, - options: GetJobOptions = { 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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _getJobDeserialize( - result: GetJob200Response | GetJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - id: result.body["id"], - displayName: result.body["displayName"], - usesTaskDependencies: result.body["usesTaskDependencies"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - priority: result.body["priority"], - allowTaskPreemption: result.body["allowTaskPreemption"], - maxParallelTasks: result.body["maxParallelTasks"], - constraints: !result.body.constraints - ? undefined - : { - maxWallClockTime: result.body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: result.body.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !result.body.jobManagerTask - ? undefined - : { - id: result.body.jobManagerTask?.["id"], - displayName: result.body.jobManagerTask?.["displayName"], - commandLine: result.body.jobManagerTask?.["commandLine"], - containerSettings: !result.body.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobManagerTask?.containerSettings?.["imageName"], - registry: !result.body.jobManagerTask?.containerSettings - ?.registry - ? undefined - : { - username: - result.body.jobManagerTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobManagerTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobManagerTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.jobManagerTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.jobManagerTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - result.body.jobManagerTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: (result.body.jobManagerTask?.["outputFiles"] ?? []).map( - (p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }) - ), - environmentSettings: ( - result.body.jobManagerTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - result.body.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - result.body.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: result.body.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - result.body.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !result.body.jobManagerTask?.userIdentity - ? undefined - : { - username: - result.body.jobManagerTask?.userIdentity?.["username"], - autoUser: !result.body.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: result.body.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - result.body.jobManagerTask?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !result.body.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - result.body.jobManagerTask?.authenticationTokenSettings?.[ - "access" - ], - }, - allowLowPriorityNode: - result.body.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !result.body.jobPreparationTask - ? undefined - : { - id: result.body.jobPreparationTask?.["id"], - commandLine: result.body.jobPreparationTask?.["commandLine"], - containerSettings: !result.body.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobPreparationTask?.containerSettings?.[ - "imageName" - ], - registry: !result.body.jobPreparationTask?.containerSettings - ?.registry - ? undefined - : { - username: - result.body.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.jobPreparationTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - result.body.jobPreparationTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - result.body.jobPreparationTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - result.body.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - result.body.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - result.body.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: result.body.jobPreparationTask?.["waitForSuccess"], - userIdentity: !result.body.jobPreparationTask?.userIdentity - ? undefined - : { - username: - result.body.jobPreparationTask?.userIdentity?.["username"], - autoUser: !result.body.jobPreparationTask?.userIdentity - ?.autoUser - ? undefined - : { - scope: - result.body.jobPreparationTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - result.body.jobPreparationTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - result.body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !result.body.jobReleaseTask - ? undefined - : { - id: result.body.jobReleaseTask?.["id"], - commandLine: result.body.jobReleaseTask?.["commandLine"], - containerSettings: !result.body.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.jobReleaseTask?.containerSettings?.["imageName"], - registry: !result.body.jobReleaseTask?.containerSettings - ?.registry - ? undefined - : { - username: - result.body.jobReleaseTask?.containerSettings - ?.registry?.["username"], - password: - result.body.jobReleaseTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.jobReleaseTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.jobReleaseTask - ?.containerSettings?.registry?.identityReference - ? undefined - : { - resourceId: - result.body.jobReleaseTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - result.body.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - result.body.jobReleaseTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - result.body.jobReleaseTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: result.body.jobReleaseTask?.["maxWallClockTime"], - retentionTime: result.body.jobReleaseTask?.["retentionTime"], - userIdentity: !result.body.jobReleaseTask?.userIdentity - ? undefined - : { - username: - result.body.jobReleaseTask?.userIdentity?.["username"], - autoUser: !result.body.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - result.body.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: ( - result.body["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: result.body.poolInfo["poolId"], - autoPoolSpecification: !result.body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - result.body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - result.body.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - result.body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !result.body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - result.body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - result.body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSKUId: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.containerConfiguration - ? undefined - : { - type: result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - result.body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !result.body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - result.body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !result.body.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - result.body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !result.body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.["provision"], - ipAddressIds: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - result.body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.["imageName"], - registry: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - result.body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - userIdentity: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask?.userIdentity - ? undefined - : { - username: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !result.body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - result.body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - result.body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: ( - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "metadata" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], - }, - })), - targetNodeCommunicationMode: - result.body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: result.body["onAllTasksComplete"], - onTaskFailure: result.body["onTaskFailure"], - networkConfiguration: !result.body.networkConfiguration - ? undefined - : { subnetId: result.body.networkConfiguration?.["subnetId"] }, - metadata: (result.body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - executionInfo: !result.body.executionInfo - ? undefined - : { - startTime: new Date(result.body.executionInfo?.["startTime"]), - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - poolId: result.body.executionInfo?.["poolId"], - schedulingError: !result.body.executionInfo?.schedulingError - ? undefined - : { - category: - result.body.executionInfo?.schedulingError?.["category"], - code: result.body.executionInfo?.schedulingError?.["code"], - message: - result.body.executionInfo?.schedulingError?.["message"], - details: ( - result.body.executionInfo?.schedulingError?.["details"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - terminateReason: result.body.executionInfo?.["terminateReason"], - }, - stats: !result.body.stats - ? undefined - : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - numSucceededTasks: result.body.stats?.["numSucceededTasks"], - numFailedTasks: result.body.stats?.["numFailedTasks"], - numTaskRetries: result.body.stats?.["numTaskRetries"], - waitTime: result.body.stats?.["waitTime"], - }, - }; -} - -/** Gets information about the specified Job. */ -export async function getJob( - context: Client, - jobId: string, - options: GetJobOptions = { requestOptions: {} } -): Promise { - const result = await _getJobSend(context, jobId, options); - return _getJobDeserialize(result); -} - -export function _updateJobSend( - context: Client, - jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs/{jobId}", jobId).patch({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - poolInfo: !body.poolInfo - ? undefined - : { - poolId: body.poolInfo?.["poolId"], - autoPoolSpecification: !body.poolInfo?.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo?.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo?.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.poolInfo?.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo?.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "vmSize" - ], - cloudServiceConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo?.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - }, - nodeAgentSKUId: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" - ], - containerConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" - ] ?? [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo?.autoPoolSpecification - ?.pool?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo?.autoPoolSpecification - ?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo - ?.autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo?.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.poolInfo?.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo?.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "username" - ], - password: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.poolInfo - ?.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - ?.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.userIdentity - ? undefined - : { - username: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo - ?.autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo?.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo?.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], - }, - certificateReferences: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "metadata" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: ( - body.poolInfo?.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, - })), - targetNodeCommunicationMode: - body.poolInfo?.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); + }; +} + +/** + * 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 evaluatePoolAutoScale( + context: Client, + poolId: string, + body: BatchPoolEvaluateAutoScaleOptions, + options: EvaluatePoolAutoScaleOptions = { requestOptions: {} } +): Promise { + const result = await _evaluatePoolAutoScaleSend( + context, + poolId, + body, + options + ); + return _evaluatePoolAutoScaleDeserialize(result); +} + +export function _resizePoolSend( + context: Client, + poolId: string, + body: BatchPoolResizeOptions, + options: ResizePoolOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools/{poolId}/resize", poolId) + .post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + targetDedicatedNodes: body["targetDedicatedNodes"], + targetLowPriorityNodes: body["targetLowPriorityNodes"], + resizeTimeout: body["resizeTimeout"], + nodeDeallocationOption: body["nodeDeallocationOption"], + }, + }); } -export async function _updateJobDeserialize( - result: UpdateJob200Response | UpdateJobDefaultResponse +export async function _resizePoolDeserialize( + result: ResizePool202Response | ResizePoolDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -4295,2667 +2254,3893 @@ export async function _updateJobDeserialize( } /** - * 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. + * 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 updateJob( +export async function resizePool( context: Client, - jobId: string, - body: BatchJobUpdateOptions, - options: UpdateJobOptions = { requestOptions: {} } + poolId: string, + body: BatchPoolResizeOptions, + options: ResizePoolOptions = { requestOptions: {} } ): Promise { - const result = await _updateJobSend(context, jobId, body, options); - return _updateJobDeserialize(result); + const result = await _resizePoolSend(context, poolId, body, options); + return _resizePoolDeserialize(result); } -export function _replaceJobSend( +export function _stopPoolResizeSend( context: Client, - jobId: string, - body: BatchJob, - options: ReplaceJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs/{jobId}", jobId).put({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - poolInfo: { - poolId: body.poolInfo["poolId"], - autoPoolSpecification: !body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" + poolId: string, + options: StopPoolResizeOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools/{poolId}/stopresize", poolId) + .post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _stopPoolResizeDeserialize( + result: StopPoolResize202Response | StopPoolResizeDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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, + options: StopPoolResizeOptions = { requestOptions: {} } +): Promise { + const result = await _stopPoolResizeSend(context, poolId, options); + return _stopPoolResizeDeserialize(result); +} + +export function _replacePoolPropertiesSend( + context: Client, + poolId: string, + body: BatchPoolReplaceOptions, + options: ReplacePoolPropertiesOptions = { requestOptions: {} } +): StreamableMethod< + ReplacePoolProperties204Response | ReplacePoolPropertiesDefaultResponse +> { + return context + .path("/pools/{poolId}/updateproperties", poolId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + startTask: !body.startTask + ? undefined + : { + commandLine: body.startTask?.["commandLine"], + containerSettings: !body.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.startTask?.containerSettings?.[ + "containerRunOptions" ], - networkConfiguration: !body.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration + imageName: body.startTask?.containerSettings?.["imageName"], + registry: !body.startTask?.containerSettings?.registry ? undefined : { - subnetId: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" + username: + body.startTask?.containerSettings?.registry?.[ + "username" ], - endpointConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration + password: + body.startTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.startTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.startTask?.containerSettings + ?.registry?.identityReference ? undefined : { - provision: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], + resourceId: + body.startTask?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - enableAcceleratedNetworking: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], }, - startTask: !body.poolInfo.autoPoolSpecification?.pool - ?.startTask + workingDirectory: + body.startTask?.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body.startTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !body.startTask?.userIdentity + ? undefined + : { + username: body.startTask?.userIdentity?.["username"], + autoUser: !body.startTask?.userIdentity?.autoUser ? undefined : { - commandLine: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings?.registry - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], + scope: + body.startTask?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, - certificateReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration + }, + maxTaskRetryCount: body.startTask?.["maxTaskRetryCount"], + waitForSuccess: body.startTask?.["waitForSuccess"], + }, + certificateReferences: (body["certificateReferences"] ?? []).map( + (p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + }) + ), + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + targetNodeCommunicationMode: body["targetNodeCommunicationMode"], + }, + }); +} + +export async function _replacePoolPropertiesDeserialize( + result: + | ReplacePoolProperties204Response + | ReplacePoolPropertiesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + poolId: string, + body: BatchPoolReplaceOptions, + options: ReplacePoolPropertiesOptions = { requestOptions: {} } +): Promise { + const result = await _replacePoolPropertiesSend( + context, + poolId, + body, + options + ); + return _replacePoolPropertiesDeserialize(result); +} + +export function _removeNodesSend( + context: Client, + poolId: string, + body: NodeRemoveOptions, + options: RemoveNodesOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/pools/{poolId}/removenodes", poolId) + .post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + nodeList: body["nodeList"], + resizeTimeout: body["resizeTimeout"], + nodeDeallocationOption: body["nodeDeallocationOption"], + }, + }); +} + +export async function _removeNodesDeserialize( + result: RemoveNodes202Response | RemoveNodesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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 removeNodes( + context: Client, + poolId: string, + body: NodeRemoveOptions, + options: RemoveNodesOptions = { requestOptions: {} } +): Promise { + const result = await _removeNodesSend(context, poolId, body, options); + return _removeNodesDeserialize(result); +} + +export function _listSupportedImagesSend( + context: Client, + options: ListSupportedImagesOptions = { requestOptions: {} } +): StreamableMethod< + ListSupportedImages200Response | ListSupportedImagesDefaultResponse +> { + return context + .path("/supportedimages") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + }, + }); +} + +export async function _listSupportedImagesDeserialize( + result: ListSupportedImages200Response | ListSupportedImagesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + nodeAgentSKUId: p["nodeAgentSKUId"], + imageReference: { + publisher: p.imageReference["publisher"], + offer: p.imageReference["offer"], + sku: p.imageReference["sku"], + version: p.imageReference["version"], + virtualMachineImageId: p.imageReference["virtualMachineImageId"], + exactVersion: p.imageReference["exactVersion"], + }, + osType: p["osType"], + capabilities: p["capabilities"], + batchSupportEndOfLife: + p["batchSupportEndOfLife"] !== undefined + ? new Date(p["batchSupportEndOfLife"]) + : undefined, + verificationType: p["verificationType"], + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists all Virtual Machine Images supported by the Azure Batch service. */ +export function listSupportedImages( + context: Client, + options: ListSupportedImagesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listSupportedImagesSend, + _listSupportedImagesDeserialize, + [context, options] + ); +} + +export function _listPoolNodeCountsSend( + context: Client, + options: ListPoolNodeCountsOptions = { requestOptions: {} } +): StreamableMethod< + ListPoolNodeCounts200Response | ListPoolNodeCountsDefaultResponse +> { + return context + .path("/nodecounts") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + }, + }); +} + +export async function _listPoolNodeCountsDeserialize( + result: ListPoolNodeCounts200Response | ListPoolNodeCountsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + poolId: p["poolId"], + dedicated: !p.dedicated + ? undefined + : { + creating: p.dedicated?.["creating"], + idle: p.dedicated?.["idle"], + offline: p.dedicated?.["offline"], + preempted: p.dedicated?.["preempted"], + rebooting: p.dedicated?.["rebooting"], + reimaging: p.dedicated?.["reimaging"], + running: p.dedicated?.["running"], + starting: p.dedicated?.["starting"], + startTaskFailed: p.dedicated?.["startTaskFailed"], + leavingPool: p.dedicated?.["leavingPool"], + unknown: p.dedicated?.["unknown"], + unusable: p.dedicated?.["unusable"], + waitingForStartTask: p.dedicated?.["waitingForStartTask"], + total: p.dedicated?.["total"], + }, + lowPriority: !p.lowPriority + ? undefined + : { + creating: p.lowPriority?.["creating"], + idle: p.lowPriority?.["idle"], + offline: p.lowPriority?.["offline"], + preempted: p.lowPriority?.["preempted"], + rebooting: p.lowPriority?.["rebooting"], + reimaging: p.lowPriority?.["reimaging"], + running: p.lowPriority?.["running"], + starting: p.lowPriority?.["starting"], + startTaskFailed: p.lowPriority?.["startTaskFailed"], + leavingPool: p.lowPriority?.["leavingPool"], + unknown: p.lowPriority?.["unknown"], + unusable: p.lowPriority?.["unusable"], + waitingForStartTask: p.lowPriority?.["waitingForStartTask"], + total: p.lowPriority?.["total"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** + * 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, + options: ListPoolNodeCountsOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listPoolNodeCountsSend, + _listPoolNodeCountsDeserialize, + [context, options] + ); +} + +export function _deleteJobSend( + context: Client, + jobId: string, + options: DeleteJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs/{jobId}", jobId) + .delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _deleteJobDeserialize( + result: DeleteJob202Response | DeleteJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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: DeleteJobOptions = { requestOptions: {} } +): Promise { + const result = await _deleteJobSend(context, jobId, options); + return _deleteJobDeserialize(result); +} + +export function _getJobSend( + context: Client, + jobId: string, + options: GetJobOptions = { 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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); +} + +export async function _getJobDeserialize( + result: GetJob200Response | GetJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + id: result.body["id"], + displayName: result.body["displayName"], + usesTaskDependencies: result.body["usesTaskDependencies"], + url: result.body["url"], + eTag: result.body["eTag"], + lastModified: + result.body["lastModified"] !== undefined + ? new Date(result.body["lastModified"]) + : undefined, + creationTime: + result.body["creationTime"] !== undefined + ? new Date(result.body["creationTime"]) + : undefined, + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + priority: result.body["priority"], + allowTaskPreemption: result.body["allowTaskPreemption"], + maxParallelTasks: result.body["maxParallelTasks"], + constraints: !result.body.constraints + ? undefined + : { + maxWallClockTime: result.body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: result.body.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !result.body.jobManagerTask + ? undefined + : { + id: result.body.jobManagerTask?.["id"], + displayName: result.body.jobManagerTask?.["displayName"], + commandLine: result.body.jobManagerTask?.["commandLine"], + containerSettings: !result.body.jobManagerTask?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.jobManagerTask?.containerSettings?.["imageName"], + registry: !result.body.jobManagerTask?.containerSettings + ?.registry + ? undefined + : { + username: + result.body.jobManagerTask?.containerSettings + ?.registry?.["username"], + password: + result.body.jobManagerTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.jobManagerTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body.jobManagerTask + ?.containerSettings?.registry?.identityReference ? undefined : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], + resourceId: + result.body.jobManagerTask?.containerSettings + ?.registry?.identityReference?.["resourceId"], }, - })), - metadata: ( - body.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration + }, + workingDirectory: + result.body.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + result.body.jobManagerTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: (result.body.jobManagerTask?.["outputFiles"] ?? []).map( + (p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference ? undefined : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], }, - cifsMountConfiguration: !p.cifsMountConfiguration + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + }) + ), + environmentSettings: ( + result.body.jobManagerTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobManagerTask?.constraints?.["maxWallClockTime"], + retentionTime: + result.body.jobManagerTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + result.body.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: result.body.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + result.body.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !result.body.jobManagerTask?.userIdentity + ? undefined + : { + username: + result.body.jobManagerTask?.userIdentity?.["username"], + autoUser: !result.body.jobManagerTask?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobManagerTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + result.body.jobManagerTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + runExclusive: result.body.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + result.body.jobManagerTask?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !result.body.jobManagerTask + ?.authenticationTokenSettings + ? undefined + : { + access: + result.body.jobManagerTask?.authenticationTokenSettings?.[ + "access" + ], + }, + allowLowPriorityNode: + result.body.jobManagerTask?.["allowLowPriorityNode"], + }, + jobPreparationTask: !result.body.jobPreparationTask + ? undefined + : { + id: result.body.jobPreparationTask?.["id"], + commandLine: result.body.jobPreparationTask?.["commandLine"], + containerSettings: !result.body.jobPreparationTask?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobPreparationTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.jobPreparationTask?.containerSettings?.[ + "imageName" + ], + registry: !result.body.jobPreparationTask?.containerSettings + ?.registry + ? undefined + : { + username: + result.body.jobPreparationTask?.containerSettings + ?.registry?.["username"], + password: + result.body.jobPreparationTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.jobPreparationTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body.jobPreparationTask + ?.containerSettings?.registry?.identityReference ? undefined : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], + resourceId: + result.body.jobPreparationTask?.containerSettings + ?.registry?.identityReference?.["resourceId"], }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], - }, - })), - targetNodeCommunicationMode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _replaceJobDeserialize( - result: ReplaceJob200Response | ReplaceJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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, - body: BatchJob, - options: ReplaceJobOptions = { requestOptions: {} } -): Promise { - const result = await _replaceJobSend(context, jobId, body, options); - return _replaceJobDeserialize(result); -} - -export function _disableJobSend( - context: Client, - jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs/{jobId}/disable", jobId).post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { disableTasks: body["disableTasks"] }, - }); -} - -export async function _disableJobDeserialize( - result: DisableJob202Response | DisableJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - jobId: string, - body: BatchJobDisableOptions, - options: DisableJobOptions = { requestOptions: {} } -): Promise { - const result = await _disableJobSend(context, jobId, body, options); - return _disableJobDeserialize(result); -} - -export function _enableJobSend( - context: Client, - jobId: string, - options: EnableJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs/{jobId}/enable", jobId).post({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _enableJobDeserialize( - result: EnableJob202Response | EnableJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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 enableJob( - context: Client, - jobId: string, - options: EnableJobOptions = { requestOptions: {} } -): Promise { - const result = await _enableJobSend(context, jobId, options); - return _enableJobDeserialize(result); -} - -export function _terminateJobSend( - context: Client, - jobId: string, - body: BatchJobTerminateOptions, - options: TerminateJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs/{jobId}/terminate", jobId).post({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { terminateReason: body["terminateReason"] }, - }); -} - -export async function _terminateJobDeserialize( - result: TerminateJob202Response | TerminateJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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, - body: BatchJobTerminateOptions, - options: TerminateJobOptions = { requestOptions: {} } -): Promise { - const result = await _terminateJobSend(context, jobId, body, options); - return _terminateJobDeserialize(result); -} - -export function _createJobSend( - context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs").post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - usesTaskDependencies: body["usesTaskDependencies"], - priority: body["priority"], - allowTaskPreemption: body["allowTaskPreemption"], - maxParallelTasks: body["maxParallelTasks"], - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobManagerTask + }, + workingDirectory: + result.body.jobPreparationTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + result.body.jobPreparationTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + result.body.jobPreparationTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobPreparationTask?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + result.body.jobPreparationTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + result.body.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: result.body.jobPreparationTask?.["waitForSuccess"], + userIdentity: !result.body.jobPreparationTask?.userIdentity + ? undefined + : { + username: + result.body.jobPreparationTask?.userIdentity?.["username"], + autoUser: !result.body.jobPreparationTask?.userIdentity + ?.autoUser + ? undefined + : { + scope: + result.body.jobPreparationTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + result.body.jobPreparationTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + result.body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], + }, + jobReleaseTask: !result.body.jobReleaseTask + ? undefined + : { + id: result.body.jobReleaseTask?.["id"], + commandLine: result.body.jobReleaseTask?.["commandLine"], + containerSettings: !result.body.jobReleaseTask?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.jobReleaseTask?.containerSettings?.["imageName"], + registry: !result.body.jobReleaseTask?.containerSettings + ?.registry + ? undefined + : { + username: + result.body.jobReleaseTask?.containerSettings + ?.registry?.["username"], + password: + result.body.jobReleaseTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.jobReleaseTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body.jobReleaseTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + result.body.jobReleaseTask?.containerSettings + ?.registry?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + result.body.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + result.body.jobReleaseTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + result.body.jobReleaseTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: result.body.jobReleaseTask?.["maxWallClockTime"], + retentionTime: result.body.jobReleaseTask?.["retentionTime"], + userIdentity: !result.body.jobReleaseTask?.userIdentity + ? undefined + : { + username: + result.body.jobReleaseTask?.userIdentity?.["username"], + autoUser: !result.body.jobReleaseTask?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobReleaseTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + result.body.jobReleaseTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + }, + commonEnvironmentSettings: ( + result.body["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: result.body.poolInfo["poolId"], + autoPoolSpecification: !result.body.poolInfo.autoPoolSpecification ? undefined : { - id: body.jobManagerTask?.["id"], - displayName: body.jobManagerTask?.["displayName"], - commandLine: body.jobManagerTask?.["commandLine"], - containerSettings: !body.jobManagerTask?.containerSettings + autoPoolIdPrefix: + result.body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + result.body.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + result.body.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !result.body.poolInfo.autoPoolSpecification?.pool ? undefined : { - containerRunOptions: - body.jobManagerTask?.containerSettings?.[ - "containerRunOptions" + displayName: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" ], - imageName: - body.jobManagerTask?.containerSettings?.["imageName"], - registry: !body.jobManagerTask?.containerSettings?.registry + vmSize: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "vmSize" + ], + cloudServiceConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration ? undefined : { - username: - body.jobManagerTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.jobManagerTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.jobManagerTask?.containerSettings?.registry?.[ - "registryServer" + osFamily: + result.body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + result.body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" + ], + sku: result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" ], - identityReference: !body.jobManagerTask - ?.containerSettings?.registry?.identityReference + version: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + exactVersion: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "exactVersion" + ], + }, + nodeAgentSKUId: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.windowsConfiguration ? undefined : { - resourceId: - body.jobManagerTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], + enableAutomaticUpdates: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.containerConfiguration + ? undefined + : { + type: result.body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + }, + diskEncryptionConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], }, - }, - workingDirectory: - body.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: (body.jobManagerTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - outputFiles: (body.jobManagerTask?.["outputFiles"] ?? []).map( - (p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference + nodePlacementConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration ? undefined : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], + policy: + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] + extensions: ( + result.body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? [] ).map((p) => ({ name: p["name"], - value: p["value"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], })), + osDisk: !result.body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !result.body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + result.body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - }) - ), - environmentSettings: ( - body.jobManagerTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobManagerTask?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: body.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: body.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobManagerTask?.userIdentity - ? undefined - : { - username: body.jobManagerTask?.userIdentity?.["username"], - autoUser: !body.jobManagerTask?.userIdentity?.autoUser + taskSlotsPerNode: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !result.body.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy ? undefined : { - scope: - body.jobManagerTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], + nodeFillType: + result.body.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], }, - }, - runExclusive: body.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobManagerTask?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - body.jobManagerTask?.authenticationTokenSettings?.[ - "access" + resizeTimeout: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" ], - }, - allowLowPriorityNode: body.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !body.jobPreparationTask - ? undefined - : { - id: body.jobPreparationTask?.["id"], - commandLine: body.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" + targetDedicatedNodes: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" ], - imageName: - body.jobPreparationTask?.containerSettings?.["imageName"], - registry: !body.jobPreparationTask?.containerSettings - ?.registry + targetLowPriorityNodes: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration ? undefined : { - username: - body.jobPreparationTask?.containerSettings - ?.registry?.["username"], - password: - body.jobPreparationTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobPreparationTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.jobPreparationTask - ?.containerSettings?.registry?.identityReference + subnetId: + result.body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + result.body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.endpointConfiguration ? undefined : { - resourceId: - body.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], + inboundNATPools: ( + result.body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), }, - }, - workingDirectory: - body.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobPreparationTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobPreparationTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobPreparationTask?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobPreparationTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobPreparationTask?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: body.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobPreparationTask?.userIdentity - ? undefined - : { - username: body.jobPreparationTask?.userIdentity?.["username"], - autoUser: !body.jobPreparationTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobPreparationTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobPreparationTask?.userIdentity?.autoUser?.[ - "elevationLevel" + publicIPAddressConfiguration: !result.body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + result.body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.["provision"], + ipAddressIds: + result.body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + result.body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" ], }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !body.jobReleaseTask - ? undefined - : { - id: body.jobReleaseTask?.["id"], - commandLine: body.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobReleaseTask?.containerSettings?.["imageName"], - registry: !body.jobReleaseTask?.containerSettings?.registry + startTask: !result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask ? undefined : { - username: - body.jobReleaseTask?.containerSettings?.registry?.[ - "username" - ], - password: - body.jobReleaseTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - body.jobReleaseTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobReleaseTask - ?.containerSettings?.registry?.identityReference + commandLine: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !result.body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings ? undefined : { - resourceId: - body.jobReleaseTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], + containerRunOptions: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.["imageName"], + registry: !result.body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ? undefined + : { + username: + result.body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["username"], + password: + result.body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + result.body.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], }, + resourceFiles: ( + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + userIdentity: !result.body.poolInfo + .autoPoolSpecification?.pool?.startTask?.userIdentity + ? undefined + : { + username: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !result.body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + result.body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + result.body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], }, - workingDirectory: - body.jobReleaseTask?.containerSettings?.[ - "workingDirectory" + certificateReferences: ( + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" ], - }, - resourceFiles: (body.jobReleaseTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - body.jobReleaseTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: body.jobReleaseTask?.["maxWallClockTime"], - retentionTime: body.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobReleaseTask?.userIdentity - ? undefined - : { - username: body.jobReleaseTask?.userIdentity?.["username"], - autoUser: !body.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobReleaseTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - body.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: (body["commonEnvironmentSettings"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), - poolInfo: { - poolId: body.poolInfo["poolId"], - autoPoolSpecification: !body.poolInfo.autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !body.poolInfo.autoPoolSpecification?.pool - ? undefined - : { - displayName: - body.poolInfo.autoPoolSpecification?.pool?.[ - "displayName" - ], - vmSize: - body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration + userAccounts: ( + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined : { - osFamily: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], }, - virtualMachineConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.virtualMachineConfiguration + windowsUserConfiguration: !p.windowsUserConfiguration ? undefined : { - imageReference: { - publisher: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" + loginMode: p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" ], - offer: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" ], - sku: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" ], - virtualMachineImageId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" + sasKey: + p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, }, - nodeAgentSKUId: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - taskSlotsPerNode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy + cifsMountConfiguration: !p.cifsMountConfiguration ? undefined : { - nodeFillType: - body.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], }, - resizeTimeout: - body.poolInfo.autoPoolSpecification?.pool?.[ - "resizeTimeout" - ], - targetDedicatedNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" - ], - autoScaleFormula: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" + azureFileShareConfiguration: !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: + p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.["mountOptions"], + }, + })), + targetNodeCommunicationMode: + result.body.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + onAllTasksComplete: result.body["onAllTasksComplete"], + onTaskFailure: result.body["onTaskFailure"], + networkConfiguration: !result.body.networkConfiguration + ? undefined + : { subnetId: result.body.networkConfiguration?.["subnetId"] }, + metadata: (result.body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + executionInfo: !result.body.executionInfo + ? undefined + : { + startTime: new Date(result.body.executionInfo?.["startTime"]), + endTime: + result.body.executionInfo?.["endTime"] !== undefined + ? new Date(result.body.executionInfo?.["endTime"]) + : undefined, + poolId: result.body.executionInfo?.["poolId"], + schedulingError: !result.body.executionInfo?.schedulingError + ? undefined + : { + category: + result.body.executionInfo?.schedulingError?.["category"], + code: result.body.executionInfo?.schedulingError?.["code"], + message: + result.body.executionInfo?.schedulingError?.["message"], + details: ( + result.body.executionInfo?.schedulingError?.["details"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + terminateReason: result.body.executionInfo?.["terminateReason"], + }, + stats: !result.body.stats + ? undefined + : { + url: result.body.stats?.["url"], + startTime: new Date(result.body.stats?.["startTime"]), + lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), + userCPUTime: result.body.stats?.["userCPUTime"], + kernelCPUTime: result.body.stats?.["kernelCPUTime"], + wallClockTime: result.body.stats?.["wallClockTime"], + readIOps: result.body.stats?.["readIOps"], + writeIOps: result.body.stats?.["writeIOps"], + readIOGiB: result.body.stats?.["readIOGiB"], + writeIOGiB: result.body.stats?.["writeIOGiB"], + numSucceededTasks: result.body.stats?.["numSucceededTasks"], + numFailedTasks: result.body.stats?.["numFailedTasks"], + numTaskRetries: result.body.stats?.["numTaskRetries"], + waitTime: result.body.stats?.["waitTime"], + }, + }; +} + +/** Gets information about the specified Job. */ +export async function getJob( + context: Client, + jobId: string, + options: GetJobOptions = { requestOptions: {} } +): Promise { + const result = await _getJobSend(context, jobId, options); + return _getJobDeserialize(result); +} + +export function _updateJobSend( + context: Client, + jobId: string, + body: BatchJobUpdateOptions, + options: UpdateJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs/{jobId}", jobId) + .patch({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + poolInfo: !body.poolInfo + ? undefined + : { + poolId: body.poolInfo?.["poolId"], + autoPoolSpecification: !body.poolInfo?.autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.poolInfo?.autoPoolSpecification?.[ + "autoPoolIdPrefix" ], - enableInterNodeCommunication: - body.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" + poolLifetimeOption: + body.poolInfo?.autoPoolSpecification?.[ + "poolLifetimeOption" ], - networkConfiguration: !body.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration + keepAlive: + body.poolInfo?.autoPoolSpecification?.["keepAlive"], + pool: !body.poolInfo?.autoPoolSpecification?.pool ? undefined : { - subnetId: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" + displayName: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "displayName" ], - endpointConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration + vmSize: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "vmSize" + ], + cloudServiceConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.cloudServiceConfiguration ? undefined : { - inboundNATPools: ( - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" + osFamily: + body.poolInfo?.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.poolInfo?.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.imageReference["sku"], + version: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + }, + nodeAgentSKUId: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" ] ?? [] ).map((p) => ({ name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], })), + osDisk: !body.poolInfo?.autoPoolSpecification + ?.pool?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.poolInfo + ?.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, }, - publicIPAddressConfiguration: !body.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration + taskSlotsPerNode: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !body.poolInfo + ?.autoPoolSpecification?.pool?.taskSchedulingPolicy ? undefined : { - provision: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" + nodeFillType: + body.poolInfo?.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], + targetDedicatedNodes: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" ], - ipAddressIds: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" + endpointConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.poolInfo?.autoPoolSpecification + ?.pool?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: + p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.poolInfo?.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.poolInfo?.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.poolInfo?.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" ], }, - enableAcceleratedNetworking: - body.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["commandLine"], - containerSettings: !body.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings + startTask: !body.poolInfo?.autoPoolSpecification?.pool + ?.startTask ? undefined : { - containerRunOptions: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings?.registry + commandLine: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.containerSettings ? undefined : { - username: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body.poolInfo - .autoPoolSpecification?.pool?.startTask + containerRunOptions: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask ?.containerSettings?.registry - ?.identityReference ? undefined : { - resourceId: + username: body.poolInfo - .autoPoolSpecification?.pool + ?.autoPoolSpecification?.pool ?.startTask?.containerSettings - ?.registry?.identityReference?.[ - "resourceId" - ], + ?.registry?.["username"], + password: + body.poolInfo + ?.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.poolInfo + ?.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body.poolInfo + ?.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.poolInfo + ?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, }, + workingDirectory: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.[ + "workingDirectory" + ], }, - workingDirectory: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], + resourceFiles: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + body.poolInfo?.autoPoolSpecification + ?.pool?.startTask?.userIdentity?.[ + "username" + ], + autoUser: !body.poolInfo + ?.autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.poolInfo + ?.autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.poolInfo + ?.autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + body.poolInfo?.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], }, - resourceFiles: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["resourceFiles"] ?? [] + certificateReferences: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration ? undefined : { - resourceId: - p.identityReference?.["resourceId"], + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], }, + windowsUserConfiguration: + !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, })), - environmentSettings: ( - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["environmentSettings"] ?? [] + metadata: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "metadata" + ] ?? [] ).map((p) => ({ name: p["name"], value: p["value"], })), - userIdentity: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ? undefined - : { - username: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser - ? undefined - : { - scope: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - maxTaskRetryCount: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["maxTaskRetryCount"], - waitForSuccess: - body.poolInfo.autoPoolSpecification?.pool - ?.startTask?.["waitForSuccess"], + mountConfiguration: ( + body.poolInfo?.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.[ + "resourceId" + ], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: + p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: + p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.poolInfo?.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], }, - certificateReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration + }, + }, + onAllTasksComplete: body["onAllTasksComplete"], + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); +} + +export async function _updateJobDeserialize( + result: UpdateJob200Response | UpdateJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + jobId: string, + body: BatchJobUpdateOptions, + options: UpdateJobOptions = { requestOptions: {} } +): Promise { + const result = await _updateJobSend(context, jobId, body, options); + return _updateJobDeserialize(result); +} + +export function _replaceJobSend( + context: Client, + jobId: string, + body: BatchJob, + options: ReplaceJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs/{jobId}", jobId) + .put({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + poolInfo: { + poolId: body.poolInfo["poolId"], + autoPoolSpecification: !body.poolInfo.autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !body.poolInfo.autoPoolSpecification?.pool + ? undefined + : { + displayName: + body.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" + ], + vmSize: + body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration ? undefined : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], + osFamily: + body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], }, - windowsUserConfiguration: !p.windowsUserConfiguration + virtualMachineConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration ? undefined : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" + imageReference: { + publisher: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" + offer: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" ], - sasKey: - p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" + sku: body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" + virtualMachineImageId: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], + nodeAgentSKUId: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? + [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + }, + diskEncryptionConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, }, - cifsMountConfiguration: !p.cifsMountConfiguration + taskSlotsPerNode: + body.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification + ?.pool?.taskSchedulingPolicy ? undefined : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], + nodeFillType: + body.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], - }, - })), - targetNodeCommunicationMode: - body.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: body["onAllTasksComplete"], - onTaskFailure: body["onTaskFailure"], - networkConfiguration: !body.networkConfiguration - ? undefined - : { subnetId: body.networkConfiguration?.["subnetId"] }, - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); -} - -export async function _createJobDeserialize( - result: CreateJob201Response | CreateJobDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** - * 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( - context: Client, - body: BatchJobCreateOptions, - options: CreateJobOptions = { requestOptions: {} } -): Promise { - const result = await _createJobSend(context, body, options); - return _createJobDeserialize(result); -} - -export function _listJobsSend( - context: Client, - options: ListJobsOptions = { requestOptions: {} } -): StreamableMethod { - return context.path("/jobs").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _listJobsDeserialize( - result: ListJobs200Response | ListJobsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - value: (result.body["value"] ?? []).map((p) => ({ - id: p["id"], - displayName: p["displayName"], - usesTaskDependencies: p["usesTaskDependencies"], - url: p["url"], - eTag: p["eTag"], - lastModified: - p["lastModified"] !== undefined - ? new Date(p["lastModified"]) - : undefined, - creationTime: - p["creationTime"] !== undefined - ? new Date(p["creationTime"]) - : undefined, - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - priority: p["priority"], - allowTaskPreemption: p["allowTaskPreemption"], - maxParallelTasks: p["maxParallelTasks"], - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !p.jobManagerTask - ? undefined - : { - id: p.jobManagerTask?.["id"], - displayName: p.jobManagerTask?.["displayName"], - commandLine: p.jobManagerTask?.["commandLine"], - containerSettings: !p.jobManagerTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: p.jobManagerTask?.containerSettings?.["imageName"], - registry: !p.jobManagerTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobManagerTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobManagerTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobManagerTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobManagerTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - p.jobManagerTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - p.jobManagerTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (p.jobManagerTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - outputFiles: (p.jobManagerTask?.["outputFiles"] ?? []).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference + resizeTimeout: + body.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], + targetDedicatedNodes: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + body.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + body.poolInfo.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration ? undefined : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" + subnetId: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" ], }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - p.jobManagerTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !p.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobManagerTask?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobManagerTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobManagerTask?.constraints?.["maxTaskRetryCount"], - }, - requiredSlots: p.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: p.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !p.jobManagerTask?.userIdentity - ? undefined - : { - username: p.jobManagerTask?.userIdentity?.["username"], - autoUser: !p.jobManagerTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobManagerTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.jobManagerTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - runExclusive: p.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - p.jobManagerTask?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !p.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - p.jobManagerTask?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: p.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !p.jobPreparationTask - ? undefined - : { - id: p.jobPreparationTask?.["id"], - commandLine: p.jobPreparationTask?.["commandLine"], - containerSettings: !p.jobPreparationTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobPreparationTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.jobPreparationTask?.containerSettings?.["imageName"], - registry: !p.jobPreparationTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobPreparationTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobPreparationTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobPreparationTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobPreparationTask - ?.containerSettings?.registry?.identityReference + startTask: !body.poolInfo.autoPoolSpecification?.pool + ?.startTask + ? undefined + : { + commandLine: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry + ? undefined + : { + username: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ? undefined + : { + username: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + maxTaskRetryCount: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], + }, + certificateReferences: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration ? undefined : { - resourceId: - p.jobPreparationTask?.containerSettings - ?.registry?.identityReference?.["resourceId"], + loginMode: + p.windowsUserConfiguration?.["loginMode"], }, - }, - workingDirectory: - p.jobPreparationTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: (p.jobPreparationTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - p.jobPreparationTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !p.jobPreparationTask?.constraints - ? undefined - : { - maxWallClockTime: - p.jobPreparationTask?.constraints?.["maxWallClockTime"], - retentionTime: - p.jobPreparationTask?.constraints?.["retentionTime"], - maxTaskRetryCount: - p.jobPreparationTask?.constraints?.["maxTaskRetryCount"], - }, - waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], - userIdentity: !p.jobPreparationTask?.userIdentity - ? undefined - : { - username: p.jobPreparationTask?.userIdentity?.["username"], - autoUser: !p.jobPreparationTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobPreparationTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.jobPreparationTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - rerunOnNodeRebootAfterSuccess: - p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], - }, - jobReleaseTask: !p.jobReleaseTask - ? undefined - : { - id: p.jobReleaseTask?.["id"], - commandLine: p.jobReleaseTask?.["commandLine"], - containerSettings: !p.jobReleaseTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: p.jobReleaseTask?.containerSettings?.["imageName"], - registry: !p.jobReleaseTask?.containerSettings?.registry - ? undefined - : { - username: - p.jobReleaseTask?.containerSettings?.registry?.[ - "username" - ], - password: - p.jobReleaseTask?.containerSettings?.registry?.[ - "password" - ], - registryServer: - p.jobReleaseTask?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !p.jobReleaseTask?.containerSettings - ?.registry?.identityReference + })), + metadata: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - resourceId: - p.jobReleaseTask?.containerSettings?.registry - ?.identityReference?.["resourceId"], + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - }, - workingDirectory: - p.jobReleaseTask?.containerSettings?.["workingDirectory"], - }, - resourceFiles: (p.jobReleaseTask?.["resourceFiles"] ?? []).map( - (p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - }) - ), - environmentSettings: ( - p.jobReleaseTask?.["environmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], - retentionTime: p.jobReleaseTask?.["retentionTime"], - userIdentity: !p.jobReleaseTask?.userIdentity - ? undefined - : { - username: p.jobReleaseTask?.userIdentity?.["username"], - autoUser: !p.jobReleaseTask?.userIdentity?.autoUser - ? undefined - : { - scope: - p.jobReleaseTask?.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.jobReleaseTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], - }, - }, - }, - commonEnvironmentSettings: (p["commonEnvironmentSettings"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), - poolInfo: { - poolId: p.poolInfo["poolId"], - autoPoolSpecification: !p.poolInfo.autoPoolSpecification + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + onAllTasksComplete: body["onAllTasksComplete"], + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); +} + +export async function _replaceJobDeserialize( + result: ReplaceJob200Response | ReplaceJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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, + body: BatchJob, + options: ReplaceJobOptions = { requestOptions: {} } +): Promise { + const result = await _replaceJobSend(context, jobId, body, options); + return _replaceJobDeserialize(result); +} + +export function _disableJobSend( + context: Client, + jobId: string, + body: BatchJobDisableOptions, + options: DisableJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs/{jobId}/disable", jobId) + .post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { disableTasks: body["disableTasks"] }, + }); +} + +export async function _disableJobDeserialize( + result: DisableJob202Response | DisableJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + jobId: string, + body: BatchJobDisableOptions, + options: DisableJobOptions = { requestOptions: {} } +): Promise { + const result = await _disableJobSend(context, jobId, body, options); + return _disableJobDeserialize(result); +} + +export function _enableJobSend( + context: Client, + jobId: string, + options: EnableJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs/{jobId}/enable", jobId) + .post({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _enableJobDeserialize( + result: EnableJob202Response | EnableJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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 enableJob( + context: Client, + jobId: string, + options: EnableJobOptions = { requestOptions: {} } +): Promise { + const result = await _enableJobSend(context, jobId, options); + return _enableJobDeserialize(result); +} + +export function _terminateJobSend( + context: Client, + jobId: string, + body: BatchJobTerminateOptions, + options: TerminateJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs/{jobId}/terminate", jobId) + .post({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { terminateReason: body["terminateReason"] }, + }); +} + +export async function _terminateJobDeserialize( + result: TerminateJob202Response | TerminateJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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, + body: BatchJobTerminateOptions, + options: TerminateJobOptions = { requestOptions: {} } +): Promise { + const result = await _terminateJobSend(context, jobId, body, options); + return _terminateJobDeserialize(result); +} + +export function _createJobSend( + context: Client, + body: BatchJobCreateOptions, + options: CreateJobOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + usesTaskDependencies: body["usesTaskDependencies"], + priority: body["priority"], + allowTaskPreemption: body["allowTaskPreemption"], + maxParallelTasks: body["maxParallelTasks"], + constraints: !body.constraints ? undefined : { - autoPoolIdPrefix: - p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], - poolLifetimeOption: - p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], - keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], - pool: !p.poolInfo.autoPoolSpecification?.pool + maxWallClockTime: body.constraints?.["maxWallClockTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobManagerTask + ? undefined + : { + id: body.jobManagerTask?.["id"], + displayName: body.jobManagerTask?.["displayName"], + commandLine: body.jobManagerTask?.["commandLine"], + containerSettings: !body.jobManagerTask?.containerSettings ? undefined - : { - displayName: - p.poolInfo.autoPoolSpecification?.pool?.["displayName"], - vmSize: p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !p.poolInfo.autoPoolSpecification - ?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.virtualMachineConfiguration - ? undefined - : { - imageReference: { - publisher: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - exactVersion: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "exactVersion" - ], - }, - nodeAgentSKUId: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.windowsConfiguration + : { + containerRunOptions: + body.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobManagerTask?.containerSettings?.["imageName"], + registry: !body.jobManagerTask?.containerSettings?.registry + ? undefined + : { + username: + body.jobManagerTask?.containerSettings?.registry?.[ + "username" + ], + password: + body.jobManagerTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.jobManagerTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobManagerTask + ?.containerSettings?.registry?.identityReference ? undefined : { - enableAutomaticUpdates: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" + resourceId: + body.jobManagerTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" ], }, - dataDisks: ( - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration + }, + workingDirectory: + body.jobManagerTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: (body.jobManagerTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + outputFiles: (body.jobManagerTask?.["outputFiles"] ?? []).map( + (p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference ? undefined : { - type: p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" ], - containerRegistries: ( - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.["targets"], - }, - nodePlacementConfiguration: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], }, - extensions: ( - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] ).map((p) => ({ name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], + value: p["value"], })), - osDisk: !p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !p.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - p.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, }, - taskSlotsPerNode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !p.poolInfo.autoPoolSpecification - ?.pool?.taskSchedulingPolicy + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + }) + ), + environmentSettings: ( + body.jobManagerTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + body.jobManagerTask?.constraints?.["maxWallClockTime"], + retentionTime: + body.jobManagerTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + body.jobManagerTask?.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: body.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: body.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !body.jobManagerTask?.userIdentity + ? undefined + : { + username: body.jobManagerTask?.userIdentity?.["username"], + autoUser: !body.jobManagerTask?.userIdentity?.autoUser ? undefined : { - nodeFillType: - p.poolInfo.autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + scope: + body.jobManagerTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + body.jobManagerTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, - resizeTimeout: - p.poolInfo.autoPoolSpecification?.pool?.["resizeTimeout"], - targetDedicatedNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" + }, + runExclusive: body.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobManagerTask?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobManagerTask + ?.authenticationTokenSettings + ? undefined + : { + access: + body.jobManagerTask?.authenticationTokenSettings?.[ + "access" ], - targetLowPriorityNodes: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" + }, + allowLowPriorityNode: + body.jobManagerTask?.["allowLowPriorityNode"], + }, + jobPreparationTask: !body.jobPreparationTask + ? undefined + : { + id: body.jobPreparationTask?.["id"], + commandLine: body.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobPreparationTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobPreparationTask?.containerSettings?.[ + "containerRunOptions" ], - enableAutoScale: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableAutoScale" + imageName: + body.jobPreparationTask?.containerSettings?.["imageName"], + registry: !body.jobPreparationTask?.containerSettings + ?.registry + ? undefined + : { + username: + body.jobPreparationTask?.containerSettings + ?.registry?.["username"], + password: + body.jobPreparationTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobPreparationTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body.jobPreparationTask + ?.containerSettings?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobPreparationTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobPreparationTask?.containerSettings?.[ + "workingDirectory" ], - autoScaleFormula: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleFormula" + }, + resourceFiles: ( + body.jobPreparationTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobPreparationTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobPreparationTask?.constraints + ? undefined + : { + maxWallClockTime: + body.jobPreparationTask?.constraints?.[ + "maxWallClockTime" ], - autoScaleEvaluationInterval: - p.poolInfo.autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" + retentionTime: + body.jobPreparationTask?.constraints?.["retentionTime"], + maxTaskRetryCount: + body.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" ], - enableInterNodeCommunication: - p.poolInfo.autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" + }, + waitForSuccess: body.jobPreparationTask?.["waitForSuccess"], + userIdentity: !body.jobPreparationTask?.userIdentity + ? undefined + : { + username: + body.jobPreparationTask?.userIdentity?.["username"], + autoUser: !body.jobPreparationTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobPreparationTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + body.jobPreparationTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + rerunOnNodeRebootAfterSuccess: + body.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], + }, + jobReleaseTask: !body.jobReleaseTask + ? undefined + : { + id: body.jobReleaseTask?.["id"], + commandLine: body.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobReleaseTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" ], - networkConfiguration: !p.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration + imageName: + body.jobReleaseTask?.containerSettings?.["imageName"], + registry: !body.jobReleaseTask?.containerSettings?.registry ? undefined : { - subnetId: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" + username: + body.jobReleaseTask?.containerSettings?.registry?.[ + "username" ], - endpointConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.endpointConfiguration + password: + body.jobReleaseTask?.containerSettings?.registry?.[ + "password" + ], + registryServer: + body.jobReleaseTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobReleaseTask + ?.containerSettings?.registry?.identityReference ? undefined : { - inboundNATPools: ( - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] + resourceId: + body.jobReleaseTask?.containerSettings + ?.registry?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobReleaseTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: (body.jobReleaseTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + environmentSettings: ( + body.jobReleaseTask?.["environmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: body.jobReleaseTask?.["maxWallClockTime"], + retentionTime: body.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobReleaseTask?.userIdentity + ? undefined + : { + username: body.jobReleaseTask?.userIdentity?.["username"], + autoUser: !body.jobReleaseTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobReleaseTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + body.jobReleaseTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + }, + commonEnvironmentSettings: ( + body["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.poolInfo["poolId"], + autoPoolSpecification: !body.poolInfo.autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], + poolLifetimeOption: + body.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: body.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !body.poolInfo.autoPoolSpecification?.pool + ? undefined + : { + displayName: + body.poolInfo.autoPoolSpecification?.pool?.[ + "displayName" + ], + vmSize: + body.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" + ], + sku: body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + }, + nodeAgentSKUId: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? + [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + }, + diskEncryptionConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.osDisk?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + body.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !body.poolInfo.autoPoolSpecification + ?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + body.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.poolInfo.autoPoolSpecification?.pool?.[ + "resizeTimeout" + ], + targetDedicatedNodes: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + body.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + body.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + body.poolInfo.autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration + ? undefined + : { + subnetId: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), })), - })), - }, - publicIPAddressConfiguration: !p.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - p.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask - ? undefined - : { - commandLine: - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.containerSettings?.registry - ? undefined - : { - username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - p.poolInfo.autoPoolSpecification?.pool + }, + publicIPAddressConfiguration: !body.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !body.poolInfo.autoPoolSpecification?.pool + ?.startTask + ? undefined + : { + commandLine: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["commandLine"], + containerSettings: !body.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry + ? undefined + : { + username: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body.poolInfo + .autoPoolSpecification?.pool ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !p.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - p.poolInfo.autoPoolSpecification - ?.pool?.startTask - ?.containerSettings?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["environmentSettings"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity ? undefined : { - resourceId: - p.identityReference?.["resourceId"], + username: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, }, - })), - environmentSettings: ( - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity + maxTaskRetryCount: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["maxTaskRetryCount"], + waitForSuccess: + body.poolInfo.autoPoolSpecification?.pool + ?.startTask?.["waitForSuccess"], + }, + certificateReferences: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "metadata" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration ? undefined : { - username: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.["username"], - autoUser: !p.poolInfo.autoPoolSpecification - ?.pool?.startTask?.userIdentity?.autoUser + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - scope: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "scope" - ], - elevationLevel: - p.poolInfo.autoPoolSpecification?.pool - ?.startTask?.userIdentity?.autoUser?.[ - "elevationLevel" - ], + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], }, }, - maxTaskRetryCount: - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: ( - p.poolInfo.autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - p.poolInfo.autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - p.poolInfo.autoPoolSpecification?.pool?.[ - "userAccounts" - ] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - p.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - p.poolInfo.autoPoolSpecification?.pool?.[ - "mountConfiguration" - ] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.["sasKey"], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - accountName: - p.azureFileShareConfiguration?.["accountName"], - azureFileUrl: - p.azureFileShareConfiguration?.["azureFileUrl"], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], + source: p.nfsMountConfiguration?.["source"], relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], + p.nfsMountConfiguration?.["relativeMountPath"], mountOptions: - p.azureFileShareConfiguration?.["mountOptions"], + p.nfsMountConfiguration?.["mountOptions"], }, - })), - targetNodeCommunicationMode: - p.poolInfo.autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" - ], - }, - }, - }, - onAllTasksComplete: p["onAllTasksComplete"], - onTaskFailure: p["onTaskFailure"], - networkConfiguration: !p.networkConfiguration - ? undefined - : { subnetId: p.networkConfiguration?.["subnetId"] }, - metadata: (p["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: p.executionInfo?.schedulingError?.["message"], - details: ( - p.executionInfo?.schedulingError?.["details"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.poolInfo.autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + onAllTasksComplete: body["onAllTasksComplete"], + onTaskFailure: body["onTaskFailure"], + networkConfiguration: !body.networkConfiguration + ? undefined + : { subnetId: body.networkConfiguration?.["subnetId"] }, + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); } -/** Lists all of the Jobs in the specified Account. */ -export function listJobs( +export async function _createJobDeserialize( + result: CreateJob201Response | CreateJobDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** + * 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( context: Client, - options: ListJobsOptions = { requestOptions: {} } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator(context, _listJobsSend, _listJobsDeserialize, [ - context, - options, - ]); + body: BatchJobCreateOptions, + options: CreateJobOptions = { requestOptions: {} } +): Promise { + const result = await _createJobSend(context, body, options); + return _createJobDeserialize(result); } -export function _listJobsFromScheduleSend( +export function _listJobsSend( context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptions = { requestOptions: {} } -): StreamableMethod< - ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse -> { - return context.path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + options: ListJobsOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path("/jobs") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } -export async function _listJobsFromScheduleDeserialize( - result: ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse +export async function _listJobsDeserialize( + result: ListJobs200Response | ListJobsDefaultResponse ): Promise { if (isUnexpected(result)) { throw result.body; @@ -7832,849 +7017,180 @@ export async function _listJobsFromScheduleDeserialize( : { subnetId: p.networkConfiguration?.["subnetId"] }, metadata: (p["metadata"] ?? []).map((p) => ({ name: p["name"], - value: p["value"], - })), - executionInfo: !p.executionInfo - ? undefined - : { - startTime: new Date(p.executionInfo?.["startTime"]), - endTime: - p.executionInfo?.["endTime"] !== undefined - ? new Date(p.executionInfo?.["endTime"]) - : undefined, - poolId: p.executionInfo?.["poolId"], - schedulingError: !p.executionInfo?.schedulingError - ? undefined - : { - category: p.executionInfo?.schedulingError?.["category"], - code: p.executionInfo?.schedulingError?.["code"], - message: p.executionInfo?.schedulingError?.["message"], - details: ( - p.executionInfo?.schedulingError?.["details"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - terminateReason: p.executionInfo?.["terminateReason"], - }, - stats: !p.stats - ? undefined - : { - url: p.stats?.["url"], - startTime: new Date(p.stats?.["startTime"]), - lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), - userCPUTime: p.stats?.["userCPUTime"], - kernelCPUTime: p.stats?.["kernelCPUTime"], - wallClockTime: p.stats?.["wallClockTime"], - readIOps: p.stats?.["readIOps"], - writeIOps: p.stats?.["writeIOps"], - readIOGiB: p.stats?.["readIOGiB"], - writeIOGiB: p.stats?.["writeIOGiB"], - numSucceededTasks: p.stats?.["numSucceededTasks"], - numFailedTasks: p.stats?.["numFailedTasks"], - numTaskRetries: p.stats?.["numTaskRetries"], - waitTime: p.stats?.["waitTime"], - }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists the Jobs that have been created under the specified Job Schedule. */ -export function listJobsFromSchedule( - context: Client, - jobScheduleId: string, - options: ListJobsFromScheduleOptions = { requestOptions: {} } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - _listJobsFromScheduleSend, - _listJobsFromScheduleDeserialize, - [context, jobScheduleId, options] - ); -} - -export function _listJobPreparationAndReleaseTaskStatusSend( - context: Client, - jobId: string, - options: ListJobPreparationAndReleaseTaskStatusOptions = { - requestOptions: {}, - } -): StreamableMethod< - | ListJobPreparationAndReleaseTaskStatus200Response - | ListJobPreparationAndReleaseTaskStatusDefaultResponse -> { - return context - .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) - .get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - }, - }); -} - -export async function _listJobPreparationAndReleaseTaskStatusDeserialize( - result: - | ListJobPreparationAndReleaseTaskStatus200Response - | ListJobPreparationAndReleaseTaskStatusDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - value: (result.body["value"] ?? []).map((p) => ({ - poolId: p["poolId"], - nodeId: p["nodeId"], - nodeUrl: p["nodeUrl"], - jobPreparationTaskExecutionInfo: !p.jobPreparationTaskExecutionInfo - ? undefined - : { - startTime: new Date( - p.jobPreparationTaskExecutionInfo?.["startTime"] - ), - endTime: - p.jobPreparationTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobPreparationTaskExecutionInfo?.["endTime"]) - : undefined, - state: p.jobPreparationTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobPreparationTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobPreparationTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobPreparationTaskExecutionInfo?.containerInfo - ? undefined - : { - containerId: - p.jobPreparationTaskExecutionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.jobPreparationTaskExecutionInfo?.containerInfo?.["state"], - error: - p.jobPreparationTaskExecutionInfo?.containerInfo?.["error"], - }, - failureInfo: !p.jobPreparationTaskExecutionInfo?.failureInfo - ? undefined - : { - category: - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "category" - ], - code: p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "code" - ], - message: - p.jobPreparationTaskExecutionInfo?.failureInfo?.["message"], - details: ( - p.jobPreparationTaskExecutionInfo?.failureInfo?.[ - "details" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - retryCount: p.jobPreparationTaskExecutionInfo?.["retryCount"], - lastRetryTime: - p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== undefined - ? new Date(p.jobPreparationTaskExecutionInfo?.["lastRetryTime"]) - : undefined, - result: p.jobPreparationTaskExecutionInfo?.["result"], - }, - jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo + value: p["value"], + })), + executionInfo: !p.executionInfo ? undefined : { - startTime: new Date(p.jobReleaseTaskExecutionInfo?.["startTime"]), + startTime: new Date(p.executionInfo?.["startTime"]), endTime: - p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined - ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) + p.executionInfo?.["endTime"] !== undefined + ? new Date(p.executionInfo?.["endTime"]) : undefined, - state: p.jobReleaseTaskExecutionInfo?.["state"], - taskRootDirectory: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], - taskRootDirectoryUrl: - p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], - exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], - containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo - ? undefined - : { - containerId: - p.jobReleaseTaskExecutionInfo?.containerInfo?.[ - "containerId" - ], - state: - p.jobReleaseTaskExecutionInfo?.containerInfo?.["state"], - error: - p.jobReleaseTaskExecutionInfo?.containerInfo?.["error"], - }, - failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo + poolId: p.executionInfo?.["poolId"], + schedulingError: !p.executionInfo?.schedulingError ? undefined : { - category: - p.jobReleaseTaskExecutionInfo?.failureInfo?.["category"], - code: p.jobReleaseTaskExecutionInfo?.failureInfo?.["code"], - message: - p.jobReleaseTaskExecutionInfo?.failureInfo?.["message"], + category: p.executionInfo?.schedulingError?.["category"], + code: p.executionInfo?.schedulingError?.["code"], + message: p.executionInfo?.schedulingError?.["message"], details: ( - p.jobReleaseTaskExecutionInfo?.failureInfo?.["details"] ?? - [] + p.executionInfo?.schedulingError?.["details"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), }, - result: p.jobReleaseTaskExecutionInfo?.["result"], + terminateReason: p.executionInfo?.["terminateReason"], }, - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** - * 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: ListJobPreparationAndReleaseTaskStatusOptions = { - requestOptions: {}, - } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - _listJobPreparationAndReleaseTaskStatusSend, - _listJobPreparationAndReleaseTaskStatusDeserialize, - [context, jobId, options] - ); -} - -export function _getJobTaskCountsSend( - context: Client, - jobId: string, - options: GetJobTaskCountsOptions = { requestOptions: {} } -): StreamableMethod< - GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse -> { - return context.path("/jobs/{jobId}/taskcounts", jobId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _getJobTaskCountsDeserialize( - result: GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - taskCounts: { - active: result.body.taskCounts["active"], - running: result.body.taskCounts["running"], - completed: result.body.taskCounts["completed"], - succeeded: result.body.taskCounts["succeeded"], - failed: result.body.taskCounts["failed"], - }, - taskSlotCounts: { - active: result.body.taskSlotCounts["active"], - running: result.body.taskSlotCounts["running"], - completed: result.body.taskSlotCounts["completed"], - succeeded: result.body.taskSlotCounts["succeeded"], - failed: result.body.taskSlotCounts["failed"], - }, - }; -} - -/** - * 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: GetJobTaskCountsOptions = { requestOptions: {} } -): Promise { - const result = await _getJobTaskCountsSend(context, jobId, options); - return _getJobTaskCountsDeserialize(result); -} - -export function _createCertificateSend( - context: Client, - body: BatchCertificate, - options: CreateCertificateOptions = { requestOptions: {} } -): StreamableMethod< - CreateCertificate201Response | CreateCertificateDefaultResponse -> { - return context.path("/certificates").post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - thumbprint: body["thumbprint"], - thumbprintAlgorithm: body["thumbprintAlgorithm"], - data: uint8ArrayToString(body["data"], "base64"), - certificateFormat: body["certificateFormat"], - password: body["password"], - }, - }); -} - -export async function _createCertificateDeserialize( - result: CreateCertificate201Response | CreateCertificateDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** Creates a Certificate to the specified Account. */ -export async function createCertificate( - context: Client, - body: BatchCertificate, - options: CreateCertificateOptions = { requestOptions: {} } -): Promise { - const result = await _createCertificateSend(context, body, options); - return _createCertificateDeserialize(result); -} - -export function _listCertificatesSend( - context: Client, - options: ListCertificatesOptions = { requestOptions: {} } -): StreamableMethod< - ListCertificates200Response | ListCertificatesDefaultResponse -> { - return context.path("/certificates").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - }, - }); -} - -export async function _listCertificatesDeserialize( - result: ListCertificates200Response | ListCertificatesDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - value: (result.body["value"] ?? []).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - url: p["url"], - state: p["state"], - stateTransitionTime: - p["stateTransitionTime"] !== undefined - ? new Date(p["stateTransitionTime"]) - : undefined, - previousState: p["previousState"], - previousStateTransitionTime: - p["previousStateTransitionTime"] !== undefined - ? new Date(p["previousStateTransitionTime"]) - : undefined, - publicData: - typeof p["publicData"] === "string" - ? stringToUint8Array(p["publicData"], "base64") - : p["publicData"], - deleteCertificateError: !p.deleteCertificateError + stats: !p.stats ? undefined : { - code: p.deleteCertificateError?.["code"], - message: p.deleteCertificateError?.["message"], - values: (p.deleteCertificateError?.["values"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - data: - typeof p["data"] === "string" - ? stringToUint8Array(p["data"], "base64") - : p["data"], - certificateFormat: p["certificateFormat"], - password: p["password"], - })), - "odata.nextLink": result.body["odata.nextLink"], - }; -} - -/** Lists all of the Certificates that have been added to the specified Account. */ -export function listCertificates( - context: Client, - options: ListCertificatesOptions = { requestOptions: {} } -): PagedAsyncIterableIterator { - return buildPagedAsyncIterator( - context, - _listCertificatesSend, - _listCertificatesDeserialize, - [context, options] - ); -} - -export function _cancelCertificateDeletionSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptions = { requestOptions: {} } -): StreamableMethod< - | CancelCertificateDeletion204Response - | CancelCertificateDeletionDefaultResponse -> { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", - thumbprintAlgorithm, - thumbprint - ) - .post({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _cancelCertificateDeletionDeserialize( - result: - | CancelCertificateDeletion204Response - | CancelCertificateDeletionDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; + url: p.stats?.["url"], + startTime: new Date(p.stats?.["startTime"]), + lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), + userCPUTime: p.stats?.["userCPUTime"], + kernelCPUTime: p.stats?.["kernelCPUTime"], + wallClockTime: p.stats?.["wallClockTime"], + readIOps: p.stats?.["readIOps"], + writeIOps: p.stats?.["writeIOps"], + readIOGiB: p.stats?.["readIOGiB"], + writeIOGiB: p.stats?.["writeIOGiB"], + numSucceededTasks: p.stats?.["numSucceededTasks"], + numFailedTasks: p.stats?.["numFailedTasks"], + numTaskRetries: p.stats?.["numTaskRetries"], + waitTime: p.stats?.["waitTime"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; } -/** - * 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( +/** Lists all of the Jobs in the specified Account. */ +export function listJobs( context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: CancelCertificateDeletionOptions = { requestOptions: {} } -): Promise { - const result = await _cancelCertificateDeletionSend( + options: ListJobsOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator(context, _listJobsSend, _listJobsDeserialize, [ context, - thumbprintAlgorithm, - thumbprint, - options - ); - return _cancelCertificateDeletionDeserialize(result); + options, + ]); } -export function _deleteCertificateSend( +export function _listJobsFromScheduleSend( context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: DeleteCertificateOptions = { requestOptions: {} } + jobScheduleId: string, + options: ListJobsFromScheduleOptions = { requestOptions: {} } ): StreamableMethod< - DeleteCertificate202Response | DeleteCertificateDefaultResponse + ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse > { return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint - ) - .delete({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _deleteCertificateDeserialize( - result: DeleteCertificate202Response | DeleteCertificateDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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: DeleteCertificateOptions = { requestOptions: {} } -): Promise { - const result = await _deleteCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options - ); - return _deleteCertificateDeserialize(result); -} - -export function _getCertificateSend( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path( - "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", - thumbprintAlgorithm, - thumbprint - ) + .path("/jobschedules/{jobScheduleId}/jobs", jobScheduleId) .get({ ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, }); } - -export async function _getCertificateDeserialize( - result: GetCertificate200Response | GetCertificateDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - thumbprint: result.body["thumbprint"], - thumbprintAlgorithm: result.body["thumbprintAlgorithm"], - url: result.body["url"], - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - publicData: - typeof result.body["publicData"] === "string" - ? stringToUint8Array(result.body["publicData"], "base64") - : result.body["publicData"], - deleteCertificateError: !result.body.deleteCertificateError - ? undefined - : { - code: result.body.deleteCertificateError?.["code"], - message: result.body.deleteCertificateError?.["message"], - values: (result.body.deleteCertificateError?.["values"] ?? []).map( - (p) => ({ name: p["name"], value: p["value"] }) - ), - }, - data: - typeof result.body["data"] === "string" - ? stringToUint8Array(result.body["data"], "base64") - : result.body["data"], - certificateFormat: result.body["certificateFormat"], - password: result.body["password"], - }; -} - -/** Gets information about the specified Certificate. */ -export async function getCertificate( - context: Client, - thumbprintAlgorithm: string, - thumbprint: string, - options: GetCertificateOptions = { requestOptions: {} } -): Promise { - const result = await _getCertificateSend( - context, - thumbprintAlgorithm, - thumbprint, - options - ); - return _getCertificateDeserialize(result); -} - -export function _jobScheduleExistsSend( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptions = { requestOptions: {} } -): StreamableMethod< - | JobScheduleExists200Response - | JobScheduleExists404Response - | JobScheduleExistsDefaultResponse -> { - return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).head({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _jobScheduleExistsDeserialize( - result: - | JobScheduleExists200Response - | JobScheduleExists404Response - | JobScheduleExistsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return; -} - -/** Checks the specified Job Schedule exists. */ -export async function jobScheduleExists( - context: Client, - jobScheduleId: string, - options: JobScheduleExistsOptions = { requestOptions: {} } -): Promise { - const result = await _jobScheduleExistsSend(context, jobScheduleId, options); - return _jobScheduleExistsDeserialize(result); -} - -export function _deleteJobScheduleSend( - context: Client, - jobScheduleId: string, - options: DeleteJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse -> { - return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); -} - -export async function _deleteJobScheduleDeserialize( - result: DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( - context: Client, - jobScheduleId: string, - options: DeleteJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _deleteJobScheduleSend(context, jobScheduleId, options); - return _deleteJobScheduleDeserialize(result); -} - -export function _getJobScheduleSend( - context: Client, - jobScheduleId: string, - options: GetJobScheduleOptions = { 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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); -} - -export async function _getJobScheduleDeserialize( - result: GetJobSchedule200Response | GetJobScheduleDefaultResponse -): Promise { + +export async function _listJobsFromScheduleDeserialize( + result: ListJobsFromSchedule200Response | ListJobsFromScheduleDefaultResponse +): Promise { if (isUnexpected(result)) { throw result.body; } return { - id: result.body["id"], - displayName: result.body["displayName"], - url: result.body["url"], - eTag: result.body["eTag"], - lastModified: - result.body["lastModified"] !== undefined - ? new Date(result.body["lastModified"]) - : undefined, - creationTime: - result.body["creationTime"] !== undefined - ? new Date(result.body["creationTime"]) - : undefined, - state: result.body["state"], - stateTransitionTime: - result.body["stateTransitionTime"] !== undefined - ? new Date(result.body["stateTransitionTime"]) - : undefined, - previousState: result.body["previousState"], - previousStateTransitionTime: - result.body["previousStateTransitionTime"] !== undefined - ? new Date(result.body["previousStateTransitionTime"]) - : undefined, - schedule: { - doNotRunUntil: - result.body.schedule["doNotRunUntil"] !== undefined - ? new Date(result.body.schedule["doNotRunUntil"]) + value: (result.body["value"] ?? []).map((p) => ({ + id: p["id"], + displayName: p["displayName"], + usesTaskDependencies: p["usesTaskDependencies"], + url: p["url"], + eTag: p["eTag"], + lastModified: + p["lastModified"] !== undefined + ? new Date(p["lastModified"]) : undefined, - doNotRunAfter: - result.body.schedule["doNotRunAfter"] !== undefined - ? new Date(result.body.schedule["doNotRunAfter"]) + creationTime: + p["creationTime"] !== undefined + ? new Date(p["creationTime"]) : undefined, - startWindow: result.body.schedule["startWindow"], - recurrenceInterval: result.body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: result.body.jobSpecification["priority"], - allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], - displayName: result.body.jobSpecification["displayName"], - usesTaskDependencies: - result.body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], - onTaskFailure: result.body.jobSpecification["onTaskFailure"], - networkConfiguration: !result.body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - result.body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !result.body.jobSpecification.constraints + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + priority: p["priority"], + allowTaskPreemption: p["allowTaskPreemption"], + maxParallelTasks: p["maxParallelTasks"], + constraints: !p.constraints ? undefined : { - maxWallClockTime: - result.body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - result.body.jobSpecification.constraints?.["maxTaskRetryCount"], + maxWallClockTime: p.constraints?.["maxWallClockTime"], + maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], }, - jobManagerTask: !result.body.jobSpecification.jobManagerTask + jobManagerTask: !p.jobManagerTask ? undefined : { - id: result.body.jobSpecification.jobManagerTask?.["id"], - displayName: - result.body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - result.body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobManagerTask - ?.containerSettings + id: p.jobManagerTask?.["id"], + displayName: p.jobManagerTask?.["displayName"], + commandLine: p.jobManagerTask?.["commandLine"], + containerSettings: !p.jobManagerTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry + p.jobManagerTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: p.jobManagerTask?.containerSettings?.["imageName"], + registry: !p.jobManagerTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], + p.jobManagerTask?.containerSettings?.registry?.[ + "username" + ], password: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], + p.jobManagerTask?.containerSettings?.registry?.[ + "password" + ], registryServer: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference + p.jobManagerTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobManagerTask?.containerSettings + ?.registry?.identityReference ? undefined : { resourceId: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.registry + p.jobManagerTask?.containerSettings?.registry ?.identityReference?.["resourceId"], }, }, workingDirectory: - result.body.jobSpecification.jobManagerTask - ?.containerSettings?.["workingDirectory"], + p.jobManagerTask?.containerSettings?.["workingDirectory"], }, - resourceFiles: ( - result.body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - result.body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ + resourceFiles: (p.jobManagerTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), + outputFiles: (p.jobManagerTask?.["outputFiles"] ?? []).map((p) => ({ filePattern: p["filePattern"], destination: { container: !p.destination.container @@ -8701,377 +7217,297 @@ export async function _getJobScheduleDeserialize( }, })), environmentSettings: ( - result.body.jobSpecification.jobManagerTask?.[ - "environmentSettings" - ] ?? [] + p.jobManagerTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobSpecification.jobManagerTask - ?.constraints + constraints: !p.jobManagerTask?.constraints ? undefined : { maxWallClockTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], + p.jobManagerTask?.constraints?.["maxWallClockTime"], retentionTime: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], + p.jobManagerTask?.constraints?.["retentionTime"], maxTaskRetryCount: - result.body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], + p.jobManagerTask?.constraints?.["maxTaskRetryCount"], }, - requiredSlots: - result.body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - result.body.jobSpecification.jobManagerTask?.[ - "killJobOnCompletion" - ], - userIdentity: !result.body.jobSpecification.jobManagerTask - ?.userIdentity + requiredSlots: p.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: p.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !p.jobManagerTask?.userIdentity ? undefined : { - username: - result.body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser + username: p.jobManagerTask?.userIdentity?.["username"], + autoUser: !p.jobManagerTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], + p.jobManagerTask?.userIdentity?.autoUser?.["scope"], elevationLevel: - result.body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser?.["elevationLevel"], + p.jobManagerTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, }, - runExclusive: - result.body.jobSpecification.jobManagerTask?.["runExclusive"], + runExclusive: p.jobManagerTask?.["runExclusive"], applicationPackageReferences: ( - result.body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] + p.jobManagerTask?.["applicationPackageReferences"] ?? [] ).map((p) => ({ applicationId: p["applicationId"], version: p["version"], })), - authenticationTokenSettings: !result.body.jobSpecification - .jobManagerTask?.authenticationTokenSettings + authenticationTokenSettings: !p.jobManagerTask + ?.authenticationTokenSettings ? undefined : { access: - result.body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], + p.jobManagerTask?.authenticationTokenSettings?.["access"], }, - allowLowPriorityNode: - result.body.jobSpecification.jobManagerTask?.[ - "allowLowPriorityNode" - ], + allowLowPriorityNode: p.jobManagerTask?.["allowLowPriorityNode"], }, - jobPreparationTask: !result.body.jobSpecification.jobPreparationTask + jobPreparationTask: !p.jobPreparationTask ? undefined : { - id: result.body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - result.body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings + id: p.jobPreparationTask?.["id"], + commandLine: p.jobPreparationTask?.["commandLine"], + containerSettings: !p.jobPreparationTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], + p.jobPreparationTask?.containerSettings?.[ + "containerRunOptions" + ], imageName: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry + p.jobPreparationTask?.containerSettings?.["imageName"], + registry: !p.jobPreparationTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], + p.jobPreparationTask?.containerSettings?.registry?.[ + "username" + ], password: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], + p.jobPreparationTask?.containerSettings?.registry?.[ + "password" + ], registryServer: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference + p.jobPreparationTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobPreparationTask + ?.containerSettings?.registry?.identityReference ? undefined : { resourceId: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + p.jobPreparationTask?.containerSettings + ?.registry?.identityReference?.["resourceId"], }, }, workingDirectory: - result.body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], + p.jobPreparationTask?.containerSettings?.[ + "workingDirectory" + ], }, - resourceFiles: ( - result.body.jobSpecification.jobPreparationTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), + resourceFiles: (p.jobPreparationTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), environmentSettings: ( - result.body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] + p.jobPreparationTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !result.body.jobSpecification.jobPreparationTask - ?.constraints + constraints: !p.jobPreparationTask?.constraints ? undefined : { maxWallClockTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxWallClockTime"], + p.jobPreparationTask?.constraints?.["maxWallClockTime"], retentionTime: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["retentionTime"], + p.jobPreparationTask?.constraints?.["retentionTime"], maxTaskRetryCount: - result.body.jobSpecification.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], + p.jobPreparationTask?.constraints?.["maxTaskRetryCount"], }, - waitForSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity + waitForSuccess: p.jobPreparationTask?.["waitForSuccess"], + userIdentity: !p.jobPreparationTask?.userIdentity ? undefined : { - username: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser + username: p.jobPreparationTask?.userIdentity?.["username"], + autoUser: !p.jobPreparationTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "scope" + ], elevationLevel: - result.body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], + p.jobPreparationTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, }, rerunOnNodeRebootAfterSuccess: - result.body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], + p.jobPreparationTask?.["rerunOnNodeRebootAfterSuccess"], }, - jobReleaseTask: !result.body.jobSpecification.jobReleaseTask + jobReleaseTask: !p.jobReleaseTask ? undefined : { - id: result.body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - result.body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings + id: p.jobReleaseTask?.["id"], + commandLine: p.jobReleaseTask?.["commandLine"], + containerSettings: !p.jobReleaseTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + p.jobReleaseTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: p.jobReleaseTask?.containerSettings?.["imageName"], + registry: !p.jobReleaseTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], + p.jobReleaseTask?.containerSettings?.registry?.[ + "username" + ], password: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], + p.jobReleaseTask?.containerSettings?.registry?.[ + "password" + ], registryServer: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !result.body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference + p.jobReleaseTask?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !p.jobReleaseTask?.containerSettings + ?.registry?.identityReference ? undefined : { resourceId: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + p.jobReleaseTask?.containerSettings?.registry ?.identityReference?.["resourceId"], }, }, workingDirectory: - result.body.jobSpecification.jobReleaseTask - ?.containerSettings?.["workingDirectory"], + p.jobReleaseTask?.containerSettings?.["workingDirectory"], }, - resourceFiles: ( - result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), + resourceFiles: (p.jobReleaseTask?.["resourceFiles"] ?? []).map( + (p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + }) + ), environmentSettings: ( - result.body.jobSpecification.jobReleaseTask?.[ - "environmentSettings" - ] ?? [] + p.jobReleaseTask?.["environmentSettings"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - result.body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity + maxWallClockTime: p.jobReleaseTask?.["maxWallClockTime"], + retentionTime: p.jobReleaseTask?.["retentionTime"], + userIdentity: !p.jobReleaseTask?.userIdentity ? undefined : { - username: - result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser + username: p.jobReleaseTask?.userIdentity?.["username"], + autoUser: !p.jobReleaseTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], + p.jobReleaseTask?.userIdentity?.autoUser?.["scope"], elevationLevel: - result.body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser?.["elevationLevel"], + p.jobReleaseTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, }, }, - commonEnvironmentSettings: ( - result.body.jobSpecification["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), + commonEnvironmentSettings: (p["commonEnvironmentSettings"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), poolInfo: { - poolId: result.body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !result.body.jobSpecification.poolInfo - .autoPoolSpecification + poolId: p.poolInfo["poolId"], + autoPoolSpecification: !p.poolInfo.autoPoolSpecification ? undefined : { autoPoolIdPrefix: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], + p.poolInfo.autoPoolSpecification?.["autoPoolIdPrefix"], poolLifetimeOption: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool + p.poolInfo.autoPoolSpecification?.["poolLifetimeOption"], + keepAlive: p.poolInfo.autoPoolSpecification?.["keepAlive"], + pool: !p.poolInfo.autoPoolSpecification?.pool ? undefined : { displayName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration + p.poolInfo.autoPoolSpecification?.pool?.["displayName"], + vmSize: p.poolInfo.autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !p.poolInfo.autoPoolSpecification + ?.pool?.cloudServiceConfiguration ? undefined : { osFamily: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.cloudServiceConfiguration?.["osFamily"], osVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.cloudServiceConfiguration?.["osVersion"], }, - virtualMachineConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration + virtualMachineConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.virtualMachineConfiguration ? undefined : { imageReference: { - publisher: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + publisher: + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "publisher" ], offer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "offer" ], - sku: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + sku: p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "sku" ], version: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "version" ], virtualMachineImageId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "virtualMachineImageId" ], exactVersion: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ "exactVersion" ], }, nodeAgentSKUId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["nodeAgentSKUId"], - windowsConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool + windowsConfiguration: !p.poolInfo + .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.windowsConfiguration ? undefined : { enableAutomaticUpdates: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.windowsConfiguration?.[ "enableAutomaticUpdates" ], }, dataDisks: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["dataDisks"] ?? [] ).map((p) => ({ lun: p["lun"], @@ -9080,29 +7516,25 @@ export async function _getJobScheduleDeserialize( storageAccountType: p["storageAccountType"], })), licenseType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool + containerConfiguration: !p.poolInfo + .autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration ? undefined : { - type: result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + type: p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.["type"], containerImageNames: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.[ "containerImageNames" ], containerRegistries: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.containerConfiguration?.[ "containerRegistries" @@ -9119,33 +7551,30 @@ export async function _getJobScheduleDeserialize( }, })), }, - diskEncryptionConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration + diskEncryptionConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration ?.diskEncryptionConfiguration ? undefined : { targets: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.diskEncryptionConfiguration?.["targets"], }, - nodePlacementConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.virtualMachineConfiguration + nodePlacementConfiguration: !p.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration ?.nodePlacementConfiguration ? undefined : { policy: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration ?.nodePlacementConfiguration?.["policy"], }, extensions: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.["extensions"] ?? [] ).map((p) => ({ @@ -9161,21 +7590,18 @@ export async function _getJobScheduleDeserialize( provisionAfterExtensions: p["provisionAfterExtensions"], })), - osDisk: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + osDisk: !p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ? undefined : { - ephemeralOSDiskSettings: !result.body - .jobSpecification.poolInfo + ephemeralOSDiskSettings: !p.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ?.ephemeralOSDiskSettings ? undefined : { placement: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration?.osDisk ?.ephemeralOSDiskSettings?.[ "placement" @@ -9184,66 +7610,62 @@ export async function _getJobScheduleDeserialize( }, }, taskSlotsPerNode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy + p.poolInfo.autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" + ], + taskSchedulingPolicy: !p.poolInfo.autoPoolSpecification + ?.pool?.taskSchedulingPolicy ? undefined : { nodeFillType: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.taskSchedulingPolicy?.["nodeFillType"], }, resizeTimeout: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], + p.poolInfo.autoPoolSpecification?.pool?.["resizeTimeout"], targetDedicatedNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["targetDedicatedNodes"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], targetLowPriorityNodes: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "targetLowPriorityNodes" ], enableAutoScale: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["enableAutoScale"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], autoScaleFormula: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["autoScaleFormula"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], autoScaleEvaluationInterval: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "autoScaleEvaluationInterval" ], enableInterNodeCommunication: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "enableInterNodeCommunication" ], - networkConfiguration: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration + networkConfiguration: !p.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration ? undefined : { subnetId: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.["subnetId"], dynamicVNetAssignmentScope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.[ "dynamicVNetAssignmentScope" ], - endpointConfiguration: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration + endpointConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ?.endpointConfiguration ? undefined : { inboundNATPools: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.endpointConfiguration?.[ "inboundNATPools" @@ -9267,88 +7689,76 @@ export async function _getJobScheduleDeserialize( })), })), }, - publicIPAddressConfiguration: !result.body - .jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.networkConfiguration + publicIPAddressConfiguration: !p.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration ?.publicIPAddressConfiguration ? undefined : { provision: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.publicIPAddressConfiguration?.[ "provision" ], ipAddressIds: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration ?.publicIPAddressConfiguration?.[ "ipAddressIds" ], }, enableAcceleratedNetworking: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.networkConfiguration?.[ "enableAcceleratedNetworking" ], }, - startTask: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask + startTask: !p.poolInfo.autoPoolSpecification?.pool + ?.startTask ? undefined : { commandLine: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "commandLine" ], - containerSettings: !result.body.jobSpecification - .poolInfo.autoPoolSpecification?.pool?.startTask - ?.containerSettings + containerSettings: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings ? undefined : { containerRunOptions: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ "containerRunOptions" ], imageName: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.containerSettings?.registry ? undefined : { username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings ?.registry?.["username"], password: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings ?.registry?.["password"], registryServer: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.containerSettings ?.registry?.["registryServer"], - identityReference: !result.body - .jobSpecification.poolInfo + identityReference: !p.poolInfo .autoPoolSpecification?.pool?.startTask ?.containerSettings?.registry ?.identityReference ? undefined : { resourceId: - result.body.jobSpecification - .poolInfo.autoPoolSpecification + p.poolInfo.autoPoolSpecification ?.pool?.startTask ?.containerSettings?.registry ?.identityReference?.[ @@ -9357,13 +7767,13 @@ export async function _getJobScheduleDeserialize( }, }, workingDirectory: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["workingDirectory"], + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], }, resourceFiles: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "resourceFiles" ] ?? [] ).map((p) => ({ @@ -9382,56 +7792,47 @@ export async function _getJobScheduleDeserialize( }, })), environmentSettings: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "environmentSettings" ] ?? [] ).map((p) => ({ name: p["name"], value: p["value"], })), - userIdentity: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity + userIdentity: !p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity ? undefined : { username: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser + p.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.["username"], + autoUser: !p.poolInfo.autoPoolSpecification + ?.pool?.startTask?.userIdentity?.autoUser ? undefined : { scope: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.userIdentity?.autoUser?.[ "scope" ], elevationLevel: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool + p.poolInfo.autoPoolSpecification?.pool ?.startTask?.userIdentity?.autoUser?.[ "elevationLevel" ], }, }, maxTaskRetryCount: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "maxTaskRetryCount" ], waitForSuccess: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ + p.poolInfo.autoPoolSpecification?.pool?.startTask?.[ "waitForSuccess" ], }, certificateReferences: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "certificateReferences" ] ?? [] ).map((p) => ({ @@ -9442,8 +7843,7 @@ export async function _getJobScheduleDeserialize( visibility: p["visibility"], })), applicationPackageReferences: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "applicationPackageReferences" ] ?? [] ).map((p) => ({ @@ -9451,11 +7851,13 @@ export async function _getJobScheduleDeserialize( version: p["version"], })), applicationLicenses: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["applicationLicenses"], + p.poolInfo.autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], userAccounts: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] ?? [] + p.poolInfo.autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] ).map((p) => ({ name: p["name"], password: p["password"], @@ -9476,13 +7878,12 @@ export async function _getJobScheduleDeserialize( }, })), metadata: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["metadata"] ?? [] + p.poolInfo.autoPoolSpecification?.pool?.["metadata"] ?? [] ).map((p) => ({ name: p["name"], value: p["value"] })), mountConfiguration: ( - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.["mountConfiguration"] ?? - [] + p.poolInfo.autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] ).map((p) => ({ azureBlobFileSystemConfiguration: !p.azureBlobFileSystemConfiguration @@ -9559,1738 +7960,2704 @@ export async function _getJobScheduleDeserialize( }, })), targetNodeCommunicationMode: - result.body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.[ + p.poolInfo.autoPoolSpecification?.pool?.[ "targetNodeCommunicationMode" ], }, }, }, - metadata: (result.body.jobSpecification["metadata"] ?? []).map((p) => ({ + onAllTasksComplete: p["onAllTasksComplete"], + onTaskFailure: p["onTaskFailure"], + networkConfiguration: !p.networkConfiguration + ? undefined + : { subnetId: p.networkConfiguration?.["subnetId"] }, + metadata: (p["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), + executionInfo: !p.executionInfo + ? undefined + : { + startTime: new Date(p.executionInfo?.["startTime"]), + endTime: + p.executionInfo?.["endTime"] !== undefined + ? new Date(p.executionInfo?.["endTime"]) + : undefined, + poolId: p.executionInfo?.["poolId"], + schedulingError: !p.executionInfo?.schedulingError + ? undefined + : { + category: p.executionInfo?.schedulingError?.["category"], + code: p.executionInfo?.schedulingError?.["code"], + message: p.executionInfo?.schedulingError?.["message"], + details: ( + p.executionInfo?.schedulingError?.["details"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + terminateReason: p.executionInfo?.["terminateReason"], + }, + stats: !p.stats + ? undefined + : { + url: p.stats?.["url"], + startTime: new Date(p.stats?.["startTime"]), + lastUpdateTime: new Date(p.stats?.["lastUpdateTime"]), + userCPUTime: p.stats?.["userCPUTime"], + kernelCPUTime: p.stats?.["kernelCPUTime"], + wallClockTime: p.stats?.["wallClockTime"], + readIOps: p.stats?.["readIOps"], + writeIOps: p.stats?.["writeIOps"], + readIOGiB: p.stats?.["readIOGiB"], + writeIOGiB: p.stats?.["writeIOGiB"], + numSucceededTasks: p.stats?.["numSucceededTasks"], + numFailedTasks: p.stats?.["numFailedTasks"], + numTaskRetries: p.stats?.["numTaskRetries"], + waitTime: p.stats?.["waitTime"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists the Jobs that have been created under the specified Job Schedule. */ +export function listJobsFromSchedule( + context: Client, + jobScheduleId: string, + options: ListJobsFromScheduleOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listJobsFromScheduleSend, + _listJobsFromScheduleDeserialize, + [context, jobScheduleId, options] + ); +} + +export function _listJobPreparationAndReleaseTaskStatusSend( + context: Client, + jobId: string, + options: ListJobPreparationAndReleaseTaskStatusOptions = { + requestOptions: {}, + } +): StreamableMethod< + | ListJobPreparationAndReleaseTaskStatus200Response + | ListJobPreparationAndReleaseTaskStatusDefaultResponse +> { + return context + .path("/jobs/{jobId}/jobpreparationandreleasetaskstatus", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + }, + }); +} + +export async function _listJobPreparationAndReleaseTaskStatusDeserialize( + result: + | ListJobPreparationAndReleaseTaskStatus200Response + | ListJobPreparationAndReleaseTaskStatusDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + poolId: p["poolId"], + nodeId: p["nodeId"], + nodeUrl: p["nodeUrl"], + jobPreparationTaskExecutionInfo: !p.jobPreparationTaskExecutionInfo + ? undefined + : { + startTime: new Date( + p.jobPreparationTaskExecutionInfo?.["startTime"] + ), + endTime: + p.jobPreparationTaskExecutionInfo?.["endTime"] !== undefined + ? new Date(p.jobPreparationTaskExecutionInfo?.["endTime"]) + : undefined, + state: p.jobPreparationTaskExecutionInfo?.["state"], + taskRootDirectory: + p.jobPreparationTaskExecutionInfo?.["taskRootDirectory"], + taskRootDirectoryUrl: + p.jobPreparationTaskExecutionInfo?.["taskRootDirectoryUrl"], + exitCode: p.jobPreparationTaskExecutionInfo?.["exitCode"], + containerInfo: !p.jobPreparationTaskExecutionInfo?.containerInfo + ? undefined + : { + containerId: + p.jobPreparationTaskExecutionInfo?.containerInfo?.[ + "containerId" + ], + state: + p.jobPreparationTaskExecutionInfo?.containerInfo?.["state"], + error: + p.jobPreparationTaskExecutionInfo?.containerInfo?.["error"], + }, + failureInfo: !p.jobPreparationTaskExecutionInfo?.failureInfo + ? undefined + : { + category: + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "category" + ], + code: p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "code" + ], + message: + p.jobPreparationTaskExecutionInfo?.failureInfo?.["message"], + details: ( + p.jobPreparationTaskExecutionInfo?.failureInfo?.[ + "details" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + retryCount: p.jobPreparationTaskExecutionInfo?.["retryCount"], + lastRetryTime: + p.jobPreparationTaskExecutionInfo?.["lastRetryTime"] !== undefined + ? new Date(p.jobPreparationTaskExecutionInfo?.["lastRetryTime"]) + : undefined, + result: p.jobPreparationTaskExecutionInfo?.["result"], + }, + jobReleaseTaskExecutionInfo: !p.jobReleaseTaskExecutionInfo + ? undefined + : { + startTime: new Date(p.jobReleaseTaskExecutionInfo?.["startTime"]), + endTime: + p.jobReleaseTaskExecutionInfo?.["endTime"] !== undefined + ? new Date(p.jobReleaseTaskExecutionInfo?.["endTime"]) + : undefined, + state: p.jobReleaseTaskExecutionInfo?.["state"], + taskRootDirectory: + p.jobReleaseTaskExecutionInfo?.["taskRootDirectory"], + taskRootDirectoryUrl: + p.jobReleaseTaskExecutionInfo?.["taskRootDirectoryUrl"], + exitCode: p.jobReleaseTaskExecutionInfo?.["exitCode"], + containerInfo: !p.jobReleaseTaskExecutionInfo?.containerInfo + ? undefined + : { + containerId: + p.jobReleaseTaskExecutionInfo?.containerInfo?.[ + "containerId" + ], + state: + p.jobReleaseTaskExecutionInfo?.containerInfo?.["state"], + error: + p.jobReleaseTaskExecutionInfo?.containerInfo?.["error"], + }, + failureInfo: !p.jobReleaseTaskExecutionInfo?.failureInfo + ? undefined + : { + category: + p.jobReleaseTaskExecutionInfo?.failureInfo?.["category"], + code: p.jobReleaseTaskExecutionInfo?.failureInfo?.["code"], + message: + p.jobReleaseTaskExecutionInfo?.failureInfo?.["message"], + details: ( + p.jobReleaseTaskExecutionInfo?.failureInfo?.["details"] ?? + [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + }, + result: p.jobReleaseTaskExecutionInfo?.["result"], + }, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** + * 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: ListJobPreparationAndReleaseTaskStatusOptions = { + requestOptions: {}, + } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listJobPreparationAndReleaseTaskStatusSend, + _listJobPreparationAndReleaseTaskStatusDeserialize, + [context, jobId, options] + ); +} + +export function _getJobTaskCountsSend( + context: Client, + jobId: string, + options: GetJobTaskCountsOptions = { requestOptions: {} } +): StreamableMethod< + GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse +> { + return context + .path("/jobs/{jobId}/taskcounts", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _getJobTaskCountsDeserialize( + result: GetJobTaskCounts200Response | GetJobTaskCountsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + taskCounts: { + active: result.body.taskCounts["active"], + running: result.body.taskCounts["running"], + completed: result.body.taskCounts["completed"], + succeeded: result.body.taskCounts["succeeded"], + failed: result.body.taskCounts["failed"], }, - executionInfo: !result.body.executionInfo - ? undefined - : { - nextRunTime: - result.body.executionInfo?.["nextRunTime"] !== undefined - ? new Date(result.body.executionInfo?.["nextRunTime"]) - : undefined, - recentJob: !result.body.executionInfo?.recentJob - ? undefined - : { - id: result.body.executionInfo?.recentJob?.["id"], - url: result.body.executionInfo?.recentJob?.["url"], - }, - endTime: - result.body.executionInfo?.["endTime"] !== undefined - ? new Date(result.body.executionInfo?.["endTime"]) - : undefined, - }, - metadata: (result.body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], + taskSlotCounts: { + active: result.body.taskSlotCounts["active"], + running: result.body.taskSlotCounts["running"], + completed: result.body.taskSlotCounts["completed"], + succeeded: result.body.taskSlotCounts["succeeded"], + failed: result.body.taskSlotCounts["failed"], + }, + }; +} + +/** + * 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: GetJobTaskCountsOptions = { requestOptions: {} } +): Promise { + const result = await _getJobTaskCountsSend(context, jobId, options); + return _getJobTaskCountsDeserialize(result); +} + +export function _createCertificateSend( + context: Client, + body: BatchCertificate, + options: CreateCertificateOptions = { requestOptions: {} } +): StreamableMethod< + CreateCertificate201Response | CreateCertificateDefaultResponse +> { + return context + .path("/certificates") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + thumbprint: body["thumbprint"], + thumbprintAlgorithm: body["thumbprintAlgorithm"], + data: uint8ArrayToString(body["data"], "base64"), + certificateFormat: body["certificateFormat"], + password: body["password"], + }, + }); +} + +export async function _createCertificateDeserialize( + result: CreateCertificate201Response | CreateCertificateDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Creates a Certificate to the specified Account. */ +export async function createCertificate( + context: Client, + body: BatchCertificate, + options: CreateCertificateOptions = { requestOptions: {} } +): Promise { + const result = await _createCertificateSend(context, body, options); + return _createCertificateDeserialize(result); +} + +export function _listCertificatesSend( + context: Client, + options: ListCertificatesOptions = { requestOptions: {} } +): StreamableMethod< + ListCertificates200Response | ListCertificatesDefaultResponse +> { + return context + .path("/certificates") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + }, + }); +} + +export async function _listCertificatesDeserialize( + result: ListCertificates200Response | ListCertificatesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + value: (result.body["value"] ?? []).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + url: p["url"], + state: p["state"], + stateTransitionTime: + p["stateTransitionTime"] !== undefined + ? new Date(p["stateTransitionTime"]) + : undefined, + previousState: p["previousState"], + previousStateTransitionTime: + p["previousStateTransitionTime"] !== undefined + ? new Date(p["previousStateTransitionTime"]) + : undefined, + publicData: + typeof p["publicData"] === "string" + ? stringToUint8Array(p["publicData"], "base64") + : p["publicData"], + deleteCertificateError: !p.deleteCertificateError + ? undefined + : { + code: p.deleteCertificateError?.["code"], + message: p.deleteCertificateError?.["message"], + values: (p.deleteCertificateError?.["values"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + data: + typeof p["data"] === "string" + ? stringToUint8Array(p["data"], "base64") + : p["data"], + certificateFormat: p["certificateFormat"], + password: p["password"], })), - stats: !result.body.stats + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +/** Lists all of the Certificates that have been added to the specified Account. */ +export function listCertificates( + context: Client, + options: ListCertificatesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + _listCertificatesSend, + _listCertificatesDeserialize, + [context, options] + ); +} + +export function _cancelCertificateDeletionSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptions = { requestOptions: {} } +): StreamableMethod< + | CancelCertificateDeletion204Response + | CancelCertificateDeletionDefaultResponse +> { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete", + thumbprintAlgorithm, + thumbprint + ) + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _cancelCertificateDeletionDeserialize( + result: + | CancelCertificateDeletion204Response + | CancelCertificateDeletionDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: CancelCertificateDeletionOptions = { requestOptions: {} } +): Promise { + const result = await _cancelCertificateDeletionSend( + context, + thumbprintAlgorithm, + thumbprint, + options + ); + return _cancelCertificateDeletionDeserialize(result); +} + +export function _deleteCertificateSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: DeleteCertificateOptions = { requestOptions: {} } +): StreamableMethod< + DeleteCertificate202Response | DeleteCertificateDefaultResponse +> { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint + ) + .delete({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _deleteCertificateDeserialize( + result: DeleteCertificate202Response | DeleteCertificateDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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: DeleteCertificateOptions = { requestOptions: {} } +): Promise { + const result = await _deleteCertificateSend( + context, + thumbprintAlgorithm, + thumbprint, + options + ); + return _deleteCertificateDeserialize(result); +} + +export function _getCertificateSend( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptions = { requestOptions: {} } +): StreamableMethod { + return context + .path( + "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})", + thumbprintAlgorithm, + thumbprint + ) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, + }); +} + +export async function _getCertificateDeserialize( + result: GetCertificate200Response | GetCertificateDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + thumbprint: result.body["thumbprint"], + thumbprintAlgorithm: result.body["thumbprintAlgorithm"], + url: result.body["url"], + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + publicData: + typeof result.body["publicData"] === "string" + ? stringToUint8Array(result.body["publicData"], "base64") + : result.body["publicData"], + deleteCertificateError: !result.body.deleteCertificateError ? undefined : { - url: result.body.stats?.["url"], - startTime: new Date(result.body.stats?.["startTime"]), - lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), - userCPUTime: result.body.stats?.["userCPUTime"], - kernelCPUTime: result.body.stats?.["kernelCPUTime"], - wallClockTime: result.body.stats?.["wallClockTime"], - readIOps: result.body.stats?.["readIOps"], - writeIOps: result.body.stats?.["writeIOps"], - readIOGiB: result.body.stats?.["readIOGiB"], - writeIOGiB: result.body.stats?.["writeIOGiB"], - numSucceededTasks: result.body.stats?.["numSucceededTasks"], - numFailedTasks: result.body.stats?.["numFailedTasks"], - numTaskRetries: result.body.stats?.["numTaskRetries"], - waitTime: result.body.stats?.["waitTime"], + code: result.body.deleteCertificateError?.["code"], + message: result.body.deleteCertificateError?.["message"], + values: (result.body.deleteCertificateError?.["values"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), }, + data: + typeof result.body["data"] === "string" + ? stringToUint8Array(result.body["data"], "base64") + : result.body["data"], + certificateFormat: result.body["certificateFormat"], + password: result.body["password"], }; } -/** Gets information about the specified Job Schedule. */ -export async function getJobSchedule( +/** Gets information about the specified Certificate. */ +export async function getCertificate( + context: Client, + thumbprintAlgorithm: string, + thumbprint: string, + options: GetCertificateOptions = { requestOptions: {} } +): Promise { + const result = await _getCertificateSend( + context, + thumbprintAlgorithm, + thumbprint, + options + ); + return _getCertificateDeserialize(result); +} + +export function _jobScheduleExistsSend( context: Client, jobScheduleId: string, - options: GetJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _getJobScheduleSend(context, jobScheduleId, options); - return _getJobScheduleDeserialize(result); + options: JobScheduleExistsOptions = { requestOptions: {} } +): StreamableMethod< + | JobScheduleExists200Response + | JobScheduleExists404Response + | JobScheduleExistsDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .head({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } -export function _updateJobScheduleSend( +export async function _jobScheduleExistsDeserialize( + result: + | JobScheduleExists200Response + | JobScheduleExists404Response + | JobScheduleExistsDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return; +} + +/** Checks the specified Job Schedule exists. */ +export async function jobScheduleExists( context: Client, jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptions = { requestOptions: {} } + options: JobScheduleExistsOptions = { requestOptions: {} } +): Promise { + const result = await _jobScheduleExistsSend(context, jobScheduleId, options); + return _jobScheduleExistsDeserialize(result); +} + +export function _deleteJobScheduleSend( + context: Client, + jobScheduleId: string, + options: DeleteJobScheduleOptions = { requestOptions: {} } ): StreamableMethod< - UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse + DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse > { - return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).patch({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), + return context + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); +} + +export async function _deleteJobScheduleDeserialize( + result: DeleteJobSchedule202Response | DeleteJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + jobScheduleId: string, + options: DeleteJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _deleteJobScheduleSend(context, jobScheduleId, options); + return _deleteJobScheduleDeserialize(result); +} + +export function _getJobScheduleSend( + context: Client, + jobScheduleId: string, + options: GetJobScheduleOptions = { 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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); +} + +export async function _getJobScheduleDeserialize( + result: GetJobSchedule200Response | GetJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + id: result.body["id"], + displayName: result.body["displayName"], + url: result.body["url"], + eTag: result.body["eTag"], + lastModified: + result.body["lastModified"] !== undefined + ? new Date(result.body["lastModified"]) + : undefined, + creationTime: + result.body["creationTime"] !== undefined + ? new Date(result.body["creationTime"]) + : undefined, + state: result.body["state"], + stateTransitionTime: + result.body["stateTransitionTime"] !== undefined + ? new Date(result.body["stateTransitionTime"]) + : undefined, + previousState: result.body["previousState"], + previousStateTransitionTime: + result.body["previousStateTransitionTime"] !== undefined + ? new Date(result.body["previousStateTransitionTime"]) + : undefined, + schedule: { + doNotRunUntil: + result.body.schedule["doNotRunUntil"] !== undefined + ? new Date(result.body.schedule["doNotRunUntil"]) + : undefined, + doNotRunAfter: + result.body.schedule["doNotRunAfter"] !== undefined + ? new Date(result.body.schedule["doNotRunAfter"]) + : undefined, + startWindow: result.body.schedule["startWindow"], + recurrenceInterval: result.body.schedule["recurrenceInterval"], }, - queryParameters: { timeOut: options?.timeOut }, - body: { - schedule: !body.schedule + jobSpecification: { + priority: result.body.jobSpecification["priority"], + allowTaskPreemption: result.body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: result.body.jobSpecification["maxParallelTasks"], + displayName: result.body.jobSpecification["displayName"], + usesTaskDependencies: + result.body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: result.body.jobSpecification["onAllTasksComplete"], + onTaskFailure: result.body.jobSpecification["onTaskFailure"], + networkConfiguration: !result.body.jobSpecification.networkConfiguration ? undefined : { - doNotRunUntil: body.schedule?.["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule?.["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule?.["startWindow"], - recurrenceInterval: body.schedule?.["recurrenceInterval"], + subnetId: + result.body.jobSpecification.networkConfiguration?.["subnetId"], }, - jobSpecification: !body.jobSpecification + constraints: !result.body.jobSpecification.constraints ? undefined : { - priority: body.jobSpecification?.["priority"], - allowTaskPreemption: body.jobSpecification?.["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification?.["maxParallelTasks"], - displayName: body.jobSpecification?.["displayName"], - usesTaskDependencies: - body.jobSpecification?.["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification?.["onAllTasksComplete"], - onTaskFailure: body.jobSpecification?.["onTaskFailure"], - networkConfiguration: !body.jobSpecification?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification?.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification?.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification?.jobManagerTask + maxWallClockTime: + result.body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + result.body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !result.body.jobSpecification.jobManagerTask + ? undefined + : { + id: result.body.jobSpecification.jobManagerTask?.["id"], + displayName: + result.body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + result.body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobManagerTask + ?.containerSettings ? undefined : { - id: body.jobSpecification?.jobManagerTask?.["id"], - displayName: - body.jobSpecification?.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification?.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobManagerTask - ?.containerSettings + containerRunOptions: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry ? undefined : { - containerRunOptions: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry + username: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference ? undefined : { - username: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, + resourceId: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - workingDirectory: - body.jobSpecification?.jobManagerTask - ?.containerSettings?.["workingDirectory"], }, - resourceFiles: ( - body.jobSpecification?.jobManagerTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - body.jobSpecification?.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + workingDirectory: + result.body.jobSpecification.jobManagerTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + result.body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + result.body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference ? undefined : { - path: p.destination.container?.["path"], - containerUrl: - p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container - ?.identityReference?.["resourceId"], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - body.jobSpecification?.jobManagerTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification?.jobManagerTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification?.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification?.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification?.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification?.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification?.jobManagerTask?.[ - "killJobOnCompletion" + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + result.body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobSpecification.jobManagerTask + ?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" ], - userIdentity: !body.jobSpecification?.jobManagerTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification?.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobManagerTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - body.jobSpecification?.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobSpecification?.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification - ?.jobManagerTask?.authenticationTokenSettings + retentionTime: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + result.body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + result.body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + result.body.jobSpecification.jobManagerTask?.[ + "killJobOnCompletion" + ], + userIdentity: !result.body.jobSpecification.jobManagerTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser ? undefined : { - access: - body.jobSpecification?.jobManagerTask - ?.authenticationTokenSettings?.["access"], + scope: + result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser?.["elevationLevel"], }, - allowLowPriorityNode: - body.jobSpecification?.jobManagerTask?.[ - "allowLowPriorityNode" - ], }, - jobPreparationTask: !body.jobSpecification?.jobPreparationTask + runExclusive: + result.body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + result.body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !result.body.jobSpecification + .jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + result.body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + result.body.jobSpecification.jobManagerTask?.[ + "allowLowPriorityNode" + ], + }, + jobPreparationTask: !result.body.jobSpecification.jobPreparationTask + ? undefined + : { + id: result.body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + result.body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobPreparationTask + ?.containerSettings ? undefined : { - id: body.jobSpecification?.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification?.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobPreparationTask - ?.containerSettings + containerRunOptions: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry ? undefined : { - containerRunOptions: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry + username: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference ? undefined : { - username: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobPreparationTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, + resourceId: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - workingDirectory: - body.jobSpecification?.jobPreparationTask - ?.containerSettings?.["workingDirectory"], }, - resourceFiles: ( - body.jobSpecification?.jobPreparationTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification?.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification?.jobPreparationTask - ?.constraints + workingDirectory: + result.body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + result.body.jobSpecification.jobPreparationTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + result.body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !result.body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["maxWallClockTime"], + retentionTime: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["retentionTime"], + maxTaskRetryCount: + result.body.jobSpecification.jobPreparationTask + ?.constraints?.["maxTaskRetryCount"], + }, + waitForSuccess: + result.body.jobSpecification.jobPreparationTask?.[ + "waitForSuccess" + ], + userIdentity: !result.body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser ? undefined : { - maxWallClockTime: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["maxWallClockTime"], - retentionTime: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["retentionTime"], - maxTaskRetryCount: - body.jobSpecification?.jobPreparationTask - ?.constraints?.["maxTaskRetryCount"], + scope: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], }, - waitForSuccess: - body.jobSpecification?.jobPreparationTask?.[ - "waitForSuccess" - ], - userIdentity: !body.jobSpecification?.jobPreparationTask - ?.userIdentity + }, + rerunOnNodeRebootAfterSuccess: + result.body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !result.body.jobSpecification.jobReleaseTask + ? undefined + : { + id: result.body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + result.body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !result.body.jobSpecification.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry ? undefined : { username: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["registryServer"], + identityReference: !result.body.jobSpecification + .jobReleaseTask?.containerSettings?.registry + ?.identityReference ? undefined : { - scope: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], + resourceId: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification?.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], + workingDirectory: + result.body.jobSpecification.jobReleaseTask + ?.containerSettings?.["workingDirectory"], }, - jobReleaseTask: !body.jobSpecification?.jobReleaseTask + resourceFiles: ( + result.body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + result.body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + result.body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + result.body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !result.body.jobSpecification.jobReleaseTask + ?.userIdentity ? undefined : { - id: body.jobSpecification?.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification?.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification?.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry?.[ - "registryServer" - ], - identityReference: !body.jobSpecification - ?.jobReleaseTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification?.jobReleaseTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification?.jobReleaseTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification?.jobReleaseTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification?.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification?.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification?.jobReleaseTask - ?.userIdentity + username: + result.body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser ? undefined : { - username: - body.jobSpecification?.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.jobReleaseTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, + scope: + result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + result.body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser?.["elevationLevel"], }, }, - commonEnvironmentSettings: ( - body.jobSpecification?.["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.jobSpecification?.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification?.poolInfo - .autoPoolSpecification + }, + commonEnvironmentSettings: ( + result.body.jobSpecification["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: result.body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !result.body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + result.body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !result.body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool ? undefined : { - autoPoolIdPrefix: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification?.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification?.poolInfo.autoPoolSpecification - ?.pool + displayName: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["displayName"], + vmSize: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration ? undefined : { - displayName: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["displayName"], - vmSize: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.cloudServiceConfiguration + osFamily: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "publisher" + ], + offer: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "offer" + ], + sku: result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "version" + ], + virtualMachineImageId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "virtualMachineImageId" + ], + exactVersion: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "exactVersion" + ], + }, + nodeAgentSKUId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["nodeAgentSKUId"], + windowsConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.windowsConfiguration ? undefined : { - osFamily: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification?.poolInfo + enableAutomaticUpdates: + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], }, - virtualMachineConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool + dataDisks: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["dataDisks"] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["licenseType"], + containerConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool ?.virtualMachineConfiguration + ?.containerConfiguration ? undefined : { - imageReference: { - publisher: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["publisher"], - offer: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["offer"], - sku: body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["sku"], - version: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["version"], - virtualMachineImageId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.imageReference["virtualMachineImageId"], - }, - nodeAgentSKUId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool + type: result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "dataDisks" - ] ?? [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.jobSpecification?.poolInfo + ?.containerConfiguration?.["type"], + containerImageNames: + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "licenseType" + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" ], - containerConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.[ - "resourceId" - ], - }, - })), - }, - diskEncryptionConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.[ - "policy" - ], - }, - extensions: ( - body.jobSpecification?.poolInfo + containerRegistries: ( + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "extensions" + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" ] ?? [] ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk - ?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), }, - taskSlotsPerNode: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "taskSlotsPerNode" - ], - taskSchedulingPolicy: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy + diskEncryptionConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.diskEncryptionConfiguration ? undefined : { - nodeFillType: - body.jobSpecification?.poolInfo + targets: + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.["targets"], }, - resizeTimeout: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetDedicatedNodes" - ], - targetLowPriorityNodes: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetLowPriorityNodes" - ], - enableAutoScale: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleFormula" - ], - autoScaleEvaluationInterval: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "autoScaleEvaluationInterval" - ], - enableInterNodeCommunication: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "enableInterNodeCommunication" - ], - networkConfiguration: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration + nodePlacementConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.nodePlacementConfiguration ? undefined : { - subnetId: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification?.poolInfo + policy: + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: - p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body - .jobSpecification?.poolInfo + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.["policy"], + }, + extensions: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.["extensions"] ?? + [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !result.body + .jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings ? undefined : { - provision: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.jobSpecification?.poolInfo + placement: + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" ], }, - enableAcceleratedNetworking: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], }, - startTask: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask + }, + taskSlotsPerNode: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["resizeTimeout"], + targetDedicatedNodes: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["enableAutoScale"], + autoScaleFormula: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration ? undefined : { - commandLine: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification - ?.poolInfo.autoPoolSpecification?.pool - ?.startTask?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "imageName" - ], - registry: !body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification - ?.poolInfo - .autoPoolSpecification - ?.pool?.startTask - ?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - environmentSettings: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" + inboundNATPools: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" ] ?? [] ).map((p) => ({ name: p["name"], - value: p["value"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), })), - userIdentity: !body.jobSpecification?.poolInfo + }, + publicIPAddressConfiguration: !result.body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !result.body.jobSpecification + .poolInfo.autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool?.startTask - ?.userIdentity + ?.containerSettings?.registry ? undefined : { username: - body.jobSpecification?.poolInfo + result.body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.startTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification?.poolInfo + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !result.body + .jobSpecification.poolInfo .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser + ?.containerSettings?.registry + ?.identityReference ? undefined : { - scope: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], + resourceId: + result.body.jobSpecification + .poolInfo.autoPoolSpecification + ?.pool?.startTask + ?.containerSettings?.registry + ?.identityReference?.[ + "resourceId" + ], }, }, - maxTaskRetryCount: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], + workingDirectory: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["workingDirectory"], }, - certificateReferences: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "certificateReferences" - ] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "applicationLicenses" - ], - userAccounts: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["userAccounts"] ?? - [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: - !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.["metadata"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - mountConfiguration: ( - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "mountConfiguration" + resourceFiles: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" ] ?? [] ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration - ? undefined - : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], - relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ - "relativeMountPath" - ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.[ - "resourceId" - ], - }, - }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: - p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: - p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration - ? undefined - : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.[ - "accountKey" - ], - relativeMountPath: - p.azureFileShareConfiguration?.[ - "relativeMountPath" - ], - mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], - }, + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, })), - targetNodeCommunicationMode: - body.jobSpecification?.poolInfo - .autoPoolSpecification?.pool?.[ - "targetNodeCommunicationMode" + environmentSettings: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser?.[ + "scope" + ], + elevationLevel: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" ], }, + certificateReferences: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["applicationLicenses"], + userAccounts: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["userAccounts"] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["metadata"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.["mountConfiguration"] ?? + [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.["sasKey"], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.["relativeMountPath"], + mountOptions: + p.cifsMountConfiguration?.["mountOptions"], + password: p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.["accountName"], + azureFileUrl: + p.azureFileShareConfiguration?.["azureFileUrl"], + accountKey: + p.azureFileShareConfiguration?.["accountKey"], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.["mountOptions"], + }, + })), + targetNodeCommunicationMode: + result.body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], }, }, - metadata: (body.jobSpecification?.["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - metadata: (body["metadata"] ?? []).map((p) => ({ + }, + metadata: (result.body.jobSpecification["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), }, - }); -} - -export async function _updateJobScheduleDeserialize( - result: UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - 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( + executionInfo: !result.body.executionInfo + ? undefined + : { + nextRunTime: + result.body.executionInfo?.["nextRunTime"] !== undefined + ? new Date(result.body.executionInfo?.["nextRunTime"]) + : undefined, + recentJob: !result.body.executionInfo?.recentJob + ? undefined + : { + id: result.body.executionInfo?.recentJob?.["id"], + url: result.body.executionInfo?.recentJob?.["url"], + }, + endTime: + result.body.executionInfo?.["endTime"] !== undefined + ? new Date(result.body.executionInfo?.["endTime"]) + : undefined, + }, + metadata: (result.body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + stats: !result.body.stats + ? undefined + : { + url: result.body.stats?.["url"], + startTime: new Date(result.body.stats?.["startTime"]), + lastUpdateTime: new Date(result.body.stats?.["lastUpdateTime"]), + userCPUTime: result.body.stats?.["userCPUTime"], + kernelCPUTime: result.body.stats?.["kernelCPUTime"], + wallClockTime: result.body.stats?.["wallClockTime"], + readIOps: result.body.stats?.["readIOps"], + writeIOps: result.body.stats?.["writeIOps"], + readIOGiB: result.body.stats?.["readIOGiB"], + writeIOGiB: result.body.stats?.["writeIOGiB"], + numSucceededTasks: result.body.stats?.["numSucceededTasks"], + numFailedTasks: result.body.stats?.["numFailedTasks"], + numTaskRetries: result.body.stats?.["numTaskRetries"], + waitTime: result.body.stats?.["waitTime"], + }, + }; +} + +/** Gets information about the specified Job Schedule. */ +export async function getJobSchedule( context: Client, jobScheduleId: string, - body: BatchJobScheduleUpdateOptions, - options: UpdateJobScheduleOptions = { requestOptions: {} } -): Promise { - const result = await _updateJobScheduleSend( - context, - jobScheduleId, - body, - options - ); - return _updateJobScheduleDeserialize(result); + options: GetJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _getJobScheduleSend(context, jobScheduleId, options); + return _getJobScheduleDeserialize(result); } -export function _replaceJobScheduleSend( +export function _updateJobScheduleSend( context: Client, jobScheduleId: string, - body: BatchJobSchedule, - options: ReplaceJobScheduleOptions = { requestOptions: {} } + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptions = { requestOptions: {} } ): StreamableMethod< - ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse + UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse > { - return context.path("/jobschedules/{jobScheduleId}", jobScheduleId).put({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - schedule: { - doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule["startWindow"], - recurrenceInterval: body.schedule["recurrenceInterval"], + return context + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .patch({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), }, - jobSpecification: { - priority: body.jobSpecification["priority"], - allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification["maxParallelTasks"], - displayName: body.jobSpecification["displayName"], - usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], - onTaskFailure: body.jobSpecification["onTaskFailure"], - networkConfiguration: !body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification.constraints + queryParameters: { timeOut: options?.timeOut }, + body: { + schedule: !body.schedule ? undefined : { - maxWallClockTime: - body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification.constraints?.["maxTaskRetryCount"], + doNotRunUntil: body.schedule?.["doNotRunUntil"]?.toISOString(), + doNotRunAfter: body.schedule?.["doNotRunAfter"]?.toISOString(), + startWindow: body.schedule?.["startWindow"], + recurrenceInterval: body.schedule?.["recurrenceInterval"], }, - jobManagerTask: !body.jobSpecification.jobManagerTask + jobSpecification: !body.jobSpecification ? undefined : { - id: body.jobSpecification.jobManagerTask?.["id"], - displayName: - body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobManagerTask - ?.containerSettings + priority: body.jobSpecification?.["priority"], + allowTaskPreemption: + body.jobSpecification?.["allowTaskPreemption"], + maxParallelTasks: body.jobSpecification?.["maxParallelTasks"], + displayName: body.jobSpecification?.["displayName"], + usesTaskDependencies: + body.jobSpecification?.["usesTaskDependencies"], + onAllTasksComplete: body.jobSpecification?.["onAllTasksComplete"], + onTaskFailure: body.jobSpecification?.["onTaskFailure"], + networkConfiguration: !body.jobSpecification?.networkConfiguration ? undefined : { - containerRunOptions: - body.jobSpecification.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.jobManagerTask?.containerSettings?.[ - "imageName" - ], - registry: !body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], + subnetId: + body.jobSpecification?.networkConfiguration?.["subnetId"], }, - resourceFiles: ( - body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - body.jobSpecification.jobManagerTask?.["environmentSettings"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobManagerTask?.constraints + constraints: !body.jobSpecification?.constraints ? undefined : { maxWallClockTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], + body.jobSpecification?.constraints?.["maxWallClockTime"], maxTaskRetryCount: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobSpecification.jobManagerTask?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], + body.jobSpecification?.constraints?.["maxTaskRetryCount"], }, - allowLowPriorityNode: - body.jobSpecification.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !body.jobSpecification.jobPreparationTask - ? undefined - : { - id: body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobPreparationTask - ?.containerSettings + jobManagerTask: !body.jobSpecification?.jobManagerTask ? undefined : { - containerRunOptions: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry + id: body.jobSpecification?.jobManagerTask?.["id"], + displayName: + body.jobSpecification?.jobManagerTask?.["displayName"], + commandLine: + body.jobSpecification?.jobManagerTask?.["commandLine"], + containerSettings: !body.jobSpecification?.jobManagerTask + ?.containerSettings ? undefined : { - username: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference + containerRunOptions: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry ? undefined : { - resourceId: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + username: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + ?.jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, }, + workingDirectory: + body.jobSpecification?.jobManagerTask + ?.containerSettings?.["workingDirectory"], }, - workingDirectory: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: - body.jobSpecification.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask?.userIdentity?.[ - "username" + resourceFiles: ( + body.jobSpecification?.jobManagerTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + body.jobSpecification?.jobManagerTask?.["outputFiles"] ?? + [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container + ?.identityReference?.["resourceId"], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + body.jobSpecification?.jobManagerTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification?.jobManagerTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification?.jobManagerTask + ?.constraints?.["maxWallClockTime"], + retentionTime: + body.jobSpecification?.jobManagerTask + ?.constraints?.["retentionTime"], + maxTaskRetryCount: + body.jobSpecification?.jobManagerTask + ?.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: + body.jobSpecification?.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + body.jobSpecification?.jobManagerTask?.[ + "killJobOnCompletion" ], - autoUser: !body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser + userIdentity: !body.jobSpecification?.jobManagerTask + ?.userIdentity ? undefined : { - scope: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], + username: + body.jobSpecification?.jobManagerTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification?.jobManagerTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification?.jobManagerTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.jobManagerTask + ?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, + }, + runExclusive: + body.jobSpecification?.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobSpecification?.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobSpecification + ?.jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + body.jobSpecification?.jobManagerTask + ?.authenticationTokenSettings?.["access"], }, + allowLowPriorityNode: + body.jobSpecification?.jobManagerTask?.[ + "allowLowPriorityNode" + ], }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification.jobReleaseTask - ? undefined - : { - id: body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobReleaseTask - ?.containerSettings + jobPreparationTask: !body.jobSpecification?.jobPreparationTask ? undefined : { - containerRunOptions: - body.jobSpecification.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" + id: body.jobSpecification?.jobPreparationTask?.["id"], + commandLine: + body.jobSpecification?.jobPreparationTask?.[ + "commandLine" ], - imageName: - body.jobSpecification.jobReleaseTask?.containerSettings?.[ - "imageName" + containerSettings: !body.jobSpecification + ?.jobPreparationTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + ?.jobPreparationTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification + ?.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification?.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification?.jobPreparationTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification?.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification?.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification?.jobPreparationTask + ?.constraints?.["maxWallClockTime"], + retentionTime: + body.jobSpecification?.jobPreparationTask + ?.constraints?.["retentionTime"], + maxTaskRetryCount: + body.jobSpecification?.jobPreparationTask + ?.constraints?.["maxTaskRetryCount"], + }, + waitForSuccess: + body.jobSpecification?.jobPreparationTask?.[ + "waitForSuccess" ], - registry: !body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + userIdentity: !body.jobSpecification?.jobPreparationTask + ?.userIdentity ? undefined : { username: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !body.jobSpecification - .jobReleaseTask?.containerSettings?.registry - ?.identityReference + body.jobSpecification?.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification?.jobPreparationTask + ?.userIdentity?.autoUser ? undefined : { - resourceId: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + scope: + body.jobSpecification?.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.jobPreparationTask + ?.userIdentity?.autoUser?.[ + "elevationLevel" + ], }, }, - workingDirectory: - body.jobSpecification.jobReleaseTask?.containerSettings?.[ - "workingDirectory" + rerunOnNodeRebootAfterSuccess: + body.jobSpecification?.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" ], }, - resourceFiles: ( - body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobReleaseTask?.["environmentSettings"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification.jobReleaseTask?.userIdentity + jobReleaseTask: !body.jobSpecification?.jobReleaseTask ? undefined : { - username: - body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" + id: body.jobSpecification?.jobReleaseTask?.["id"], + commandLine: + body.jobSpecification?.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobSpecification?.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + ?.jobReleaseTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification?.jobReleaseTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification?.jobReleaseTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification?.jobReleaseTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + body.jobSpecification?.jobReleaseTask?.[ + "maxWallClockTime" ], - autoUser: !body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser + retentionTime: + body.jobSpecification?.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobSpecification?.jobReleaseTask + ?.userIdentity ? undefined : { - scope: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["elevationLevel"], + username: + body.jobSpecification?.jobReleaseTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification?.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification?.jobReleaseTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.jobReleaseTask + ?.userIdentity?.autoUser?.[ + "elevationLevel" + ], + }, }, }, - }, - commonEnvironmentSettings: ( - body.jobSpecification["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification.poolInfo - .autoPoolSpecification - ? undefined - : { - autoPoolIdPrefix: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" - ], - pool: !body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool + commonEnvironmentSettings: ( + body.jobSpecification?.["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.jobSpecification?.poolInfo["poolId"], + autoPoolSpecification: !body.jobSpecification?.poolInfo + .autoPoolSpecification ? undefined : { - displayName: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["displayName"], - vmSize: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration - ? undefined - : { - osFamily: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], - }, - virtualMachineConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration + autoPoolIdPrefix: + body.jobSpecification?.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + body.jobSpecification?.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.jobSpecification?.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool ? undefined : { - imageReference: { - publisher: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "publisher" - ], - offer: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" - ], - }, - nodeAgentSKUId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" + displayName: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["displayName"], + vmSize: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["vmSize"], + cloudServiceConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.[ + "osVersion" + ], + }, + virtualMachineConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["sku"], + version: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference[ + "virtualMachineImageId" + ], + }, + nodeAgentSKUId: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: + !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "taskSlotsPerNode" ], - windowsConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration + taskSchedulingPolicy: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.taskSchedulingPolicy ? undefined : { - enableAutomaticUpdates: - body.jobSpecification.poolInfo + nodeFillType: + body.jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], + ?.taskSchedulingPolicy?.["nodeFillType"], }, - dataDisks: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? - [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration + resizeTimeout: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["resizeTimeout"], + targetDedicatedNodes: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "targetDedicatedNodes" + ], + targetLowPriorityNodes: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "targetLowPriorityNodes" + ], + enableAutoScale: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "enableAutoScale" + ], + autoScaleFormula: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleFormula" + ], + autoScaleEvaluationInterval: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "autoScaleEvaluationInterval" + ], + enableInterNodeCommunication: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "enableInterNodeCommunication" + ], + networkConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration ? undefined : { - type: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification.poolInfo + subnetId: + body.jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" ], - containerRegistries: ( - body.jobSpecification.poolInfo + endpointConfiguration: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: + p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.jobSpecification?.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "imageName" + ], + registry: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry + ? undefined + : { + username: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.[ + "registryServer" + ], + identityReference: !body + .jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification + ?.poolInfo + .autoPoolSpecification + ?.pool?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" ] ?? [] ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: + p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], identityReference: !p.identityReference ? undefined : { @@ -11298,461 +10665,1310 @@ export function _replaceJobScheduleSend( p.identityReference?.["resourceId"], }, })), - }, - diskEncryptionConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" + environmentSettings: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification + ?.poolInfo.autoPoolSpecification?.pool + ?.startTask?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.[ + "elevationLevel" + ], + }, + }, + maxTaskRetryCount: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" ], }, - nodePlacementConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] + certificateReferences: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "certificateReferences" + ] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "applicationLicenses" + ], + userAccounts: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "userAccounts" + ] ?? [] ).map((p) => ({ name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.[ + "sshPrivateKey" + ], + }, + windowsUserConfiguration: + !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.[ + "loginMode" + ], + }, })), - osDisk: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk + metadata: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.["metadata"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + mountConfiguration: ( + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "mountConfiguration" + ] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration + ? undefined + : { + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference + ? undefined + : { + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.[ + "resourceId" + ], + }, + }, + nfsMountConfiguration: !p.nfsMountConfiguration + ? undefined + : { + source: p.nfsMountConfiguration?.["source"], + relativeMountPath: + p.nfsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], + }, + cifsMountConfiguration: !p.cifsMountConfiguration + ? undefined + : { + username: + p.cifsMountConfiguration?.["username"], + source: + p.cifsMountConfiguration?.["source"], + relativeMountPath: + p.cifsMountConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.cifsMountConfiguration?.[ + "mountOptions" + ], + password: + p.cifsMountConfiguration?.["password"], + }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.jobSpecification?.poolInfo + .autoPoolSpecification?.pool?.[ + "targetNodeCommunicationMode" + ], + }, + }, + }, + metadata: (body.jobSpecification?.["metadata"] ?? []).map( + (p) => ({ name: p["name"], value: p["value"] }) + ), + }, + metadata: (body["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }); +} + +export async function _updateJobScheduleDeserialize( + result: UpdateJobSchedule200Response | UpdateJobScheduleDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + 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( + context: Client, + jobScheduleId: string, + body: BatchJobScheduleUpdateOptions, + options: UpdateJobScheduleOptions = { requestOptions: {} } +): Promise { + const result = await _updateJobScheduleSend( + context, + jobScheduleId, + body, + options + ); + return _updateJobScheduleDeserialize(result); +} + +export function _replaceJobScheduleSend( + context: Client, + jobScheduleId: string, + body: BatchJobSchedule, + options: ReplaceJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + ReplaceJobSchedule200Response | ReplaceJobScheduleDefaultResponse +> { + return context + .path("/jobschedules/{jobScheduleId}", jobScheduleId) + .put({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + schedule: { + doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), + doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), + startWindow: body.schedule["startWindow"], + recurrenceInterval: body.schedule["recurrenceInterval"], + }, + jobSpecification: { + priority: body.jobSpecification["priority"], + allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: body.jobSpecification["maxParallelTasks"], + displayName: body.jobSpecification["displayName"], + usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], + onTaskFailure: body.jobSpecification["onTaskFailure"], + networkConfiguration: !body.jobSpecification.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification.networkConfiguration?.["subnetId"], + }, + constraints: !body.jobSpecification.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobSpecification.jobManagerTask + ? undefined + : { + id: body.jobSpecification.jobManagerTask?.["id"], + displayName: + body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobManagerTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference ? undefined : { - ephemeralOSDiskSettings: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, + resourceId: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, }, - taskSlotsPerNode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy + workingDirectory: + body.jobSpecification.jobManagerTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container + ? undefined + : { + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container + ?.identityReference + ? undefined + : { + resourceId: + p.destination.container?.identityReference?.[ + "resourceId" + ], + }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + }, + }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !body.jobSpecification.jobManagerTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser ? undefined : { - nodeFillType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], + scope: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["elevationLevel"], }, - resizeTimeout: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetLowPriorityNodes"], - enableAutoScale: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleEvaluationInterval"], - enableInterNodeCommunication: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableInterNodeCommunication"], - networkConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration + }, + runExclusive: + body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobSpecification + .jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + body.jobSpecification.jobManagerTask?.[ + "allowLowPriorityNode" + ], + }, + jobPreparationTask: !body.jobSpecification.jobPreparationTask + ? undefined + : { + id: body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry ? undefined : { - subnetId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" + username: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.[ + "registryServer" ], - endpointConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] - ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], - })), - })), - }, - publicIPAddressConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration + identityReference: !body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference ? undefined : { - provision: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], + resourceId: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], }, - enableAcceleratedNetworking: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], }, - startTask: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask + workingDirectory: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: + body.jobSpecification.jobPreparationTask?.["waitForSuccess"], + userIdentity: !body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" + ], + }, + jobReleaseTask: !body.jobSpecification.jobReleaseTask + ? undefined + : { + id: body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobReleaseTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry ? undefined : { - commandLine: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" + username: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.[ + "registryServer" ], - containerSettings: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings + identityReference: !body.jobSpecification + .jobReleaseTask?.containerSettings?.registry + ?.identityReference ? undefined : { - containerRunOptions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.poolInfo + resourceId: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobSpecification.jobReleaseTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: ( + body.jobSpecification["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool + ? undefined + : { + displayName: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["displayName"], + vmSize: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["vmSize"], + cloudServiceConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.imageReference[ + "sku" + ], + version: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + }, + nodeAgentSKUId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "extensions" + ] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["resizeTimeout"], + targetDedicatedNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetLowPriorityNodes"], + enableAutoScale: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableAutoScale"], + autoScaleFormula: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleEvaluationInterval"], + enableInterNodeCommunication: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableInterNodeCommunication"], + networkConfiguration: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" + ], + endpointConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] + ).map((p) => ({ + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), + })), + }, + publicIPAddressConfiguration: !body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.poolInfo .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification.poolInfo + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body + .jobSpecification.poolInfo .autoPoolSpecification?.pool ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity ? undefined : { - resourceId: - p.identityReference?.["resourceId"], + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, }, - })), - environmentSettings: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity + maxTaskRetryCount: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" + ], + }, + certificateReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["certificateReferences"] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationLicenses"], + userAccounts: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["userAccounts"] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["metadata"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["mountConfiguration"] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration ? undefined : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - scope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], }, }, - maxTaskRetryCount: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["certificateReferences"] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationLicenses"], - userAccounts: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["userAccounts"] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["metadata"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["mountConfiguration"] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], + source: p.nfsMountConfiguration?.["source"], relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ + p.nfsMountConfiguration?.[ "relativeMountPath" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + cifsMountConfiguration: !p.cifsMountConfiguration ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], + username: + p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], relativeMountPath: - p.azureFileShareConfiguration?.[ + p.cifsMountConfiguration?.[ "relativeMountPath" ], mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], + p.cifsMountConfiguration?.["mountOptions"], + password: + p.cifsMountConfiguration?.["password"], }, - })), - targetNodeCommunicationMode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetNodeCommunicationMode"], - }, - }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetNodeCommunicationMode"], + }, + }, + }, + metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), }, - metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ + metadata: (body["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), }, - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); + }); } export async function _replaceJobScheduleDeserialize( @@ -11934,1010 +12150,1036 @@ export async function terminateJobSchedule( context, jobScheduleId, options - ); - return _terminateJobScheduleDeserialize(result); -} - -export function _createJobScheduleSend( - context: Client, - body: BatchJobScheduleCreateOptions, - options: CreateJobScheduleOptions = { requestOptions: {} } -): StreamableMethod< - CreateJobSchedule201Response | CreateJobScheduleDefaultResponse -> { - return context.path("/jobschedules").post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - schedule: { - doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), - doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), - startWindow: body.schedule["startWindow"], - recurrenceInterval: body.schedule["recurrenceInterval"], - }, - jobSpecification: { - priority: body.jobSpecification["priority"], - allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], - maxParallelTasks: body.jobSpecification["maxParallelTasks"], - displayName: body.jobSpecification["displayName"], - usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], - onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], - onTaskFailure: body.jobSpecification["onTaskFailure"], - networkConfiguration: !body.jobSpecification.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.networkConfiguration?.["subnetId"], - }, - constraints: !body.jobSpecification.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.constraints?.["maxWallClockTime"], - maxTaskRetryCount: - body.jobSpecification.constraints?.["maxTaskRetryCount"], - }, - jobManagerTask: !body.jobSpecification.jobManagerTask - ? undefined - : { - id: body.jobSpecification.jobManagerTask?.["id"], - displayName: - body.jobSpecification.jobManagerTask?.["displayName"], - commandLine: - body.jobSpecification.jobManagerTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobManagerTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobManagerTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.jobManagerTask?.containerSettings?.[ - "imageName" - ], - registry: !body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !body.jobSpecification - .jobManagerTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobManagerTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobManagerTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + ); + return _terminateJobScheduleDeserialize(result); +} + +export function _createJobScheduleSend( + context: Client, + body: BatchJobScheduleCreateOptions, + options: CreateJobScheduleOptions = { requestOptions: {} } +): StreamableMethod< + CreateJobSchedule201Response | CreateJobScheduleDefaultResponse +> { + return context + .path("/jobschedules") + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + schedule: { + doNotRunUntil: body.schedule["doNotRunUntil"]?.toISOString(), + doNotRunAfter: body.schedule["doNotRunAfter"]?.toISOString(), + startWindow: body.schedule["startWindow"], + recurrenceInterval: body.schedule["recurrenceInterval"], + }, + jobSpecification: { + priority: body.jobSpecification["priority"], + allowTaskPreemption: body.jobSpecification["allowTaskPreemption"], + maxParallelTasks: body.jobSpecification["maxParallelTasks"], + displayName: body.jobSpecification["displayName"], + usesTaskDependencies: body.jobSpecification["usesTaskDependencies"], + onAllTasksComplete: body.jobSpecification["onAllTasksComplete"], + onTaskFailure: body.jobSpecification["onTaskFailure"], + networkConfiguration: !body.jobSpecification.networkConfiguration + ? undefined + : { + subnetId: + body.jobSpecification.networkConfiguration?.["subnetId"], + }, + constraints: !body.jobSpecification.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.constraints?.["maxWallClockTime"], + maxTaskRetryCount: + body.jobSpecification.constraints?.["maxTaskRetryCount"], + }, + jobManagerTask: !body.jobSpecification.jobManagerTask + ? undefined + : { + id: body.jobSpecification.jobManagerTask?.["id"], + displayName: + body.jobSpecification.jobManagerTask?.["displayName"], + commandLine: + body.jobSpecification.jobManagerTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobManagerTask + ?.containerSettings ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: ( - body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] - ).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container + : { + containerRunOptions: + body.jobSpecification.jobManagerTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobManagerTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + .jobManagerTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobManagerTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobManagerTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobManagerTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container - ?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: ( - body.jobSpecification.jobManagerTask?.["environmentSettings"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobManagerTask?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobManagerTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobManagerTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - requiredSlots: - body.jobSpecification.jobManagerTask?.["requiredSlots"], - killJobOnCompletion: - body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], - userIdentity: !body.jobSpecification.jobManagerTask?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobManagerTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobManagerTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobManagerTask?.userIdentity - ?.autoUser?.["elevationLevel"], - }, - }, - runExclusive: - body.jobSpecification.jobManagerTask?.["runExclusive"], - applicationPackageReferences: ( - body.jobSpecification.jobManagerTask?.[ - "applicationPackageReferences" - ] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings - ? undefined - : { - access: - body.jobSpecification.jobManagerTask - ?.authenticationTokenSettings?.["access"], - }, - allowLowPriorityNode: - body.jobSpecification.jobManagerTask?.["allowLowPriorityNode"], - }, - jobPreparationTask: !body.jobSpecification.jobPreparationTask - ? undefined - : { - id: body.jobSpecification.jobPreparationTask?.["id"], - commandLine: - body.jobSpecification.jobPreparationTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobPreparationTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["containerRunOptions"], - imageName: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !body.jobSpecification - .jobPreparationTask?.containerSettings?.registry - ?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], - }, - }, - workingDirectory: - body.jobSpecification.jobPreparationTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? - [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobPreparationTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - constraints: !body.jobSpecification.jobPreparationTask - ?.constraints - ? undefined - : { - maxWallClockTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxWallClockTime" - ], - retentionTime: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "retentionTime" - ], - maxTaskRetryCount: - body.jobSpecification.jobPreparationTask?.constraints?.[ - "maxTaskRetryCount" - ], - }, - waitForSuccess: - body.jobSpecification.jobPreparationTask?.["waitForSuccess"], - userIdentity: !body.jobSpecification.jobPreparationTask - ?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobPreparationTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobPreparationTask - ?.userIdentity?.autoUser?.["elevationLevel"], - }, - }, - rerunOnNodeRebootAfterSuccess: - body.jobSpecification.jobPreparationTask?.[ - "rerunOnNodeRebootAfterSuccess" - ], - }, - jobReleaseTask: !body.jobSpecification.jobReleaseTask - ? undefined - : { - id: body.jobSpecification.jobReleaseTask?.["id"], - commandLine: - body.jobSpecification.jobReleaseTask?.["commandLine"], - containerSettings: !body.jobSpecification.jobReleaseTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.jobReleaseTask?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.jobReleaseTask?.containerSettings?.[ - "imageName" - ], - registry: !body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: ( + body.jobSpecification.jobManagerTask?.["outputFiles"] ?? [] + ).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined : { - username: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["username"], - password: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["password"], - registryServer: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry?.["registryServer"], - identityReference: !body.jobSpecification - .jobReleaseTask?.containerSettings?.registry + path: p.destination.container?.["path"], + containerUrl: + p.destination.container?.["containerUrl"], + identityReference: !p.destination.container ?.identityReference ? undefined : { resourceId: - body.jobSpecification.jobReleaseTask - ?.containerSettings?.registry - ?.identityReference?.["resourceId"], + p.destination.container?.identityReference?.[ + "resourceId" + ], }, - }, - workingDirectory: - body.jobSpecification.jobReleaseTask?.containerSettings?.[ - "workingDirectory" - ], - }, - resourceFiles: ( - body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - environmentSettings: ( - body.jobSpecification.jobReleaseTask?.["environmentSettings"] ?? - [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - maxWallClockTime: - body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], - retentionTime: - body.jobSpecification.jobReleaseTask?.["retentionTime"], - userIdentity: !body.jobSpecification.jobReleaseTask?.userIdentity - ? undefined - : { - username: - body.jobSpecification.jobReleaseTask?.userIdentity?.[ - "username" - ], - autoUser: !body.jobSpecification.jobReleaseTask - ?.userIdentity?.autoUser - ? undefined - : { - scope: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.jobReleaseTask?.userIdentity - ?.autoUser?.["elevationLevel"], + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), }, }, - }, - commonEnvironmentSettings: ( - body.jobSpecification["commonEnvironmentSettings"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - poolInfo: { - poolId: body.jobSpecification.poolInfo["poolId"], - autoPoolSpecification: !body.jobSpecification.poolInfo - .autoPoolSpecification + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], + }, + })), + environmentSettings: ( + body.jobSpecification.jobManagerTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobManagerTask?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobManagerTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobManagerTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + requiredSlots: + body.jobSpecification.jobManagerTask?.["requiredSlots"], + killJobOnCompletion: + body.jobSpecification.jobManagerTask?.["killJobOnCompletion"], + userIdentity: !body.jobSpecification.jobManagerTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobManagerTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobManagerTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobManagerTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + runExclusive: + body.jobSpecification.jobManagerTask?.["runExclusive"], + applicationPackageReferences: ( + body.jobSpecification.jobManagerTask?.[ + "applicationPackageReferences" + ] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.jobSpecification + .jobManagerTask?.authenticationTokenSettings + ? undefined + : { + access: + body.jobSpecification.jobManagerTask + ?.authenticationTokenSettings?.["access"], + }, + allowLowPriorityNode: + body.jobSpecification.jobManagerTask?.[ + "allowLowPriorityNode" + ], + }, + jobPreparationTask: !body.jobSpecification.jobPreparationTask ? undefined : { - autoPoolIdPrefix: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "autoPoolIdPrefix" - ], - poolLifetimeOption: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "poolLifetimeOption" - ], - keepAlive: - body.jobSpecification.poolInfo.autoPoolSpecification?.[ - "keepAlive" + id: body.jobSpecification.jobPreparationTask?.["id"], + commandLine: + body.jobSpecification.jobPreparationTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobPreparationTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + .jobPreparationTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: + body.jobSpecification.jobPreparationTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobPreparationTask?.["resourceFiles"] ?? + [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobPreparationTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + constraints: !body.jobSpecification.jobPreparationTask + ?.constraints + ? undefined + : { + maxWallClockTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxWallClockTime" + ], + retentionTime: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "retentionTime" + ], + maxTaskRetryCount: + body.jobSpecification.jobPreparationTask?.constraints?.[ + "maxTaskRetryCount" + ], + }, + waitForSuccess: + body.jobSpecification.jobPreparationTask?.["waitForSuccess"], + userIdentity: !body.jobSpecification.jobPreparationTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobPreparationTask + ?.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + rerunOnNodeRebootAfterSuccess: + body.jobSpecification.jobPreparationTask?.[ + "rerunOnNodeRebootAfterSuccess" ], - pool: !body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool + }, + jobReleaseTask: !body.jobSpecification.jobReleaseTask + ? undefined + : { + id: body.jobSpecification.jobReleaseTask?.["id"], + commandLine: + body.jobSpecification.jobReleaseTask?.["commandLine"], + containerSettings: !body.jobSpecification.jobReleaseTask + ?.containerSettings ? undefined : { - displayName: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["displayName"], - vmSize: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["vmSize"], - cloudServiceConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.cloudServiceConfiguration + containerRunOptions: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.["containerRunOptions"], + imageName: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry ? undefined : { - osFamily: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osFamily"], - osVersion: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.cloudServiceConfiguration?.["osVersion"], + username: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["username"], + password: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.["password"], + registryServer: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry?.[ + "registryServer" + ], + identityReference: !body.jobSpecification + .jobReleaseTask?.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, }, - virtualMachineConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration + workingDirectory: + body.jobSpecification.jobReleaseTask + ?.containerSettings?.["workingDirectory"], + }, + resourceFiles: ( + body.jobSpecification.jobReleaseTask?.["resourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + environmentSettings: ( + body.jobSpecification.jobReleaseTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + maxWallClockTime: + body.jobSpecification.jobReleaseTask?.["maxWallClockTime"], + retentionTime: + body.jobSpecification.jobReleaseTask?.["retentionTime"], + userIdentity: !body.jobSpecification.jobReleaseTask + ?.userIdentity + ? undefined + : { + username: + body.jobSpecification.jobReleaseTask?.userIdentity?.[ + "username" + ], + autoUser: !body.jobSpecification.jobReleaseTask + ?.userIdentity?.autoUser ? undefined : { - imageReference: { - publisher: + scope: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.jobReleaseTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, + }, + }, + commonEnvironmentSettings: ( + body.jobSpecification["commonEnvironmentSettings"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + poolInfo: { + poolId: body.jobSpecification.poolInfo["poolId"], + autoPoolSpecification: !body.jobSpecification.poolInfo + .autoPoolSpecification + ? undefined + : { + autoPoolIdPrefix: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "autoPoolIdPrefix" + ], + poolLifetimeOption: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "poolLifetimeOption" + ], + keepAlive: + body.jobSpecification.poolInfo.autoPoolSpecification?.[ + "keepAlive" + ], + pool: !body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool + ? undefined + : { + displayName: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["displayName"], + vmSize: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["vmSize"], + cloudServiceConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.cloudServiceConfiguration + ? undefined + : { + osFamily: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osFamily"], + osVersion: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.cloudServiceConfiguration?.["osVersion"], + }, + virtualMachineConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ? undefined + : { + imageReference: { + publisher: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["publisher"], + offer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["offer"], + sku: body.jobSpecification.poolInfo .autoPoolSpecification?.pool ?.virtualMachineConfiguration?.imageReference[ - "publisher" + "sku" ], - offer: + version: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["version"], + virtualMachineImageId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.imageReference["virtualMachineImageId"], + }, + nodeAgentSKUId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "nodeAgentSKUId" + ], + windowsConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration + ? undefined + : { + enableAutomaticUpdates: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.windowsConfiguration?.[ + "enableAutomaticUpdates" + ], + }, + dataDisks: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "dataDisks" + ] ?? [] + ).map((p) => ({ + lun: p["lun"], + caching: p["caching"], + diskSizeGB: p["diskSizeGB"], + storageAccountType: p["storageAccountType"], + })), + licenseType: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.[ + "licenseType" + ], + containerConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration + ? undefined + : { + type: body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.["type"], + containerImageNames: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerImageNames" + ], + containerRegistries: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.containerConfiguration?.[ + "containerRegistries" + ] ?? [] + ).map((p) => ({ + username: p["username"], + password: p["password"], + registryServer: p["registryServer"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.[ + "resourceId" + ], + }, + })), + }, + diskEncryptionConfiguration: !body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.virtualMachineConfiguration + ?.diskEncryptionConfiguration + ? undefined + : { + targets: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.diskEncryptionConfiguration?.[ + "targets" + ], + }, + nodePlacementConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration + ? undefined + : { + policy: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.nodePlacementConfiguration?.[ + "policy" + ], + }, + extensions: ( body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "offer" - ], - sku: body.jobSpecification.poolInfo + ?.virtualMachineConfiguration?.[ + "extensions" + ] ?? [] + ).map((p) => ({ + name: p["name"], + publisher: p["publisher"], + type: p["type"], + typeHandlerVersion: p["typeHandlerVersion"], + autoUpgradeMinorVersion: + p["autoUpgradeMinorVersion"], + enableAutomaticUpgrade: + p["enableAutomaticUpgrade"], + settings: p["settings"], + protectedSettings: p["protectedSettings"], + provisionAfterExtensions: + p["provisionAfterExtensions"], + })), + osDisk: !body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "sku" - ], - version: + ?.virtualMachineConfiguration?.osDisk + ? undefined + : { + ephemeralOSDiskSettings: !body + .jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration?.osDisk + ?.ephemeralOSDiskSettings + ? undefined + : { + placement: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.virtualMachineConfiguration + ?.osDisk + ?.ephemeralOSDiskSettings?.[ + "placement" + ], + }, + }, + }, + taskSlotsPerNode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["taskSlotsPerNode"], + taskSchedulingPolicy: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.taskSchedulingPolicy + ? undefined + : { + nodeFillType: body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "version" - ], - virtualMachineImageId: + ?.taskSchedulingPolicy?.["nodeFillType"], + }, + resizeTimeout: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["resizeTimeout"], + targetDedicatedNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetDedicatedNodes"], + targetLowPriorityNodes: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetLowPriorityNodes"], + enableAutoScale: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableAutoScale"], + autoScaleFormula: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleFormula"], + autoScaleEvaluationInterval: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["autoScaleEvaluationInterval"], + enableInterNodeCommunication: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["enableInterNodeCommunication"], + networkConfiguration: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.networkConfiguration + ? undefined + : { + subnetId: body.jobSpecification.poolInfo .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.imageReference[ - "virtualMachineImageId" + ?.networkConfiguration?.["subnetId"], + dynamicVNetAssignmentScope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "dynamicVNetAssignmentScope" ], - }, - nodeAgentSKUId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.[ - "nodeAgentSKUId" - ], - windowsConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration - ? undefined - : { - enableAutomaticUpdates: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.windowsConfiguration?.[ - "enableAutomaticUpdates" - ], - }, - dataDisks: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["dataDisks"] ?? - [] - ).map((p) => ({ - lun: p["lun"], - caching: p["caching"], - diskSizeGB: p["diskSizeGB"], - storageAccountType: p["storageAccountType"], - })), - licenseType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["licenseType"], - containerConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration - ? undefined - : { - type: body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.["type"], - containerImageNames: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerImageNames" - ], - containerRegistries: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.containerConfiguration?.[ - "containerRegistries" - ] ?? [] - ).map((p) => ({ - username: p["username"], - password: p["password"], - registryServer: p["registryServer"], - identityReference: !p.identityReference - ? undefined - : { - resourceId: - p.identityReference?.["resourceId"], - }, - })), - }, - diskEncryptionConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration - ? undefined - : { - targets: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.diskEncryptionConfiguration?.[ - "targets" - ], - }, - nodePlacementConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration - ? undefined - : { - policy: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.nodePlacementConfiguration?.["policy"], - }, - extensions: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.["extensions"] ?? - [] - ).map((p) => ({ - name: p["name"], - publisher: p["publisher"], - type: p["type"], - typeHandlerVersion: p["typeHandlerVersion"], - autoUpgradeMinorVersion: - p["autoUpgradeMinorVersion"], - enableAutomaticUpgrade: - p["enableAutomaticUpgrade"], - settings: p["settings"], - protectedSettings: p["protectedSettings"], - provisionAfterExtensions: - p["provisionAfterExtensions"], - })), - osDisk: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ? undefined - : { - ephemeralOSDiskSettings: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration?.osDisk - ?.ephemeralOSDiskSettings - ? undefined - : { - placement: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.virtualMachineConfiguration - ?.osDisk?.ephemeralOSDiskSettings?.[ - "placement" - ], - }, - }, - }, - taskSlotsPerNode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["taskSlotsPerNode"], - taskSchedulingPolicy: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.taskSchedulingPolicy - ? undefined - : { - nodeFillType: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.taskSchedulingPolicy?.["nodeFillType"], - }, - resizeTimeout: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["resizeTimeout"], - targetDedicatedNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetDedicatedNodes"], - targetLowPriorityNodes: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetLowPriorityNodes"], - enableAutoScale: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableAutoScale"], - autoScaleFormula: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleFormula"], - autoScaleEvaluationInterval: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["autoScaleEvaluationInterval"], - enableInterNodeCommunication: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["enableInterNodeCommunication"], - networkConfiguration: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.networkConfiguration - ? undefined - : { - subnetId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.["subnetId"], - dynamicVNetAssignmentScope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "dynamicVNetAssignmentScope" - ], - endpointConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration?.endpointConfiguration - ? undefined - : { - inboundNATPools: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.endpointConfiguration?.[ - "inboundNATPools" - ] ?? [] - ).map((p) => ({ - name: p["name"], - protocol: p["protocol"], - backendPort: p["backendPort"], - frontendPortRangeStart: - p["frontendPortRangeStart"], - frontendPortRangeEnd: - p["frontendPortRangeEnd"], - networkSecurityGroupRules: ( - p["networkSecurityGroupRules"] ?? [] + endpointConfiguration: !body.jobSpecification + .poolInfo.autoPoolSpecification?.pool + ?.networkConfiguration?.endpointConfiguration + ? undefined + : { + inboundNATPools: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.endpointConfiguration?.[ + "inboundNATPools" + ] ?? [] ).map((p) => ({ - priority: p["priority"], - access: p["access"], - sourceAddressPrefix: - p["sourceAddressPrefix"], - sourcePortRanges: p["sourcePortRanges"], + name: p["name"], + protocol: p["protocol"], + backendPort: p["backendPort"], + frontendPortRangeStart: + p["frontendPortRangeStart"], + frontendPortRangeEnd: + p["frontendPortRangeEnd"], + networkSecurityGroupRules: ( + p["networkSecurityGroupRules"] ?? [] + ).map((p) => ({ + priority: p["priority"], + access: p["access"], + sourceAddressPrefix: + p["sourceAddressPrefix"], + sourcePortRanges: p["sourcePortRanges"], + })), })), - })), - }, - publicIPAddressConfiguration: !body.jobSpecification - .poolInfo.autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration - ? undefined - : { - provision: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "provision" - ], - ipAddressIds: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration - ?.publicIPAddressConfiguration?.[ - "ipAddressIds" - ], - }, - enableAcceleratedNetworking: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.networkConfiguration?.[ - "enableAcceleratedNetworking" - ], - }, - startTask: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ? undefined - : { - commandLine: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "commandLine" - ], - containerSettings: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings - ? undefined - : { - containerRunOptions: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.[ - "containerRunOptions" - ], - imageName: - body.jobSpecification.poolInfo + }, + publicIPAddressConfiguration: !body + .jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.networkConfiguration + ?.publicIPAddressConfiguration + ? undefined + : { + provision: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "provision" + ], + ipAddressIds: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration + ?.publicIPAddressConfiguration?.[ + "ipAddressIds" + ], + }, + enableAcceleratedNetworking: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.networkConfiguration?.[ + "enableAcceleratedNetworking" + ], + }, + startTask: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ? undefined + : { + commandLine: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "commandLine" + ], + containerSettings: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings + ? undefined + : { + containerRunOptions: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "containerRunOptions" + ], + imageName: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.["imageName"], + registry: !body.jobSpecification.poolInfo .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["imageName"], - registry: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.registry - ? undefined - : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["username"], - password: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.["password"], - registryServer: - body.jobSpecification.poolInfo + ?.containerSettings?.registry + ? undefined + : { + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["username"], + password: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["password"], + registryServer: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.containerSettings + ?.registry?.["registryServer"], + identityReference: !body + .jobSpecification.poolInfo .autoPoolSpecification?.pool ?.startTask?.containerSettings - ?.registry?.["registryServer"], - identityReference: !body - .jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry?.identityReference - ? undefined - : { - resourceId: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.containerSettings - ?.registry - ?.identityReference?.[ - "resourceId" - ], - }, - }, - workingDirectory: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.containerSettings?.["workingDirectory"], - }, - resourceFiles: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "resourceFiles" - ] ?? [] - ).map((p) => ({ - autoStorageContainerName: - p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + ?.registry?.identityReference + ? undefined + : { + resourceId: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask + ?.containerSettings + ?.registry + ?.identityReference?.[ + "resourceId" + ], + }, + }, + workingDirectory: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.containerSettings?.[ + "workingDirectory" + ], + }, + resourceFiles: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "resourceFiles" + ] ?? [] + ).map((p) => ({ + autoStorageContainerName: + p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { + resourceId: + p.identityReference?.["resourceId"], + }, + })), + environmentSettings: ( + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "environmentSettings" + ] ?? [] + ).map((p) => ({ + name: p["name"], + value: p["value"], + })), + userIdentity: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity ? undefined : { - resourceId: - p.identityReference?.["resourceId"], + username: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.["username"], + autoUser: !body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask + ?.userIdentity?.autoUser + ? undefined + : { + scope: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["scope"], + elevationLevel: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool + ?.startTask?.userIdentity + ?.autoUser?.["elevationLevel"], + }, }, - })), - environmentSettings: ( - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "environmentSettings" - ] ?? [] - ).map((p) => ({ - name: p["name"], - value: p["value"], - })), - userIdentity: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity + maxTaskRetryCount: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "maxTaskRetryCount" + ], + waitForSuccess: + body.jobSpecification.poolInfo + .autoPoolSpecification?.pool?.startTask?.[ + "waitForSuccess" + ], + }, + certificateReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["certificateReferences"] ?? [] + ).map((p) => ({ + thumbprint: p["thumbprint"], + thumbprintAlgorithm: p["thumbprintAlgorithm"], + storeLocation: p["storeLocation"], + storeName: p["storeName"], + visibility: p["visibility"], + })), + applicationPackageReferences: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + applicationLicenses: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["applicationLicenses"], + userAccounts: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["userAccounts"] ?? [] + ).map((p) => ({ + name: p["name"], + password: p["password"], + elevationLevel: p["elevationLevel"], + linuxUserConfiguration: !p.linuxUserConfiguration + ? undefined + : { + uid: p.linuxUserConfiguration?.["uid"], + gid: p.linuxUserConfiguration?.["gid"], + sshPrivateKey: + p.linuxUserConfiguration?.["sshPrivateKey"], + }, + windowsUserConfiguration: !p.windowsUserConfiguration + ? undefined + : { + loginMode: + p.windowsUserConfiguration?.["loginMode"], + }, + })), + metadata: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["metadata"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), + mountConfiguration: ( + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["mountConfiguration"] ?? [] + ).map((p) => ({ + azureBlobFileSystemConfiguration: + !p.azureBlobFileSystemConfiguration ? undefined : { - username: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.["username"], - autoUser: !body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask - ?.userIdentity?.autoUser + accountName: + p.azureBlobFileSystemConfiguration?.[ + "accountName" + ], + containerName: + p.azureBlobFileSystemConfiguration?.[ + "containerName" + ], + accountKey: + p.azureBlobFileSystemConfiguration?.[ + "accountKey" + ], + sasKey: + p.azureBlobFileSystemConfiguration?.[ + "sasKey" + ], + blobfuseOptions: + p.azureBlobFileSystemConfiguration?.[ + "blobfuseOptions" + ], + relativeMountPath: + p.azureBlobFileSystemConfiguration?.[ + "relativeMountPath" + ], + identityReference: !p + .azureBlobFileSystemConfiguration + ?.identityReference ? undefined : { - scope: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["scope"], - elevationLevel: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool - ?.startTask?.userIdentity - ?.autoUser?.["elevationLevel"], + resourceId: + p.azureBlobFileSystemConfiguration + ?.identityReference?.["resourceId"], }, }, - maxTaskRetryCount: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "maxTaskRetryCount" - ], - waitForSuccess: - body.jobSpecification.poolInfo - .autoPoolSpecification?.pool?.startTask?.[ - "waitForSuccess" - ], - }, - certificateReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["certificateReferences"] ?? [] - ).map((p) => ({ - thumbprint: p["thumbprint"], - thumbprintAlgorithm: p["thumbprintAlgorithm"], - storeLocation: p["storeLocation"], - storeName: p["storeName"], - visibility: p["visibility"], - })), - applicationPackageReferences: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - applicationLicenses: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["applicationLicenses"], - userAccounts: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["userAccounts"] ?? [] - ).map((p) => ({ - name: p["name"], - password: p["password"], - elevationLevel: p["elevationLevel"], - linuxUserConfiguration: !p.linuxUserConfiguration - ? undefined - : { - uid: p.linuxUserConfiguration?.["uid"], - gid: p.linuxUserConfiguration?.["gid"], - sshPrivateKey: - p.linuxUserConfiguration?.["sshPrivateKey"], - }, - windowsUserConfiguration: !p.windowsUserConfiguration - ? undefined - : { - loginMode: - p.windowsUserConfiguration?.["loginMode"], - }, - })), - metadata: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["metadata"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - mountConfiguration: ( - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["mountConfiguration"] ?? [] - ).map((p) => ({ - azureBlobFileSystemConfiguration: - !p.azureBlobFileSystemConfiguration + nfsMountConfiguration: !p.nfsMountConfiguration ? undefined : { - accountName: - p.azureBlobFileSystemConfiguration?.[ - "accountName" - ], - containerName: - p.azureBlobFileSystemConfiguration?.[ - "containerName" - ], - accountKey: - p.azureBlobFileSystemConfiguration?.[ - "accountKey" - ], - sasKey: - p.azureBlobFileSystemConfiguration?.[ - "sasKey" - ], - blobfuseOptions: - p.azureBlobFileSystemConfiguration?.[ - "blobfuseOptions" - ], + source: p.nfsMountConfiguration?.["source"], relativeMountPath: - p.azureBlobFileSystemConfiguration?.[ + p.nfsMountConfiguration?.[ "relativeMountPath" ], - identityReference: !p - .azureBlobFileSystemConfiguration - ?.identityReference - ? undefined - : { - resourceId: - p.azureBlobFileSystemConfiguration - ?.identityReference?.["resourceId"], - }, + mountOptions: + p.nfsMountConfiguration?.["mountOptions"], }, - nfsMountConfiguration: !p.nfsMountConfiguration - ? undefined - : { - source: p.nfsMountConfiguration?.["source"], - relativeMountPath: - p.nfsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.nfsMountConfiguration?.["mountOptions"], - }, - cifsMountConfiguration: !p.cifsMountConfiguration - ? undefined - : { - username: p.cifsMountConfiguration?.["username"], - source: p.cifsMountConfiguration?.["source"], - relativeMountPath: - p.cifsMountConfiguration?.["relativeMountPath"], - mountOptions: - p.cifsMountConfiguration?.["mountOptions"], - password: p.cifsMountConfiguration?.["password"], - }, - azureFileShareConfiguration: - !p.azureFileShareConfiguration + cifsMountConfiguration: !p.cifsMountConfiguration ? undefined : { - accountName: - p.azureFileShareConfiguration?.[ - "accountName" - ], - azureFileUrl: - p.azureFileShareConfiguration?.[ - "azureFileUrl" - ], - accountKey: - p.azureFileShareConfiguration?.["accountKey"], + username: + p.cifsMountConfiguration?.["username"], + source: p.cifsMountConfiguration?.["source"], relativeMountPath: - p.azureFileShareConfiguration?.[ + p.cifsMountConfiguration?.[ "relativeMountPath" ], mountOptions: - p.azureFileShareConfiguration?.[ - "mountOptions" - ], + p.cifsMountConfiguration?.["mountOptions"], + password: + p.cifsMountConfiguration?.["password"], }, - })), - targetNodeCommunicationMode: - body.jobSpecification.poolInfo.autoPoolSpecification - ?.pool?.["targetNodeCommunicationMode"], - }, - }, + azureFileShareConfiguration: + !p.azureFileShareConfiguration + ? undefined + : { + accountName: + p.azureFileShareConfiguration?.[ + "accountName" + ], + azureFileUrl: + p.azureFileShareConfiguration?.[ + "azureFileUrl" + ], + accountKey: + p.azureFileShareConfiguration?.[ + "accountKey" + ], + relativeMountPath: + p.azureFileShareConfiguration?.[ + "relativeMountPath" + ], + mountOptions: + p.azureFileShareConfiguration?.[ + "mountOptions" + ], + }, + })), + targetNodeCommunicationMode: + body.jobSpecification.poolInfo.autoPoolSpecification + ?.pool?.["targetNodeCommunicationMode"], + }, + }, + }, + metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), }, - metadata: (body.jobSpecification["metadata"] ?? []).map((p) => ({ + metadata: (body["metadata"] ?? []).map((p) => ({ name: p["name"], value: p["value"], })), }, - metadata: (body["metadata"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - }, - }); + }); } export async function _createJobScheduleDeserialize( @@ -12966,16 +13208,18 @@ export function _listJobSchedulesSend( ): StreamableMethod< ListJobSchedules200Response | ListJobSchedulesDefaultResponse > { - return context.path("/jobschedules").get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context + .path("/jobschedules") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _listJobSchedulesDeserialize( @@ -14030,190 +14274,195 @@ export function _createTaskSend( body: BatchTaskCreateOptions, options: CreateTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks", jobId).post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - id: body["id"], - displayName: body["displayName"], - exitConditions: !body.exitConditions - ? undefined - : { - exitCodes: (body.exitConditions?.["exitCodes"] ?? []).map((p) => ({ - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - exitCodeRanges: (body.exitConditions?.["exitCodeRanges"] ?? []).map( - (p) => ({ + return context + .path("/jobs/{jobId}/tasks", jobId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + id: body["id"], + displayName: body["displayName"], + exitConditions: !body.exitConditions + ? undefined + : { + exitCodes: (body.exitConditions?.["exitCodes"] ?? []).map( + (p) => ({ + code: p["code"], + exitOptions: { + jobAction: p.exitOptions["jobAction"], + dependencyAction: p.exitOptions["dependencyAction"], + }, + }) + ), + exitCodeRanges: ( + body.exitConditions?.["exitCodeRanges"] ?? [] + ).map((p) => ({ start: p["start"], end: p["end"], exitOptions: { jobAction: p.exitOptions["jobAction"], dependencyAction: p.exitOptions["dependencyAction"], }, - }) - ), - preProcessingError: !body.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - body.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - body.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !body.exitConditions?.fileUploadError - ? undefined - : { - jobAction: - body.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - body.exitConditions?.fileUploadError?.["dependencyAction"], - }, - default: !body.exitConditions?.default - ? undefined - : { - jobAction: body.exitConditions?.default?.["jobAction"], - dependencyAction: - body.exitConditions?.default?.["dependencyAction"], - }, - }, - commandLine: body["commandLine"], - containerSettings: !body.containerSettings - ? undefined - : { - containerRunOptions: - body.containerSettings?.["containerRunOptions"], - imageName: body.containerSettings?.["imageName"], - registry: !body.containerSettings?.registry + })), + preProcessingError: !body.exitConditions?.preProcessingError + ? undefined + : { + jobAction: + body.exitConditions?.preProcessingError?.["jobAction"], + dependencyAction: + body.exitConditions?.preProcessingError?.[ + "dependencyAction" + ], + }, + fileUploadError: !body.exitConditions?.fileUploadError + ? undefined + : { + jobAction: + body.exitConditions?.fileUploadError?.["jobAction"], + dependencyAction: + body.exitConditions?.fileUploadError?.[ + "dependencyAction" + ], + }, + default: !body.exitConditions?.default + ? undefined + : { + jobAction: body.exitConditions?.default?.["jobAction"], + dependencyAction: + body.exitConditions?.default?.["dependencyAction"], + }, + }, + commandLine: body["commandLine"], + containerSettings: !body.containerSettings + ? undefined + : { + containerRunOptions: + body.containerSettings?.["containerRunOptions"], + imageName: body.containerSettings?.["imageName"], + registry: !body.containerSettings?.registry + ? undefined + : { + username: body.containerSettings?.registry?.["username"], + password: body.containerSettings?.registry?.["password"], + registryServer: + body.containerSettings?.registry?.["registryServer"], + identityReference: !body.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + body.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: body.containerSettings?.["workingDirectory"], + }, + resourceFiles: (body["resourceFiles"] ?? []).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: (body["outputFiles"] ?? []).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined : { - username: body.containerSettings?.registry?.["username"], - password: body.containerSettings?.registry?.["password"], - registryServer: - body.containerSettings?.registry?.["registryServer"], - identityReference: !body.containerSettings?.registry - ?.identityReference + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container?.identityReference ? undefined : { resourceId: - body.containerSettings?.registry?.identityReference?.[ + p.destination.container?.identityReference?.[ "resourceId" ], }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), }, - workingDirectory: body.containerSettings?.["workingDirectory"], - }, - resourceFiles: (body["resourceFiles"] ?? []).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: (body["outputFiles"] ?? []).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: (body["environmentSettings"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - affinityInfo: !body.affinityInfo - ? undefined - : { affinityId: body.affinityInfo?.["affinityId"] }, - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - retentionTime: body.constraints?.["retentionTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], }, - requiredSlots: body["requiredSlots"], - userIdentity: !body.userIdentity - ? undefined - : { - username: body.userIdentity?.["username"], - autoUser: !body.userIdentity?.autoUser - ? undefined - : { - scope: body.userIdentity?.autoUser?.["scope"], - elevationLevel: - body.userIdentity?.autoUser?.["elevationLevel"], - }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], }, - multiInstanceSettings: !body.multiInstanceSettings - ? undefined - : { - numberOfInstances: - body.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - body.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: ( - body.multiInstanceSettings?.["commonResourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + })), + environmentSettings: (body["environmentSettings"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + affinityInfo: !body.affinityInfo + ? undefined + : { affinityId: body.affinityInfo?.["affinityId"] }, + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + retentionTime: body.constraints?.["retentionTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: body["requiredSlots"], + userIdentity: !body.userIdentity + ? undefined + : { + username: body.userIdentity?.["username"], + autoUser: !body.userIdentity?.autoUser ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - dependsOn: !body.dependsOn - ? undefined - : { - taskIds: body.dependsOn?.["taskIds"], - taskIdRanges: (body.dependsOn?.["taskIdRanges"] ?? []).map((p) => ({ - start: p["start"], - end: p["end"], - })), - }, - applicationPackageReferences: ( - body["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], - })), - authenticationTokenSettings: !body.authenticationTokenSettings - ? undefined - : { access: body.authenticationTokenSettings?.["access"] }, - }, - }); + : { + scope: body.userIdentity?.autoUser?.["scope"], + elevationLevel: + body.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + multiInstanceSettings: !body.multiInstanceSettings + ? undefined + : { + numberOfInstances: + body.multiInstanceSettings?.["numberOfInstances"], + coordinationCommandLine: + body.multiInstanceSettings?.["coordinationCommandLine"], + commonResourceFiles: ( + body.multiInstanceSettings?.["commonResourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + dependsOn: !body.dependsOn + ? undefined + : { + taskIds: body.dependsOn?.["taskIds"], + taskIdRanges: (body.dependsOn?.["taskIdRanges"] ?? []).map( + (p) => ({ start: p["start"], end: p["end"] }) + ), + }, + applicationPackageReferences: ( + body["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !body.authenticationTokenSettings + ? undefined + : { access: body.authenticationTokenSettings?.["access"] }, + }, + }); } export async function _createTaskDeserialize( @@ -14246,16 +14495,18 @@ export function _listTasksSend( jobId: string, options: ListTasksOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks", jobId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context + .path("/jobs/{jobId}/tasks", jobId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _listTasksDeserialize( @@ -14552,189 +14803,194 @@ export function _createTaskCollectionSend( ): StreamableMethod< CreateTaskCollection200Response | CreateTaskCollectionDefaultResponse > { - return context.path("/jobs/{jobId}/addtaskcollection", jobId).post({ - ...operationOptionsToRequestParameters(options), - contentType: - (options.contentType as any) ?? "application/json; odata=minimalmetadata", - queryParameters: { timeOut: options?.timeOut }, - body: { - value: (collection["value"] ?? []).map((p) => ({ - id: p["id"], - displayName: p["displayName"], - exitConditions: !p.exitConditions - ? undefined - : { - exitCodes: (p.exitConditions?.["exitCodes"] ?? []).map((p) => ({ - code: p["code"], - exitOptions: { - jobAction: p.exitOptions["jobAction"], - dependencyAction: p.exitOptions["dependencyAction"], - }, - })), - exitCodeRanges: (p.exitConditions?.["exitCodeRanges"] ?? []).map( - (p) => ({ - start: p["start"], - end: p["end"], + return context + .path("/jobs/{jobId}/addtaskcollection", jobId) + .post({ + ...operationOptionsToRequestParameters(options), + contentType: + (options.contentType as any) ?? + "application/json; odata=minimalmetadata", + queryParameters: { timeOut: options?.timeOut }, + body: { + value: (collection["value"] ?? []).map((p) => ({ + id: p["id"], + displayName: p["displayName"], + exitConditions: !p.exitConditions + ? undefined + : { + exitCodes: (p.exitConditions?.["exitCodes"] ?? []).map((p) => ({ + code: p["code"], exitOptions: { jobAction: p.exitOptions["jobAction"], dependencyAction: p.exitOptions["dependencyAction"], }, - }) - ), - preProcessingError: !p.exitConditions?.preProcessingError - ? undefined - : { - jobAction: - p.exitConditions?.preProcessingError?.["jobAction"], - dependencyAction: - p.exitConditions?.preProcessingError?.[ - "dependencyAction" - ], - }, - fileUploadError: !p.exitConditions?.fileUploadError - ? undefined - : { - jobAction: p.exitConditions?.fileUploadError?.["jobAction"], - dependencyAction: - p.exitConditions?.fileUploadError?.["dependencyAction"], - }, - default: !p.exitConditions?.default - ? undefined - : { - jobAction: p.exitConditions?.default?.["jobAction"], - dependencyAction: - p.exitConditions?.default?.["dependencyAction"], + })), + exitCodeRanges: ( + p.exitConditions?.["exitCodeRanges"] ?? [] + ).map((p) => ({ + start: p["start"], + end: p["end"], + exitOptions: { + jobAction: p.exitOptions["jobAction"], + dependencyAction: p.exitOptions["dependencyAction"], }, - }, - commandLine: p["commandLine"], - containerSettings: !p.containerSettings - ? undefined - : { - containerRunOptions: p.containerSettings?.["containerRunOptions"], - imageName: p.containerSettings?.["imageName"], - registry: !p.containerSettings?.registry + })), + preProcessingError: !p.exitConditions?.preProcessingError + ? undefined + : { + jobAction: + p.exitConditions?.preProcessingError?.["jobAction"], + dependencyAction: + p.exitConditions?.preProcessingError?.[ + "dependencyAction" + ], + }, + fileUploadError: !p.exitConditions?.fileUploadError + ? undefined + : { + jobAction: + p.exitConditions?.fileUploadError?.["jobAction"], + dependencyAction: + p.exitConditions?.fileUploadError?.["dependencyAction"], + }, + default: !p.exitConditions?.default + ? undefined + : { + jobAction: p.exitConditions?.default?.["jobAction"], + dependencyAction: + p.exitConditions?.default?.["dependencyAction"], + }, + }, + commandLine: p["commandLine"], + containerSettings: !p.containerSettings + ? undefined + : { + containerRunOptions: + p.containerSettings?.["containerRunOptions"], + imageName: p.containerSettings?.["imageName"], + registry: !p.containerSettings?.registry + ? undefined + : { + username: p.containerSettings?.registry?.["username"], + password: p.containerSettings?.registry?.["password"], + registryServer: + p.containerSettings?.registry?.["registryServer"], + identityReference: !p.containerSettings?.registry + ?.identityReference + ? undefined + : { + resourceId: + p.containerSettings?.registry + ?.identityReference?.["resourceId"], + }, + }, + workingDirectory: p.containerSettings?.["workingDirectory"], + }, + resourceFiles: (p["resourceFiles"] ?? []).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + outputFiles: (p["outputFiles"] ?? []).map((p) => ({ + filePattern: p["filePattern"], + destination: { + container: !p.destination.container ? undefined : { - username: p.containerSettings?.registry?.["username"], - password: p.containerSettings?.registry?.["password"], - registryServer: - p.containerSettings?.registry?.["registryServer"], - identityReference: !p.containerSettings?.registry + path: p.destination.container?.["path"], + containerUrl: p.destination.container?.["containerUrl"], + identityReference: !p.destination.container ?.identityReference ? undefined : { resourceId: - p.containerSettings?.registry?.identityReference?.[ + p.destination.container?.identityReference?.[ "resourceId" ], }, + uploadHeaders: ( + p.destination.container?.["uploadHeaders"] ?? [] + ).map((p) => ({ name: p["name"], value: p["value"] })), }, - workingDirectory: p.containerSettings?.["workingDirectory"], - }, - resourceFiles: (p["resourceFiles"] ?? []).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference - ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - outputFiles: (p["outputFiles"] ?? []).map((p) => ({ - filePattern: p["filePattern"], - destination: { - container: !p.destination.container - ? undefined - : { - path: p.destination.container?.["path"], - containerUrl: p.destination.container?.["containerUrl"], - identityReference: !p.destination.container?.identityReference - ? undefined - : { - resourceId: - p.destination.container?.identityReference?.[ - "resourceId" - ], - }, - uploadHeaders: ( - p.destination.container?.["uploadHeaders"] ?? [] - ).map((p) => ({ name: p["name"], value: p["value"] })), - }, - }, - uploadOptions: { - uploadCondition: p.uploadOptions["uploadCondition"], - }, - })), - environmentSettings: (p["environmentSettings"] ?? []).map((p) => ({ - name: p["name"], - value: p["value"], - })), - affinityInfo: !p.affinityInfo - ? undefined - : { affinityId: p.affinityInfo?.["affinityId"] }, - constraints: !p.constraints - ? undefined - : { - maxWallClockTime: p.constraints?.["maxWallClockTime"], - retentionTime: p.constraints?.["retentionTime"], - maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], }, - requiredSlots: p["requiredSlots"], - userIdentity: !p.userIdentity - ? undefined - : { - username: p.userIdentity?.["username"], - autoUser: !p.userIdentity?.autoUser - ? undefined - : { - scope: p.userIdentity?.autoUser?.["scope"], - elevationLevel: - p.userIdentity?.autoUser?.["elevationLevel"], - }, + uploadOptions: { + uploadCondition: p.uploadOptions["uploadCondition"], }, - multiInstanceSettings: !p.multiInstanceSettings - ? undefined - : { - numberOfInstances: p.multiInstanceSettings?.["numberOfInstances"], - coordinationCommandLine: - p.multiInstanceSettings?.["coordinationCommandLine"], - commonResourceFiles: ( - p.multiInstanceSettings?.["commonResourceFiles"] ?? [] - ).map((p) => ({ - autoStorageContainerName: p["autoStorageContainerName"], - storageContainerUrl: p["storageContainerUrl"], - httpUrl: p["httpUrl"], - blobPrefix: p["blobPrefix"], - filePath: p["filePath"], - fileMode: p["fileMode"], - identityReference: !p.identityReference + })), + environmentSettings: (p["environmentSettings"] ?? []).map((p) => ({ + name: p["name"], + value: p["value"], + })), + affinityInfo: !p.affinityInfo + ? undefined + : { affinityId: p.affinityInfo?.["affinityId"] }, + constraints: !p.constraints + ? undefined + : { + maxWallClockTime: p.constraints?.["maxWallClockTime"], + retentionTime: p.constraints?.["retentionTime"], + maxTaskRetryCount: p.constraints?.["maxTaskRetryCount"], + }, + requiredSlots: p["requiredSlots"], + userIdentity: !p.userIdentity + ? undefined + : { + username: p.userIdentity?.["username"], + autoUser: !p.userIdentity?.autoUser ? undefined - : { resourceId: p.identityReference?.["resourceId"] }, - })), - }, - dependsOn: !p.dependsOn - ? undefined - : { - taskIds: p.dependsOn?.["taskIds"], - taskIdRanges: (p.dependsOn?.["taskIdRanges"] ?? []).map((p) => ({ - start: p["start"], - end: p["end"], - })), - }, - applicationPackageReferences: ( - p["applicationPackageReferences"] ?? [] - ).map((p) => ({ - applicationId: p["applicationId"], - version: p["version"], + : { + scope: p.userIdentity?.autoUser?.["scope"], + elevationLevel: + p.userIdentity?.autoUser?.["elevationLevel"], + }, + }, + multiInstanceSettings: !p.multiInstanceSettings + ? undefined + : { + numberOfInstances: + p.multiInstanceSettings?.["numberOfInstances"], + coordinationCommandLine: + p.multiInstanceSettings?.["coordinationCommandLine"], + commonResourceFiles: ( + p.multiInstanceSettings?.["commonResourceFiles"] ?? [] + ).map((p) => ({ + autoStorageContainerName: p["autoStorageContainerName"], + storageContainerUrl: p["storageContainerUrl"], + httpUrl: p["httpUrl"], + blobPrefix: p["blobPrefix"], + filePath: p["filePath"], + fileMode: p["fileMode"], + identityReference: !p.identityReference + ? undefined + : { resourceId: p.identityReference?.["resourceId"] }, + })), + }, + dependsOn: !p.dependsOn + ? undefined + : { + taskIds: p.dependsOn?.["taskIds"], + taskIdRanges: (p.dependsOn?.["taskIdRanges"] ?? []).map( + (p) => ({ start: p["start"], end: p["end"] }) + ), + }, + applicationPackageReferences: ( + p["applicationPackageReferences"] ?? [] + ).map((p) => ({ + applicationId: p["applicationId"], + version: p["version"], + })), + authenticationTokenSettings: !p.authenticationTokenSettings + ? undefined + : { access: p.authenticationTokenSettings?.["access"] }, })), - authenticationTokenSettings: !p.authenticationTokenSettings - ? undefined - : { access: p.authenticationTokenSettings?.["access"] }, - })), - }, - }); + }, + }); } export async function _createTaskCollectionDeserialize( @@ -14810,24 +15066,26 @@ export function _deleteTaskSend( taskId: string, options: DeleteTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).delete({ - ...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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - }); + return context + .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) + .delete({ + ...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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + }); } export async function _deleteTaskDeserialize( @@ -14863,28 +15121,30 @@ export function _getTaskSend( taskId: string, options: GetTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).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?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { - timeOut: options?.timeOut, - $select: options?.$select, - $expand: options?.$expand, - }, - }); + return context + .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) + .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?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { + timeOut: options?.timeOut, + $select: options?.$select, + $expand: options?.$expand, + }, + }); } export async function _getTaskDeserialize( @@ -15182,35 +15442,38 @@ export function _replaceTaskSend( body: BatchTask, options: ReplaceTaskOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId).put({ - ...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?.ifModifiedSince !== undefined - ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } - : {}), - ...(options?.ifUnmodifiedSince !== undefined - ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } - : {}), - }, - queryParameters: { timeOut: options?.timeOut }, - body: { - constraints: !body.constraints - ? undefined - : { - maxWallClockTime: body.constraints?.["maxWallClockTime"], - retentionTime: body.constraints?.["retentionTime"], - maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], - }, - }, - }); + return context + .path("/jobs/{jobId}/tasks/{taskId}", jobId, taskId) + .put({ + ...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?.ifModifiedSince !== undefined + ? { "if-modified-since": options?.ifModifiedSince?.toUTCString() } + : {}), + ...(options?.ifUnmodifiedSince !== undefined + ? { "if-unmodified-since": options?.ifUnmodifiedSince?.toUTCString() } + : {}), + }, + queryParameters: { timeOut: options?.timeOut }, + body: { + constraints: !body.constraints + ? undefined + : { + maxWallClockTime: body.constraints?.["maxWallClockTime"], + retentionTime: body.constraints?.["retentionTime"], + maxTaskRetryCount: body.constraints?.["maxTaskRetryCount"], + }, + }, + }); } export async function _replaceTaskDeserialize( @@ -15603,15 +15866,17 @@ export function _listTaskFilesSend( taskId: string, options: ListTaskFilesOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/jobs/{jobId}/tasks/{taskId}/files", jobId, taskId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - recursive: options?.recursive, - }, - }); + return context + .path("/jobs/{jobId}/tasks/{taskId}/files", jobId, taskId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + recursive: options?.recursive, + }, + }); } export async function _listTaskFilesDeserialize( @@ -15837,10 +16102,12 @@ export function _getNodeSend( nodeId: string, options: GetNodeOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, - }); + return context + .path("/pools/{poolId}/nodes/{nodeId}", poolId, nodeId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { timeOut: options?.timeOut, $select: options?.$select }, + }); } export async function _getNodeDeserialize( @@ -16475,15 +16742,17 @@ export function _listNodesSend( poolId: string, options: ListNodesOptions = { requestOptions: {} } ): StreamableMethod { - return context.path("/pools/{poolId}/nodes", poolId).get({ - ...operationOptionsToRequestParameters(options), - queryParameters: { - maxresults: options?.maxresults, - timeOut: options?.timeOut, - $filter: options?.$filter, - $select: options?.$select, - }, - }); + return context + .path("/pools/{poolId}/nodes", poolId) + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { + maxresults: options?.maxresults, + timeOut: options?.timeOut, + $filter: options?.$filter, + $select: options?.$select, + }, + }); } export async function _listNodesDeserialize( diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/paginateHelper.ts similarity index 94% rename from packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts rename to packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/paginateHelper.ts index 0d1e5efb7f..89e3390018 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelper.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/paginateHelper.ts @@ -12,9 +12,10 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; - -import { PageSettings, PagedAsyncIterableIterator } from "../models/index.js"; - +import { + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; /** * Helper type to extract the type of an array */ @@ -153,7 +154,8 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` ); } @@ -189,7 +191,7 @@ function checkPagingRequest(response: PathUncheckedResponse): void { */ function getPaginationProperties(initialResponse: PathUncheckedResponse) { // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); + const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); // Build a set with the passed custom set of itemNames const itemNames = new Set(["value", "items"]); @@ -219,9 +221,10 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames, - ].join(" OR ")}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 ff17438ca3..3d61a867f5 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 @@ -283,6 +283,6 @@ export { GetNodeFileOptions, GetNodeFilePropertiesOptions, ListNodeFilesOptions, - PagedAsyncIterableIterator, PageSettings, + PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts index 66e204e8d3..d4a4972ad5 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts @@ -285,5 +285,4 @@ export { GetNodeFilePropertiesOptions, ListNodeFilesOptions, } from "./options.js"; - -export { PagedAsyncIterableIterator, PageSettings } from "./pagings.js"; +export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 59efbb8d33..7eae21b82f 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -57,7 +57,7 @@ import { getClientName } from "@azure-tools/rlc-common"; import { buildPagingTypes, buildPaginateHelper as buildModularPaginateHelper -} from "./modular/buildPagingTypesAndHelper.js"; +} from "./modular/buildPagingFiles.js"; export * from "./lib.js"; diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 5dd4b0d869..640f405e3b 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -1,61 +1,330 @@ -import { RLCModel } from "@azure-tools/rlc-common"; -import { dirname, join as joinPath } from "path"; -import { promises } from "fs"; +import path from "path"; import { Client, ModularCodeModel } from "./modularCodeModel.js"; -import { fileURLToPath } from "url"; +import { + hasPagingOperation, + isPagingOperation +} from "./helpers/operationHelpers.js"; -export async function buildPagingUtils( - modularCodeModel: ModularCodeModel, - rlcCodeModels: RLCModel[] +export async function buildPagingTypes( + codeModel: ModularCodeModel, + client: Client ) { - const hasPaging = rlcCodeModels.some( - (codeModel) => codeModel.helperDetails?.hasPaging - ); - if (!hasPaging) { + if (!hasPagingOperation(client)) { return; } - const project = modularCodeModel.project; - const helperFile = "pagingUtil.ts"; - const baseTargetPath = modularCodeModel.modularOptions.sourceRoot; - const __filename = fileURLToPath(import.meta.url); - const __dirname = dirname(__filename); - const srcDir = joinPath( - __dirname, - "..", - "..", - "..", - "src", - "modular", - "static" - ); - const fileContent = await promises.readFile( - joinPath(srcDir, helperFile), - "utf-8" + const filePath = path.join( + codeModel.modularOptions.sourceRoot, + client.subfolder ?? "", + `models/pagingTypes.ts` ); - // TODO: Here to replace the itemNames and pageLink info - project.createSourceFile( - joinPath(baseTargetPath, "util", helperFile), - fileContent, - { - overwrite: true + const fileContent = codeModel.project.createSourceFile(filePath, undefined, { + overwrite: true + }); + fileContent.addStatements([ + ` + export interface PageSettings { + /** + * 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 = PageSettings + > { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; + } + ` + ]); -export async function buildPagingTypes( - _codeModel: ModularCodeModel, - _client: Client -) { - // const _hasPaging = rlcCodeModels.some( - // (codeModel) => codeModel.helperDetails?.hasPaging - // ); + return fileContent; } -export async function buildPagingHelper( - _codeModel: ModularCodeModel, - _client: Client +export async function buildPaginateHelper( + codeModel: ModularCodeModel, + client: Client ) { - // const _hasPaging = rlcCodeModels.some( - // (codeModel) => codeModel.helperDetails?.hasPaging - // ); + const pagingOperstions = client.operationGroups + .flatMap((op) => op.operations) + .filter(isPagingOperation); + if (!pagingOperstions || pagingOperstions.length === 0) { + return; + } + // prepare custom nextLinkNames and itemNames + const nextLinkNames = new Set(["nextLink"]); + const itemNames = new Set(["value", "items"]); + for (const op of pagingOperstions) { + if (op.continuationTokenName) { + nextLinkNames.add(op.continuationTokenName); + } + if (op.itemName) { + itemNames.add(op.itemName); + } + } + const nextLinkNamesStr = [...nextLinkNames] + .map((name) => `"${name}"`) + .join(", "); + const itemNamesStr = [...itemNames].map((name) => `"${name}"`).join(", "); + const pagingTypesPath = `../models/pagingTypes.js`; + const filePath = path.join( + codeModel.modularOptions.sourceRoot, + client.subfolder ?? "", + `api/paginateHelper.ts` + ); + + const fileContent = codeModel.project.createSourceFile(filePath, undefined, { + overwrite: true + }); + + fileContent.addStatements([ + ` + import { + getPagedAsyncIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, + PagedResult, + PageSettings as CorePageSettings + } from "@azure/core-paging"; + import { + Client, + createRestError, + PathUncheckedResponse + } from "@azure-rest/core-client"; + import { PageSettings, PagedAsyncIterableIterator } from "${pagingTypesPath}"; + + export interface PageInfo { + continuationToken?: string; + } + + /** + * Helper type to extract the type of an array + */ + export type GetArrayType = T extends Array ? TData : never; + + /** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is \`value\`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ + export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + + export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse + >( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: (result: TResponse) => Promise, + sendFunctionArgs: any[] = [] + ): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string) => { + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + return { + page: values, + nextPageLink: nextLink + }; + }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken + }) as any; + } + }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); + + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + } + }; + } + + async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} + ): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + } + } + + /** + * 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") { + throw new Error( + \`Body Property \${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + \`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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226" + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + \`Pagination failed with unexpected statusCode \${response.status}\`, + response + ); + } + } + + /** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ + function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set([${nextLinkNamesStr}]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set([${itemNamesStr}]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + \`Couldn't paginate response\n Body doesn't contain an array property with name: \${[ + ...itemNames + ].join(" OR ")}\` + ); + } + + return { itemName, nextLinkName }; + } + ` + ]); } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index fb0d8fa3ad..1890099a6c 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -6,6 +6,7 @@ import { import { toPascalCase } from "../../utils/casingUtils.js"; import { BodyParameter, + Client, ModularCodeModel, Operation, Parameter, @@ -1062,24 +1063,37 @@ function needsDeserialize(type?: Type) { export function hasLROOperation(codeModel: ModularCodeModel) { return (codeModel.clients ?? []).some((c) => (c.operationGroups ?? []).some((og) => - (og.operations ?? []).some( - (op) => op.discriminator === "lro" || op.discriminator === "lropaging" - ) + (og.operations ?? []).some(isPagingOperation) ) ); } -export function hasPagingOperation(codeModel: ModularCodeModel) { - return (codeModel.clients ?? []).some((c) => +export function isLROOperation(op: Operation): boolean { + return op.discriminator === "lro" || op.discriminator === "lropaging"; +} + +export function hasPagingOperation(client: Client): boolean; +export function hasPagingOperation(codeModel: ModularCodeModel): boolean; +export function hasPagingOperation( + clientOrCodeModel: Client | ModularCodeModel +): 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) => (c.operationGroups ?? []).some((og) => - (og.operations ?? []).some( - (op) => - op.discriminator === "paging" || op.discriminator === "lropaging" - ) + (og.operations ?? []).some(isPagingOperation) ) ); } +export function isPagingOperation(op: Operation): boolean { + return op.discriminator === "paging" || op.discriminator === "lropaging"; +} + function getAllProperties(type: Type): Property[] { const propertiesMap: Map = new Map(); if (!type) { diff --git a/packages/typespec-ts/src/modular/static/pagingHelpers.ts b/packages/typespec-ts/src/modular/static/pagingHelpers.ts deleted file mode 100644 index 1ffff07c6c..0000000000 --- a/packages/typespec-ts/src/modular/static/pagingHelpers.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings -} from "@azure/core-paging"; -import { - Client, - createRestError, - PathUncheckedResponse -} from "@azure-rest/core-client"; -import { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; - -export interface PageInfo { - continuationToken?: string; -} - -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; - -export function buildPagedAsyncIterator< - TElement, - TResponse extends PathUncheckedResponse = PathUncheckedResponse ->( - client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] -): PagedAsyncIterableIterator { - let firstRun = true; - let itemName: string, nextLinkName: string | undefined; - const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { - const result = - firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) - : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; - checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); - const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); - return { - page: values, - nextPageLink: nextLink - }; - }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken - }) as any; - } - }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); - - return { - next() { - return iter.next(); - }, - [Symbol.asyncIterator]() { - return this; - }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - } - }; -} - -async function* getPageAsyncIterator( - pagedResult: PagedResult, - options: { - pageLink?: string; - } = {} -): AsyncIterableIterator { - const { pageLink } = options; - let response = await pagedResult.getPage( - pageLink ?? pagedResult.firstPageLink - ); - if (!response) { - return; - } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; - while (response.nextPageLink) { - response = await pagedResult.getPage(response.nextPageLink); - if (!response) { - return; - } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; - } -} - -/** - * 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") { - throw new Error( - `Body Property ${nextLinkName} should be a string or 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[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn - if (!Array.isArray(value)) { - throw new Error( - `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): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226" - ]; - if (!Http2xxStatusCodes.includes(response.status)) { - throw createRestError( - `Pagination failed with unexpected statusCode ${response.status}`, - response - ); - } -} - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames - ].join(" OR ")}` - ); - } - - return { itemName, nextLinkName }; -} diff --git a/packages/typespec-ts/src/modular/static/pagingTypes.ts b/packages/typespec-ts/src/modular/static/pagingTypes.ts deleted file mode 100644 index 9d1d61320d..0000000000 --- a/packages/typespec-ts/src/modular/static/pagingTypes.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -export interface PageSettings { - /** - * 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 = PageSettings -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings - ) => AsyncIterableIterator; -} From a9c5b48c858ca0c342daa7f938b4f721528a020d Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 20:26:52 +0800 Subject: [PATCH 22/60] Update the codegen --- .../generated/typespec-ts/src/BatchClient.ts | 2 +- .../generated/typespec-ts/src/api/index.ts | 2 +- .../typespec-ts/src/api/operations.ts | 6 +- .../{paginateHelper.ts => pagingHelpers.ts} | 0 packages/typespec-ts/src/index.ts | 2 +- .../src/modular/buildClassicalClient.ts | 15 +++++ .../src/modular/buildOperations.ts | 65 ++++++++++++++----- .../src/modular/buildPagingFiles.ts | 4 +- 8 files changed, 72 insertions(+), 24 deletions(-) rename packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/{paginateHelper.ts => pagingHelpers.ts} (100%) 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 a58a644ac3..5835c32668 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 @@ -123,6 +123,7 @@ import { GetNodeFilePropertiesOptions, ListNodeFilesOptions, } from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createBatch, BatchClientOptions, @@ -204,7 +205,6 @@ import { getNodeFileProperties, listNodeFiles, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "@azure/core-paging"; export { BatchClientOptions } from "./api/BatchContext.js"; 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 a2efb424a3..2cde7c284f 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 @@ -88,4 +88,4 @@ export { buildPagedAsyncIterator, GetArrayType, PaginateReturn, -} from "./paginateHelper.js"; +} from "./pagingHelpers.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 6130410ad6..d19fbeb114 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 @@ -56,6 +56,8 @@ import { NodeVMExtension, NodeVMExtensionList, } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "../api/pagingTypes.js"; import { isUnexpected, BatchContext as Client, @@ -219,10 +221,6 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString, stringToUint8Array } from "@azure/core-util"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../util/pagingUtil.js"; import { ListApplicationsOptions, GetApplicationOptions, diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/paginateHelper.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts similarity index 100% rename from packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/paginateHelper.ts rename to packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 7eae21b82f..53036ce941 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -56,7 +56,7 @@ import { ModularCodeModel } from "./modular/modularCodeModel.js"; import { getClientName } from "@azure-tools/rlc-common"; import { buildPagingTypes, - buildPaginateHelper as buildModularPaginateHelper + buildPagingHelpers as buildModularPaginateHelper } from "./modular/buildPagingFiles.js"; export * from "./lib.js"; diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index 246944a13b..8414668e1c 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -176,6 +176,21 @@ function importAllModels( moduleSpecifier: `./models/options.js`, namedImports: exportedOptions }); + + const pagingTypes = project.getSourceFile( + `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}models/pagingTypes.ts` + ); + + if (!pagingTypes) { + return; + } + + const exportedPaingTypes = [...pagingTypes.getExportedDeclarations().keys()]; + + clientFile.addImportDeclaration({ + moduleSpecifier: `./models/pagingTypes.js`, + namedImports: exportedPaingTypes + }); } function importPipeline( diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index 440e061bea..fea2b64154 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -5,8 +5,7 @@ import { getOperationFunction, getSendPrivateFunction, getDeserializePrivateFunction, - getOperationOptionsName, - hasPagingOperation + getOperationOptionsName } from "./helpers/operationHelpers.js"; import { Client, ModularCodeModel, Operation } from "./modularCodeModel.js"; import { isRLCMultiEndpoint } from "../utils/clientUtils.js"; @@ -57,6 +56,15 @@ export function buildOperationFiles( operationGroup.namespaceHierarchies.length ); + // We need to import the paging helpers and types explicitly because ts-morph may not be able to find them. + importPagingDependencies( + srcPath, + operationGroupFile, + codeModel.project, + subfolder, + operationGroup.namespaceHierarchies.length + ); + const namedImports: string[] = []; let clientType = "Client"; if (isRLCMultiEndpoint(dpgContext)) { @@ -135,19 +143,6 @@ export function buildOperationFiles( ]); } } - if (hasPagingOperation(codeModel)) { - operationGroupFile.addImportDeclarations([ - { - moduleSpecifier: `${ - subfolder && subfolder !== "" ? "../" : "" - }../util/pagingUtil.js`, - namedImports: [ - "PagedAsyncIterableIterator", - "buildPagedAsyncIterator" - ] - } - ]); - } operationGroupFile.fixMissingImports(); // have to fixUnusedIdentifiers after everything get generated. operationGroupFile.fixUnusedIdentifiers(); @@ -189,6 +184,46 @@ export function importModels( // sourceFile.fixUnusedIdentifiers(); } +function importPagingDependencies( + srcPath: string, + sourceFile: SourceFile, + project: Project, + subfolder: string = "", + importLayer: number = 0 +) { + const pagingTypes = project.getSourceFile( + `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}models/pagingTypes.ts` + ); + + if (!pagingTypes) { + return; + } + + const exportedPaingTypes = [...pagingTypes.getExportedDeclarations().keys()]; + + sourceFile.addImportDeclaration({ + moduleSpecifier: `${"../".repeat(importLayer + 1)}models/pagingTypes.js`, + namedImports: exportedPaingTypes + }); + + const pagingHelper = project.getSourceFile( + `${srcPath}/${subfolder !== "" ? subfolder + "/" : ""}api/pagingHelpers.ts` + ); + + if (!pagingHelper) { + return; + } + + const exportedPaingHelpers = [ + ...pagingHelper.getExportedDeclarations().keys() + ]; + + sourceFile.addImportDeclaration({ + moduleSpecifier: `${"../".repeat(importLayer + 1)}api/pagingTypes.js`, + namedImports: exportedPaingHelpers + }); +} + /** * This function generates the interfaces for each operation options */ diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 640f405e3b..a48870e873 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -58,7 +58,7 @@ export async function buildPagingTypes( return fileContent; } -export async function buildPaginateHelper( +export async function buildPagingHelpers( codeModel: ModularCodeModel, client: Client ) { @@ -87,7 +87,7 @@ export async function buildPaginateHelper( const filePath = path.join( codeModel.modularOptions.sourceRoot, client.subfolder ?? "", - `api/paginateHelper.ts` + `api/pagingHelpers.ts` ); const fileContent = codeModel.project.createSourceFile(filePath, undefined, { From ea4b6aa08a94ccbcd78118bb53cf6fad52674cf8 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 21:50:08 +0800 Subject: [PATCH 23/60] Re-generate the batch modular --- .../generated/typespec-ts/review/batch.api.md | 44 ++++++++++++------- .../generated/typespec-ts/src/api/index.ts | 5 --- .../typespec-ts/src/api/operations.ts | 2 +- .../src/modular/buildOperations.ts | 4 +- .../src/modular/buildSubpathIndex.ts | 5 +++ 5 files changed, 38 insertions(+), 22 deletions(-) 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 c9b29c3c49..afc86c02e8 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 @@ -161,22 +161,22 @@ export class BatchClient { getTaskFile(jobId: string, taskId: string, filePath: string, options?: GetTaskFileOptions): Promise; getTaskFileProperties(jobId: string, taskId: string, filePath: string, options?: GetTaskFilePropertiesOptions): Promise; jobScheduleExists(jobScheduleId: string, options?: JobScheduleExistsOptions): Promise; - listApplications(options?: ListApplicationsOptions): Promise; - listCertificates(options?: ListCertificatesOptions): Promise; - listJobPreparationAndReleaseTaskStatus(jobId: string, options?: ListJobPreparationAndReleaseTaskStatusOptions): Promise; - listJobs(options?: ListJobsOptions): Promise; - listJobSchedules(options?: ListJobSchedulesOptions): Promise; - listJobsFromSchedule(jobScheduleId: string, options?: ListJobsFromScheduleOptions): Promise; - listNodeExtensions(poolId: string, nodeId: string, options?: ListNodeExtensionsOptions): Promise; - listNodeFiles(poolId: string, nodeId: string, options?: ListNodeFilesOptions): Promise; - listNodes(poolId: string, options?: ListNodesOptions): Promise; - listPoolNodeCounts(options?: ListPoolNodeCountsOptions): Promise; - listPools(options?: ListPoolsOptions): Promise; - listPoolUsageMetrics(options?: ListPoolUsageMetricsOptions): Promise; + listApplications(options?: ListApplicationsOptions): PagedAsyncIterableIterator; + listCertificates(options?: ListCertificatesOptions): PagedAsyncIterableIterator; + listJobPreparationAndReleaseTaskStatus(jobId: string, options?: ListJobPreparationAndReleaseTaskStatusOptions): PagedAsyncIterableIterator; + listJobs(options?: ListJobsOptions): PagedAsyncIterableIterator; + listJobSchedules(options?: ListJobSchedulesOptions): PagedAsyncIterableIterator; + listJobsFromSchedule(jobScheduleId: string, options?: ListJobsFromScheduleOptions): PagedAsyncIterableIterator; + listNodeExtensions(poolId: string, nodeId: string, options?: ListNodeExtensionsOptions): PagedAsyncIterableIterator; + listNodeFiles(poolId: string, nodeId: string, options?: ListNodeFilesOptions): PagedAsyncIterableIterator; + listNodes(poolId: string, options?: ListNodesOptions): PagedAsyncIterableIterator; + listPoolNodeCounts(options?: ListPoolNodeCountsOptions): PagedAsyncIterableIterator; + listPools(options?: ListPoolsOptions): PagedAsyncIterableIterator; + listPoolUsageMetrics(options?: ListPoolUsageMetricsOptions): PagedAsyncIterableIterator; listSubTasks(jobId: string, taskId: string, options?: ListSubTasksOptions): Promise; - listSupportedImages(options?: ListSupportedImagesOptions): Promise; - listTaskFiles(jobId: string, taskId: string, options?: ListTaskFilesOptions): Promise; - listTasks(jobId: string, options?: ListTasksOptions): Promise; + listSupportedImages(options?: ListSupportedImagesOptions): PagedAsyncIterableIterator; + listTaskFiles(jobId: string, taskId: string, options?: ListTaskFilesOptions): PagedAsyncIterableIterator; + listTasks(jobId: string, options?: ListTasksOptions): PagedAsyncIterableIterator; readonly pipeline: Pipeline; poolExists(poolId: string, options?: PoolExistsOptions): Promise; reactivateTask(jobId: string, taskId: string, options?: ReactivateTaskOptions): Promise; @@ -1645,6 +1645,20 @@ export interface OutputFileUploadOptions { uploadCondition: OutputFileUploadCondition; } +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + +// @public (undocumented) +export interface PageSettings { + continuationToken?: string; +} + // @public export interface PoolEndpointConfiguration { inboundNATPools: InboundNATPool[]; 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 2cde7c284f..cfc770d76f 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 @@ -84,8 +84,3 @@ export { getNodeFileProperties, listNodeFiles, } from "./operations.js"; -export { - buildPagedAsyncIterator, - GetArrayType, - PaginateReturn, -} from "./pagingHelpers.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 d19fbeb114..ed8ab82c48 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 @@ -57,7 +57,7 @@ import { NodeVMExtensionList, } from "../models/models.js"; import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; -import { buildPagedAsyncIterator } from "../api/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, BatchContext as Client, diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index fea2b64154..1838cec085 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -219,7 +219,9 @@ function importPagingDependencies( ]; sourceFile.addImportDeclaration({ - moduleSpecifier: `${"../".repeat(importLayer + 1)}api/pagingTypes.js`, + moduleSpecifier: `${ + importLayer === 0 ? "./" : "../".repeat(importLayer) + }pagingHelpers.js`, namedImports: exportedPaingHelpers }); } diff --git a/packages/typespec-ts/src/modular/buildSubpathIndex.ts b/packages/typespec-ts/src/modular/buildSubpathIndex.ts index dc85ac0d62..3de96c12af 100644 --- a/packages/typespec-ts/src/modular/buildSubpathIndex.ts +++ b/packages/typespec-ts/src/modular/buildSubpathIndex.ts @@ -32,6 +32,11 @@ export function buildSubpathIndexFile( if (!options.exportIndex && file.getFilePath().endsWith("index.ts")) { continue; } + // Skip to export pagingHelpers.ts + // pagingHelpers.ts is a file that is used internally and is not exported. + if (file.getFilePath().endsWith("pagingHelpers.ts")) { + continue; + } if (file.getFilePath() === indexFile.getFilePath()) { continue; } From a10c6d311403e862939df3db072c0bfe649aa3cf Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 21:59:03 +0800 Subject: [PATCH 24/60] Re-generate the integration testings --- .../generated/typespec-ts/package.json | 2 - .../src/modular/helpers/operationHelpers.ts | 2 +- .../generated/azure/core/src/BasicClient.ts | 3 +- .../azure/core/src/api/operations.ts | 6 +-- .../pagingUtil.ts => api/pagingHelpers.ts} | 45 +++++-------------- .../generated/azure/core/src/index.ts | 2 + .../generated/azure/core/src/models/index.ts | 1 + .../azure/core/src/models/pagingTypes.ts | 33 ++++++++++++++ .../payload/pageable/src/PageableClient.ts | 6 ++- .../payload/pageable/src/api/operations.ts | 6 +-- .../pagingUtil.ts => api/pagingHelpers.ts} | 45 +++++-------------- .../generated/payload/pageable/src/index.ts | 8 +++- .../payload/pageable/src/models/index.ts | 1 + .../pageable/src/models/pagingTypes.ts | 33 ++++++++++++++ 14 files changed, 109 insertions(+), 84 deletions(-) rename packages/typespec-ts/test/modularIntegration/generated/azure/core/src/{util/pagingUtil.ts => api/pagingHelpers.ts} (85%) create mode 100644 packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts rename packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/{util/pagingUtil.ts => api/pagingHelpers.ts} (85%) create mode 100644 packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json b/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json index 9630571769..f0bce94891 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/package.json @@ -73,8 +73,6 @@ "@azure/logger": "^1.0.0", "tslib": "^2.2.0", "@azure/core-paging": "^1.5.0", - "@azure/core-lro": "^2.5.4", - "@azure/abort-controller": "^1.0.0", "@azure/core-util": "^1.4.0" }, "devDependencies": { diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 1890099a6c..0fdfbac414 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -1063,7 +1063,7 @@ function needsDeserialize(type?: Type) { export function hasLROOperation(codeModel: ModularCodeModel) { return (codeModel.clients ?? []).some((c) => (c.operationGroups ?? []).some((og) => - (og.operations ?? []).some(isPagingOperation) + (og.operations ?? []).some(isLROOperation) ) ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts index af667c3809..9adf4d0ac9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { Pipeline } from "@azure/core-rest-pipeline"; import { User } from "./models/models.js"; import { CreateOrUpdateOptions, @@ -12,6 +13,7 @@ import { DeleteOperationOptions, ExportOperationOptions, } from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createBasic, BasicClientOptions, @@ -25,7 +27,6 @@ import { deleteOperation, exportOperation, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; export { BasicClientOptions } from "./api/BasicContext.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 64be3e7192..f060121080 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -2,6 +2,8 @@ // Licensed under the MIT license. import { User, UserListResults, PagedUser } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, BasicContext as Client, @@ -29,10 +31,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../util/pagingUtil.js"; import { CreateOrUpdateOptions, CreateOrReplaceOptions, diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts similarity index 85% rename from packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts rename to packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index e7221e3e53..01fbf65b80 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -12,6 +12,10 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; /** * Helper type to extract the type of an array */ @@ -34,37 +38,6 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; -export interface PageSettings { - /** - * 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 = PageSettings -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings - ) => AsyncIterableIterator; -} - export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -181,7 +154,8 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` ); } @@ -247,9 +221,10 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames, - ].join(" OR ")}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts index 7829aaa4d2..52294d174d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts @@ -15,4 +15,6 @@ export { ListWithCustomPageModelOptions, DeleteOperationOptions, ExportOperationOptions, + PageSettings, + PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts index a79ba0eeb3..ad548f65f5 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts @@ -12,3 +12,4 @@ export { DeleteOperationOptions, ExportOperationOptions, } from "./options.js"; +export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts index 9ea532f28f..8ed100b9f7 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/PageableClient.ts @@ -1,24 +1,28 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +import { Pipeline } from "@azure/core-rest-pipeline"; import { User } from "./models/models.js"; import { ListOptions } from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { list, createPageable, PageableClientOptions, PageableContext, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; export { PageableClientOptions } from "./api/PageableContext.js"; export class PageableClient { private _client: PageableContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; /** Test describing pageable. */ constructor(options: PageableClientOptions = {}) { this._client = createPageable(options); + this.pipeline = this._client.pipeline; } /** List users */ diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts index 21713f06fc..9703f39824 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts @@ -2,15 +2,13 @@ // Licensed under the MIT license. import { PagedUser, User } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { List200Response, PageableContext as Client } from "../rest/index.js"; import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../util/pagingUtil.js"; import { ListOptions } from "../models/options.js"; export function _listSend( diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts similarity index 85% rename from packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts rename to packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index e7221e3e53..01fbf65b80 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/util/pagingUtil.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -12,6 +12,10 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; /** * Helper type to extract the type of an array */ @@ -34,37 +38,6 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; -export interface PageSettings { - /** - * 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 = PageSettings -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings - ) => AsyncIterableIterator; -} - export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -181,7 +154,8 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` ); } @@ -247,9 +221,10 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames, - ].join(" OR ")}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts index 61faa1ac7b..257d09fd2f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts @@ -2,4 +2,10 @@ // Licensed under the MIT license. export { PageableClient, PageableClientOptions } from "./PageableClient.js"; -export { PagedUser, User, ListOptions } from "./models/index.js"; +export { + PagedUser, + User, + ListOptions, + PageSettings, + PagedAsyncIterableIterator, +} from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts index ade0de25f2..332c7bf5e5 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts @@ -3,3 +3,4 @@ export { PagedUser, User } from "./models.js"; export { ListOptions } from "./options.js"; +export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} From e6c9c53149ddaabaa4cd5fc0748a2f3f303e0e17 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 22:22:57 +0800 Subject: [PATCH 25/60] Update the integrate for paging --- .../test/modularIntegration/azureCore.spec.ts | 39 ++++++++++++++----- ...geable.spec.ts => payloadPageable.spec.ts} | 16 +------- 2 files changed, 32 insertions(+), 23 deletions(-) rename packages/typespec-ts/test/modularIntegration/{pageable.spec.ts => payloadPageable.spec.ts} (85%) diff --git a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts index 19acd0bb03..63a410d2fa 100644 --- a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts @@ -71,15 +71,8 @@ describe("BasicClient Classical Client", () => { }); const pagedIter = iter.byPage({ maxPageSize: 10 } as any); - try { - const items: User[] = (await pagedIter.next()).value; - assert.strictEqual(items.length, 2); - } catch (err: any) { - assert.strictEqual( - err.message, - "maxPageSize is not supported by this operation." - ); - } + const items: User[] = (await pagedIter.next()).value; + assert.strictEqual(items.length, 2); }); it("should get users by continuationToken", async () => { @@ -101,4 +94,32 @@ describe("BasicClient Classical Client", () => { }); }); }); + + it("should get a user", async () => { + const user = await client.get(1); + assert.strictEqual(user?.name, "Madge"); + assert.strictEqual(user?.etag, "11bdc430-65e8-45ad-81d9-8ffa60d55b59"); + }); + + it("should list with custom page model", async () => { + const customPageIter = await client.listWithCustomPageModel(); + const items = []; + for await (const user of customPageIter) { + items.push(user); + } + assert.strictEqual(items.length, 1); + assert.strictEqual(items[0]?.name, "Madge"); + assert.strictEqual(items[0]?.etag, "11bdc430-65e8-45ad-81d9-8ffa60d55b59"); + }); + + it("should list with page", async () => { + const customPageIter = await client.listWithPage(); + const items = []; + for await (const user of customPageIter) { + items.push(user); + } + assert.strictEqual(items.length, 1); + assert.strictEqual(items[0]?.name, "Madge"); + assert.strictEqual(items[0]?.etag, "11bdc430-65e8-45ad-81d9-8ffa60d55b59"); + }); }); diff --git a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts b/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts similarity index 85% rename from packages/typespec-ts/test/modularIntegration/pageable.spec.ts rename to packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts index 4e6389b4b7..f89beca981 100644 --- a/packages/typespec-ts/test/modularIntegration/pageable.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts @@ -4,11 +4,6 @@ import { } from "./generated/payload/pageable/src/index.js"; import { assert } from "chai"; -/** - * Add test cases to test the iterable and iterator - * Add test cases to test error handling - */ - describe("PageableClient Classical Client", () => { let client: PageableClient; @@ -86,14 +81,7 @@ describe("PageableClient Classical Client", () => { const pagedIter = client .list({ maxpagesize: 3 }) .byPage({ maxPageSize: 10 } as any); - try { - const items: User[] = (await pagedIter.next()).value; - assert.strictEqual(items.length, 3); - } catch (err: any) { - assert.strictEqual( - err.message, - "maxPageSize is not supported by this operation." - ); - } + const items: User[] = (await pagedIter.next()).value; + assert.strictEqual(items.length, 3); }); }); From 04f6e241c2bf085f402b066866623ce4b97287db Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 22:24:40 +0800 Subject: [PATCH 26/60] Fix lint issues --- packages/typespec-ts/src/modular/buildPagingFiles.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index a48870e873..113ae44720 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -5,10 +5,7 @@ import { isPagingOperation } from "./helpers/operationHelpers.js"; -export async function buildPagingTypes( - codeModel: ModularCodeModel, - client: Client -) { +export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { if (!hasPagingOperation(client)) { return; } @@ -58,7 +55,7 @@ export async function buildPagingTypes( return fileContent; } -export async function buildPagingHelpers( +export function buildPagingHelpers( codeModel: ModularCodeModel, client: Client ) { From 931cf4db05b3fb998accd5fd802e56b945d8fec4 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 22:35:43 +0800 Subject: [PATCH 27/60] Fix lint issues --- .../test/modularIntegration/payloadPageable.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts b/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts index f89beca981..012a2a7fbc 100644 --- a/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts @@ -70,6 +70,10 @@ describe("PageableClient Classical Client", () => { assert.strictEqual(firstPage.value.length, 3); // initiate another iterator starting with 2nd page const continuationToken = firstPage.value.continuationToken; + assert.strictEqual( + continuationToken, + "http://localhost:3000/payload/pageable?skipToken=name-user7&maxpagesize=3" + ); const items: User[] = []; for await (const pagedUsers of iter.byPage({ continuationToken })) { items.push(...pagedUsers); From 448846dd882a96979b8524d737a8e6b3c6e7b985 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 22:51:14 +0800 Subject: [PATCH 28/60] Update the paging for smoke testings --- .../review/ai-content-safety.api.md | 16 +- .../typespec-ts/src/ContentSafetyClient.ts | 2 +- .../typespec-ts/src/api/operations.ts | 6 +- .../pagingUtil.ts => api/pagingHelpers.ts} | 45 +--- .../generated/typespec-ts/src/index.ts | 2 + .../generated/typespec-ts/src/models/index.ts | 1 + .../typespec-ts/src/models/pagingTypes.ts | 33 +++ .../typespec-ts/review/load-testing.api.md | 37 ++- .../generated/typespec-ts/src/index.ts | 4 + .../LoadTestAdministrationClient.ts | 2 +- .../loadTestAdministration/api/operations.ts | 6 +- .../api/pagingHelpers.ts} | 45 +--- .../src/loadTestAdministration/index.ts | 2 + .../loadTestAdministration/models/index.ts | 1 + .../models/pagingTypes.ts | 33 +++ .../src/loadTestRun/LoadTestRunClient.ts | 3 +- .../src/loadTestRun/api/operations.ts | 8 +- .../src/loadTestRun/api/pagingHelpers.ts | 232 ++++++++++++++++++ .../typespec-ts/src/loadTestRun/index.ts | 2 + .../src/loadTestRun/models/index.ts | 1 + .../src/loadTestRun/models/pagingTypes.ts | 33 +++ .../src/modular/buildClassicalClient.ts | 21 -- 22 files changed, 423 insertions(+), 112 deletions(-) rename packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/{util/pagingUtil.ts => api/pagingHelpers.ts} (85%) create mode 100644 packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts rename packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/{pagingUtil.ts => loadTestAdministration/api/pagingHelpers.ts} (85%) create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts create mode 100644 packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts 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 680cea71ea..0173fb362b 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 @@ -76,8 +76,8 @@ export class ContentSafetyClient { getTextBlocklist(blocklistName: string, options?: GetTextBlocklistOptions): Promise; getTextBlocklistItem(blocklistName: string, blockItemId: string, options?: GetTextBlocklistItemOptions): Promise; listTextBlocklistItems(blocklistName: string, options?: ListTextBlocklistItemsOptions): PagedAsyncIterableIterator; - // Warning: (ae-forgotten-export) The symbol "PagedAsyncIterableIterator" needs to be exported by the entry point index.d.ts listTextBlocklists(options?: ListTextBlocklistsOptions): PagedAsyncIterableIterator; + readonly pipeline: Pipeline; removeBlockItems(blocklistName: string, body: RemoveBlockItemsOptions, options?: RemoveBlockItemsRequestOptions): Promise; } @@ -129,6 +129,15 @@ export interface ListTextBlocklistItemsOptions extends OperationOptions { export interface ListTextBlocklistsOptions extends OperationOptions { } +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + // @public export interface PagedTextBlockItem { nextLink?: string; @@ -141,6 +150,11 @@ export interface PagedTextBlocklist { value: TextBlocklist[]; } +// @public (undocumented) +export interface PageSettings { + continuationToken?: string; +} + // @public export interface RemoveBlockItemsOptions { blockItemIds: string[]; 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 48fc92e2b5..facad036e5 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 @@ -26,6 +26,7 @@ import { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createContentSafety, ContentSafetyClientOptions, @@ -41,7 +42,6 @@ import { getTextBlocklistItem, listTextBlocklistItems, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "./util/pagingUtil.js"; export { ContentSafetyClientOptions } from "./api/ContentSafetyContext.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 237df3fc12..8d66c896a0 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 @@ -14,6 +14,8 @@ import { PagedTextBlocklist, PagedTextBlockItem, } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, ContentSafetyContext as Client, @@ -44,10 +46,6 @@ import { operationOptionsToRequestParameters, } from "@azure-rest/core-client"; import { uint8ArrayToString } from "@azure/core-util"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../util/pagingUtil.js"; import { AnalyzeTextRequestOptions, AnalyzeImageRequestOptions, diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts similarity index 85% rename from packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts rename to packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index e7221e3e53..01fbf65b80 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/util/pagingUtil.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -12,6 +12,10 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; /** * Helper type to extract the type of an array */ @@ -34,37 +38,6 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; -export interface PageSettings { - /** - * 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 = PageSettings -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings - ) => AsyncIterableIterator; -} - export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -181,7 +154,8 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` ); } @@ -247,9 +221,10 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames, - ].join(" OR ")}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 08fdd88800..64bf083e26 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 @@ -36,4 +36,6 @@ export { RemoveBlockItemsRequestOptions, GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, + PageSettings, + PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts index 280a85b61f..8ee8a8abb9 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts @@ -35,3 +35,4 @@ export { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "./options.js"; +export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} 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 29c45ad685..e8e0fbdb1b 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 @@ -190,9 +190,9 @@ export class LoadTestAdministrationClient { getServerMetricsConfig(testId: string, options?: GetServerMetricsConfigOptions): Promise; getTest(testId: string, options?: GetTestOptions): Promise; getTestFile(testId: string, fileName: string, options?: GetTestFileOptions): Promise; - // Warning: (ae-forgotten-export) The symbol "PagedAsyncIterableIterator" needs to be exported by the entry point index.d.ts listTestFiles(testId: string, options?: ListTestFilesOptions): PagedAsyncIterableIterator; listTests(options?: ListTestsOptions): PagedAsyncIterableIterator; + readonly pipeline: Pipeline; uploadTestFile(testId: string, fileName: string, body: Uint8Array, options?: UploadTestFileOptions): Promise; } @@ -222,11 +222,12 @@ export class LoadTestRunClient { getTestRunFile(testRunId: string, fileName: string, options?: GetTestRunFileOptions): Promise; // Warning: (ae-forgotten-export) The symbol "MetricDefinitionCollection" needs to be exported by the entry point index.d.ts listMetricDefinitions(testRunId: string, options?: ListMetricDefinitionsOptions): Promise; - listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptions): PagedAsyncIterableIterator; + listMetricDimensionValues(testRunId: string, name: string, metricNamespace: string, options?: ListMetricDimensionValuesOptions): LoadTestRunClientPagedAsyncIterableIterator; // Warning: (ae-forgotten-export) The symbol "MetricNamespaceCollection" needs to be exported by the entry point index.d.ts listMetricNamespaces(testRunId: string, options?: ListMetricNamespacesOptions): Promise; - listMetrics(testRunId: string, options?: ListMetricsOptions): PagedAsyncIterableIterator; - listTestRuns(options?: ListTestRunsOptions): PagedAsyncIterableIterator; + // Warning: (ae-forgotten-export) The symbol "MetricRequestPayload" needs to be exported by the entry point index.d.ts + listMetrics(testRunId: string, body: MetricRequestPayload, options?: ListMetricsOptions): LoadTestRunClientPagedAsyncIterableIterator; + listTestRuns(options?: ListTestRunsOptions): LoadTestRunClientPagedAsyncIterableIterator; readonly pipeline: Pipeline; stopTestRun(testRunId: string, options?: StopTestRunOptions): Promise; testRun(testRunId: string, resource: LoadTestRunClientTestRun, options?: TestRunOptions): Promise; @@ -376,6 +377,20 @@ export interface LoadTestRunClientOptionalLoadTestConfig { export interface LoadTestRunClientOptions extends ClientOptions { } +// @public +export interface LoadTestRunClientPagedAsyncIterableIterator { + [Symbol.asyncIterator](): LoadTestRunClientPagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + +// @public (undocumented) +export interface LoadTestRunClientPageSettings { + continuationToken?: string; +} + // @public export interface LoadTestRunClientPassFailCriteria { passFailMetrics?: Record; @@ -584,6 +599,15 @@ export interface OptionalLoadTestConfig { virtualUsers?: number; } +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator; + next(): Promise>; +} + // @public export interface PagedFileInfo { nextLink?: string; @@ -596,6 +620,11 @@ export interface PagedTest { value: Test[]; } +// @public (undocumented) +export interface PageSettings { + continuationToken?: string; +} + // @public export interface PassFailCriteria { passFailMetrics?: Record; 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 cd91d5d41b..13c0e4402d 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 @@ -62,6 +62,8 @@ export { UploadTestFileOptions, DeleteTestFileOptions, DeleteTestOptions, + PageSettings, + PagedAsyncIterableIterator, } from "./loadTestAdministration/models/index.js"; export { LoadTestRunClient, @@ -122,4 +124,6 @@ export { ListMetricsOptions, ListTestRunsOptions, StopTestRunOptions, + PageSettings as LoadTestRunClientPageSettings, + PagedAsyncIterableIterator as LoadTestRunClientPagedAsyncIterableIterator, } from "./loadTestRun/models/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 a3f19b680c..aabca806c9 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 @@ -23,6 +23,7 @@ import { DeleteTestFileOptions, DeleteTestOptions, } from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createLoadTestAdministration, LoadTestAdministrationClientOptions, @@ -40,7 +41,6 @@ import { deleteTestFile, deleteTest, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "../util/pagingUtil.js"; export { LoadTestAdministrationClientOptions } from "./api/LoadTestAdministrationContext.js"; 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 09af133c77..67af8b86a9 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 @@ -9,6 +9,8 @@ import { PagedFileInfo, PagedTest, } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, AzureLoadTestingContext as Client, @@ -44,10 +46,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../../util/pagingUtil.js"; import { CreateOrUpdateTestOptions, CreateOrUpdateAppComponentsOptions, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/pagingUtil.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts similarity index 85% rename from packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/pagingUtil.ts rename to packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index e7221e3e53..01fbf65b80 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/pagingUtil.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -12,6 +12,10 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; /** * Helper type to extract the type of an array */ @@ -34,37 +38,6 @@ export type PaginateReturn = TResult extends ? GetArrayType : Array; -export interface PageSettings { - /** - * 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 = PageSettings -> { - /** - * The next method, part of the iteration protocol - */ - next(): Promise>; - /** - * The connection to the async iterator, part of the iteration protocol - */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - /** - * Return an AsyncIterableIterator that works a page at a time - */ - byPage: ( - settings?: TPageSettings - ) => AsyncIterableIterator; -} - export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse @@ -181,7 +154,8 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` ); } @@ -247,9 +221,10 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( - `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ - ...itemNames, - ].join(" OR ")}` + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 34faaccfef..733f16c264 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 @@ -62,4 +62,6 @@ export { UploadTestFileOptions, DeleteTestFileOptions, DeleteTestOptions, + PageSettings, + PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts index 76273f1843..a6f3105411 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts @@ -61,3 +61,4 @@ export { DeleteTestFileOptions, DeleteTestOptions, } from "./options.js"; +export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} 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 14b2906dd9..814e820eaa 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 @@ -10,6 +10,7 @@ import { TestRunServerMetricConfig, MetricDefinitionCollection, MetricNamespaceCollection, + MetricRequestPayload, TimeSeriesElement, DimensionValueList, } from "./models/models.js"; @@ -29,6 +30,7 @@ import { ListTestRunsOptions, StopTestRunOptions, } from "./models/options.js"; +import { PagedAsyncIterableIterator } from "./models/pagingTypes.js"; import { createLoadTestRun, LoadTestRunClientOptions, @@ -48,7 +50,6 @@ import { listTestRuns, stopTestRun, } from "./api/index.js"; -import { PagedAsyncIterableIterator } from "../util/pagingUtil.js"; export { LoadTestRunClientOptions } from "./api/LoadTestRunContext.js"; 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 adf9996ef6..81a573e3e3 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 @@ -15,6 +15,8 @@ import { PagedDimensionValueList, DimensionValueList, } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, AzureLoadTestingContext as Client, @@ -55,10 +57,6 @@ import { StreamableMethod, operationOptionsToRequestParameters, } from "@azure-rest/core-client"; -import { - PagedAsyncIterableIterator, - buildPagedAsyncIterator, -} from "../../util/pagingUtil.js"; import { TestRunOptions, CreateOrUpdateAppComponentsOptions, @@ -1142,7 +1140,7 @@ export function listMetrics( context, _listMetricsSend, _listMetricsDeserialize, - [context, testRunId, options] + [context, testRunId, body, options] ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts new file mode 100644 index 0000000000..01fbf65b80 --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, + PagedResult, + PageSettings as CorePageSettings, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { items?: infer TPage }; + } + ? GetArrayType + : Array; + +export function buildPagedAsyncIterator< + TElement, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + initialSendFunction: (...args: any[]) => PromiseLike, + deserializeFunction: (result: TResponse) => Promise, + sendFunctionArgs: any[] = [] +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string) => { + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await initialSendFunction(...sendFunctionArgs) + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + const results = await deserializeFunction(result as TResponse); + const nextLink = getNextLink(results, nextLinkName); + const values = getElements(results, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + byPage: (settings?: PageSettings) => { + const { continuationToken } = settings ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }) as any; + }, + }; + const iter: CorePagedAsyncIterableIterator = + getPagedAsyncIterator(pagedResult); + + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (settings?: PageSettings) => { + return iter.byPage( + settings as CorePageSettings + ) as unknown as AsyncIterableIterator< + TElement[] & { continuationToken?: string } + >; + }, + }; +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + (response.page as any).continuationToken = response.nextPageLink; + yield response.page as any; + } +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` + ); + } + + return { itemName, nextLinkName }; +} 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 10f2cd0239..37ec63c818 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 @@ -68,4 +68,6 @@ export { ListMetricsOptions, ListTestRunsOptions, StopTestRunOptions, + PageSettings, + PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts index ee4a125d67..48d354af22 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts @@ -67,3 +67,4 @@ export { ListTestRunsOptions, StopTestRunOptions, } from "./options.js"; +export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts new file mode 100644 index 0000000000..9d1d61320d --- /dev/null +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export interface PageSettings { + /** + * 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 = PageSettings +> { + /** + * The next method, part of the iteration protocol + */ + next(): Promise>; + /** + * The connection to the async iterator, part of the iteration protocol + */ + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + /** + * Return an AsyncIterableIterator that works a page at a time + */ + byPage: ( + settings?: TPageSettings + ) => AsyncIterableIterator; +} diff --git a/packages/typespec-ts/src/modular/buildClassicalClient.ts b/packages/typespec-ts/src/modular/buildClassicalClient.ts index 8414668e1c..2d5b1e94a1 100644 --- a/packages/typespec-ts/src/modular/buildClassicalClient.ts +++ b/packages/typespec-ts/src/modular/buildClassicalClient.ts @@ -90,31 +90,10 @@ export function buildClassicalClient( importAllModels(clientFile, srcPath, subfolder); buildClientOperationGroups(clientFile, client, clientClass); importAllApis(clientFile, srcPath, subfolder); - importAllUtils(clientFile, srcPath, subfolder); clientFile.fixMissingImports(); clientFile.fixUnusedIdentifiers(); } -function importAllUtils( - clientFile: SourceFile, - srcPath: string, - subfolder: string -) { - const project = clientFile.getProject(); - const utils = project.getSourceFile(`${srcPath}/util/pagingUtil.ts`); - - if (!utils) { - return; - } - - const exported = [...utils.getExportedDeclarations().keys()]; - - clientFile.addImportDeclaration({ - moduleSpecifier: `${subfolder !== "" ? "." : ""}./util/pagingUtil.js`, - namedImports: exported - }); -} - function importAllApis( clientFile: SourceFile, srcPath: string, From 917e9bc897767ab8c96c47878b1da05d43d1b1fb Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 22:55:25 +0800 Subject: [PATCH 29/60] Refactor code --- .../typespec-ts/src/modular/buildCodeModel.ts | 8 +++++--- .../transform/transformHelperFunctionDetails.ts | 17 +++-------------- packages/typespec-ts/src/utils/operationUtil.ts | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index dcfe9b978f..0a603ff95f 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -96,7 +96,9 @@ import { getOperationName, isBinaryPayload, isIgnoredHeaderParam, - isLongRunningOperation + isLongRunningOperation, + parseItemName, + parseNextLinkName } from "../utils/operationUtil.js"; import { SdkContext } from "../utils/interfaces.js"; import { Project } from "ts-morph"; @@ -680,8 +682,8 @@ function addPagingInformation( "Trying to add paging information, but not paging metadata for this operation" ); } - emittedOperation["itemName"] = pagedResult.itemsPath; - emittedOperation["continuationTokenName"] = pagedResult.nextLinkPath; + emittedOperation["itemName"] = parseItemName(pagedResult); + emittedOperation["continuationTokenName"] = parseNextLinkName(pagedResult); } function emitLroPagingOperation( diff --git a/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts b/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts index e5eb6f9421..24483cf784 100644 --- a/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts +++ b/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts @@ -11,7 +11,9 @@ import { hasPagingOperations, extractPagedMetadataNested, hasPollingOperations, - getSpecialSerializeInfo + getSpecialSerializeInfo, + parseNextLinkName, + parseItemName } from "../utils/operationUtil.js"; import { SdkContext } from "../utils/interfaces.js"; @@ -167,19 +169,6 @@ function extractPageDetailFromCore( }; } -function parseNextLinkName(paged: PagedResultMetadata): string | undefined { - return paged.nextLinkProperty?.name; -} - -function parseItemName(paged: PagedResultMetadata): string | undefined { - const pathComponents = paged.itemsPath?.split("."); - if (pathComponents) { - // TODO: This logic breaks down if there actually is a dotted path. - return pathComponents[pathComponents.length - 1]; - } - return undefined; -} - function extractSpecialSerializeInfo( program: Program, client: SdkClient, diff --git a/packages/typespec-ts/src/utils/operationUtil.ts b/packages/typespec-ts/src/utils/operationUtil.ts index 9f4f7bed26..60a2ff503f 100644 --- a/packages/typespec-ts/src/utils/operationUtil.ts +++ b/packages/typespec-ts/src/utils/operationUtil.ts @@ -530,3 +530,18 @@ export function isIgnoredHeaderParam(param: HttpOperationParameter) { )) ); } + +export function parseNextLinkName( + paged: PagedResultMetadata +): string | undefined { + return paged.nextLinkProperty?.name; +} + +export function parseItemName(paged: PagedResultMetadata): string | undefined { + const pathComponents = paged.itemsPath?.split("."); + if (pathComponents) { + // TODO: This logic breaks down if there actually is a dotted path. + return pathComponents[pathComponents.length - 1]; + } + return undefined; +} From 37d56262d1fe10a158ee33c893b1e4d244cd8b86 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 23:01:42 +0800 Subject: [PATCH 30/60] Refactor code --- .../typespec-ts/src/transform/transformHelperFunctionDetails.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts b/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts index 24483cf784..e9f9fe21ae 100644 --- a/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts +++ b/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts @@ -1,4 +1,3 @@ -import { PagedResultMetadata } from "@azure-tools/typespec-azure-core"; import { SdkClient, listOperationGroups, From 963d5df2326507ffd8f825a1c2a6822c849757e1 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 15 Nov 2023 23:33:59 +0800 Subject: [PATCH 31/60] Refactor code --- common/config/rush/pnpm-lock.yaml | 10 +++++----- packages/typespec-ts/package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 23ce4ed8eb..f434f578f8 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -231,7 +231,7 @@ importers: '@azure-rest/core-client': ^1.1.4 '@azure-tools/cadl-ranch': ^0.9.0 '@azure-tools/cadl-ranch-expect': ^0.8.0 - '@azure-tools/cadl-ranch-specs': ^0.25.0 + '@azure-tools/cadl-ranch-specs': ^0.24.0 '@azure-tools/rlc-common': workspace:^0.18.0 '@azure-tools/typespec-azure-core': '>=0.35.0 <1.0.0' '@azure-tools/typespec-client-generator-core': '>=0.35.0 <1.0.0' @@ -283,7 +283,7 @@ importers: '@azure-rest/core-client': 1.1.4 '@azure-tools/cadl-ranch': 0.9.0_tezp5rjfyokhpujhigtdeqwzp4 '@azure-tools/cadl-ranch-expect': 0.8.0_hyg5yyh7beodvmafzqxellnzky - '@azure-tools/cadl-ranch-specs': 0.25.0_o47dwcig7y553a2ndtr7sutngq + '@azure-tools/cadl-ranch-specs': 0.24.0_o47dwcig7y553a2ndtr7sutngq '@azure/core-auth': 1.5.0 '@azure/core-lro': 2.5.4 '@azure/core-paging': 1.5.0 @@ -417,11 +417,11 @@ packages: '@typespec/versioning': 0.49.0_@typespec+compiler@0.49.0 dev: true - /@azure-tools/cadl-ranch-specs/0.25.0_o47dwcig7y553a2ndtr7sutngq: - resolution: {integrity: sha512-TV1EsOCjeRCS/54KWCekwMDjGZN/H4F9Hqkp3djNhpemBCThiuGImNLC01b0ivY1r1NhiPZ08rFRq3QpFU22Rw==} + /@azure-tools/cadl-ranch-specs/0.24.0_o47dwcig7y553a2ndtr7sutngq: + resolution: {integrity: sha512-60gcPbnh1JMoE7IGJyXVfX6SRM/X4hE+fHzRc0oe64/GuRJuNS9Xzi8pwOqmoCJDQU1Y2O0y0H0fDHtEJdL6Sg==} engines: {node: '>=16.0.0'} peerDependencies: - '@azure-tools/cadl-ranch-expect': ~0.8.1 + '@azure-tools/cadl-ranch-expect': ~0.8.0 '@azure-tools/typespec-azure-core': ~0.35.0 '@typespec/compiler': ~0.49.0 '@typespec/http': ~0.49.0 diff --git a/packages/typespec-ts/package.json b/packages/typespec-ts/package.json index b6c866f80d..9119baf928 100644 --- a/packages/typespec-ts/package.json +++ b/packages/typespec-ts/package.json @@ -58,7 +58,7 @@ "ts-node": "~10.9.1", "typescript": "~5.2.0", "prettier": "~2.7.1", - "@azure-tools/cadl-ranch-specs": "^0.25.0", + "@azure-tools/cadl-ranch-specs": "^0.24.0", "@azure-tools/cadl-ranch-expect": "^0.8.0", "@azure-tools/cadl-ranch": "^0.9.0", "chalk": "^4.0.0", From 494e6168d7685dbfb549a53de44fbeadc948cac3 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 00:02:08 +0800 Subject: [PATCH 32/60] Update packages/typespec-ts/test/commands/cadl-ranch-list.ts --- packages/typespec-ts/test/commands/cadl-ranch-list.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index f8f155ab9b..64590d38f4 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -226,7 +226,6 @@ export const modularTsps: TypeSpecRanchConfig[] = [ { outputPath: "azure/core", inputPath: "azure/core/basic", - debug: true }, { outputPath: "payload/pageable", From fa6c1dece9ea376a01382be8ee37dec7a4a2c434 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 00:02:35 +0800 Subject: [PATCH 33/60] Update packages/typespec-ts/test/commands/cadl-ranch-list.ts --- packages/typespec-ts/test/commands/cadl-ranch-list.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index 64590d38f4..de3a27f64a 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -225,7 +225,7 @@ export const modularTsps: TypeSpecRanchConfig[] = [ }, { outputPath: "azure/core", - inputPath: "azure/core/basic", + inputPath: "azure/core/basic" }, { outputPath: "payload/pageable", From 27c25d49f3ba0d5e24d87744dee4c64d4f89e0b4 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 00:03:04 +0800 Subject: [PATCH 34/60] Update packages/typespec-ts/test/commands/cadl-ranch-list.ts --- packages/typespec-ts/test/commands/cadl-ranch-list.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index de3a27f64a..4fb341814d 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -230,7 +230,6 @@ export const modularTsps: TypeSpecRanchConfig[] = [ { outputPath: "payload/pageable", inputPath: "payload/pageable", - debug: true }, { outputPath: "encode/duration", From e3fd177fc103fe4be48f7c575a9b36bb476d83a8 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 00:03:30 +0800 Subject: [PATCH 35/60] Update packages/typespec-ts/test/commands/cadl-ranch-list.ts --- packages/typespec-ts/test/commands/cadl-ranch-list.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index 4fb341814d..01d359c8f0 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -229,7 +229,7 @@ export const modularTsps: TypeSpecRanchConfig[] = [ }, { outputPath: "payload/pageable", - inputPath: "payload/pageable", + inputPath: "payload/pageable" }, { outputPath: "encode/duration", From ee3b29aba166b01f286348e5d15da59d89bbd536 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 11:03:13 +0800 Subject: [PATCH 36/60] Add comments for interface --- .../batch_modular/generated/typespec-ts/review/batch.api.md | 2 +- .../generated/typespec-ts/src/models/pagingTypes.ts | 3 +++ .../generated/typespec-ts/review/ai-content-safety.api.md | 2 +- .../generated/typespec-ts/src/models/pagingTypes.ts | 3 +++ .../generated/typespec-ts/review/load-testing.api.md | 4 ++-- .../src/loadTestAdministration/models/pagingTypes.ts | 3 +++ .../typespec-ts/src/loadTestRun/models/pagingTypes.ts | 3 +++ packages/typespec-ts/src/modular/buildPagingFiles.ts | 4 ++++ .../generated/azure/core/src/models/pagingTypes.ts | 3 +++ .../generated/payload/pageable/src/models/pagingTypes.ts | 3 +++ 10 files changed, 26 insertions(+), 4 deletions(-) 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 afc86c02e8..00ef0cc922 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 @@ -1654,7 +1654,7 @@ export interface PagedAsyncIterableIterator>; } -// @public (undocumented) +// @public export interface PageSettings { continuationToken?: string; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts index 9d1d61320d..cba454057d 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator 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 0173fb362b..80b897e165 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 @@ -150,7 +150,7 @@ export interface PagedTextBlocklist { value: TextBlocklist[]; } -// @public (undocumented) +// @public export interface PageSettings { continuationToken?: string; } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index 9d1d61320d..cba454057d 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator 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 e8e0fbdb1b..b56460aaee 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 @@ -386,7 +386,7 @@ export interface LoadTestRunClientPagedAsyncIterableIterator>; } -// @public (undocumented) +// @public export interface LoadTestRunClientPageSettings { continuationToken?: string; } @@ -620,7 +620,7 @@ export interface PagedTest { value: Test[]; } -// @public (undocumented) +// @public export interface PageSettings { continuationToken?: string; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts index 9d1d61320d..cba454057d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts index 9d1d61320d..cba454057d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 113ae44720..8db31b39d0 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -19,6 +19,10 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { }); fileContent.addStatements([ ` + + /** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts index 9d1d61320d..cba454057d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts index 9d1d61320d..cba454057d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts @@ -1,6 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * An interface that tracks the settings for paged iteration + */ export interface PageSettings { /** * The token that keeps track of where to continue the iterator From dfd18ea31c98809f7abff96e4a0d9605b5cfe009 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 15:58:10 +0800 Subject: [PATCH 37/60] Resolve comments --- packages/typespec-ts/src/modular/helpers/operationHelpers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index fcb4ffd088..be1c21b83a 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -249,7 +249,7 @@ export function getOperationFunction( // Extract required parameters const parameters: OptionalKind[] = getOperationSignatureParameters(operation, clientType); - const isPaging = operation.discriminator === "paging"; + const isPaging = isPagingOperation(operation); // TODO: Support operation overloads const response = operation.responses[0]!; From d7877c3cc8611f8327a7ed48770a386f7d7b57e0 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 16 Nov 2023 19:21:55 +0800 Subject: [PATCH 38/60] Update the modular paging regen --- .../generated/payload/pageable/src/api/operations.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts index 9703f39824..fe351800f0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts @@ -31,7 +31,7 @@ export async function _listDeserialize( } return { - value: (result.body["value"] ?? []).map((p) => ({ name: p["name"] })), + value: result.body["value"].map((p) => ({ name: p["name"] })), nextLink: result.body["nextLink"], }; } From 7f6c9abadaa5e08c50fa6a6343aa0387341fd81d Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 20 Nov 2023 13:55:04 +0800 Subject: [PATCH 39/60] Update the helpers and regenerate codes --- .../typespec-ts/src/api/operations.ts | 77 ++++++++----------- .../typespec-ts/src/api/pagingHelpers.ts | 9 +-- .../typespec-ts/src/api/operations.ts | 10 +-- .../typespec-ts/src/api/pagingHelpers.ts | 9 +-- .../loadTestAdministration/api/operations.ts | 10 +-- .../api/pagingHelpers.ts | 9 +-- .../src/loadTestRun/api/operations.ts | 22 +++--- .../src/loadTestRun/api/pagingHelpers.ts | 9 +-- packages/typespec-ts/src/index.ts | 4 +- .../typespec-ts/src/modular/buildCodeModel.ts | 10 +++ .../src/modular/buildPagingFiles.ts | 9 +-- .../src/modular/helpers/operationHelpers.ts | 4 +- .../transformHelperFunctionDetails.ts | 22 ++++-- .../azure/core/src/api/operations.ts | 17 ++-- .../azure/core/src/api/pagingHelpers.ts | 9 +-- .../payload/pageable/src/api/operations.ts | 7 +- .../payload/pageable/src/api/pagingHelpers.ts | 9 +-- 17 files changed, 123 insertions(+), 123 deletions(-) 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 253eddb1de..79b4cf7b08 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 @@ -349,9 +349,8 @@ export function listApplications( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listApplicationsSend, - _listApplicationsDeserialize, - [context, options] + () => _listApplicationsSend(context, options), + _listApplicationsDeserialize ); } @@ -453,9 +452,8 @@ export function listPoolUsageMetrics( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listPoolUsageMetricsSend, - _listPoolUsageMetricsDeserialize, - [context, options] + () => _listPoolUsageMetricsSend(context, options), + _listPoolUsageMetricsDeserialize ); } @@ -1349,9 +1347,8 @@ export function listPools( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listPoolsSend, - _listPoolsDeserialize, - [context, options] + () => _listPoolsSend(context, options), + _listPoolsDeserialize ); } @@ -2689,9 +2686,8 @@ export function listSupportedImages( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listSupportedImagesSend, - _listSupportedImagesDeserialize, - [context, options] + () => _listSupportedImagesSend(context, options), + _listSupportedImagesDeserialize ); } @@ -2777,9 +2773,8 @@ export function listPoolNodeCounts( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listPoolNodeCountsSend, - _listPoolNodeCountsDeserialize, - [context, options] + () => _listPoolNodeCountsSend(context, options), + _listPoolNodeCountsDeserialize ); } @@ -7623,10 +7618,11 @@ export function listJobs( context: Client, options: ListJobsOptions = { requestOptions: {} } ): PagedAsyncIterableIterator { - return buildPagedAsyncIterator(context, _listJobsSend, _listJobsDeserialize, [ + return buildPagedAsyncIterator( context, - options, - ]); + () => _listJobsSend(context, options), + _listJobsDeserialize + ); } export function _listJobsFromScheduleSend( @@ -8731,9 +8727,8 @@ export function listJobsFromSchedule( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listJobsFromScheduleSend, - _listJobsFromScheduleDeserialize, - [context, jobScheduleId, options] + () => _listJobsFromScheduleSend(context, jobScheduleId, options), + _listJobsFromScheduleDeserialize ); } @@ -8921,9 +8916,8 @@ export function listJobPreparationAndReleaseTaskStatus( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listJobPreparationAndReleaseTaskStatusSend, - _listJobPreparationAndReleaseTaskStatusDeserialize, - [context, jobId, options] + () => _listJobPreparationAndReleaseTaskStatusSend(context, jobId, options), + _listJobPreparationAndReleaseTaskStatusDeserialize ); } @@ -9104,9 +9098,8 @@ export function listCertificates( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listCertificatesSend, - _listCertificatesDeserialize, - [context, options] + () => _listCertificatesSend(context, options), + _listCertificatesDeserialize ); } @@ -15597,9 +15590,8 @@ export function listJobSchedules( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listJobSchedulesSend, - _listJobSchedulesDeserialize, - [context, options] + () => _listJobSchedulesSend(context, options), + _listJobSchedulesDeserialize ); } @@ -16171,9 +16163,8 @@ export function listTasks( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTasksSend, - _listTasksDeserialize, - [context, jobId, options] + () => _listTasksSend(context, jobId, options), + _listTasksDeserialize ); } @@ -17350,9 +17341,8 @@ export function listTaskFiles( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTaskFilesSend, - _listTaskFilesDeserialize, - [context, jobId, taskId, options] + () => _listTaskFilesSend(context, jobId, taskId, options), + _listTaskFilesDeserialize ); } @@ -18479,9 +18469,8 @@ export function listNodes( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listNodesSend, - _listNodesDeserialize, - [context, poolId, options] + () => _listNodesSend(context, poolId, options), + _listNodesDeserialize ); } @@ -18661,9 +18650,8 @@ export function listNodeExtensions( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listNodeExtensionsSend, - _listNodeExtensionsDeserialize, - [context, poolId, nodeId, options] + () => _listNodeExtensionsSend(context, poolId, nodeId, options), + _listNodeExtensionsDeserialize ); } @@ -18898,8 +18886,7 @@ export function listNodeFiles( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listNodeFilesSend, - _listNodeFilesDeserialize, - [context, poolId, nodeId, options] + () => _listNodeFilesSend(context, poolId, nodeId, options), + _listNodeFilesDeserialize ); } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 89e3390018..7dcf410724 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -43,9 +43,8 @@ export function buildPagedAsyncIterator< TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -55,7 +54,7 @@ export function buildPagedAsyncIterator< getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -64,7 +63,7 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { 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 919730fcd2..fd994c248c 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 @@ -315,9 +315,8 @@ export function listTextBlocklists( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTextBlocklistsSend, - _listTextBlocklistsDeserialize, - [context, options] + () => _listTextBlocklistsSend(context, options), + _listTextBlocklistsDeserialize ); } @@ -516,8 +515,7 @@ export function listTextBlocklistItems( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTextBlocklistItemsSend, - _listTextBlocklistItemsDeserialize, - [context, blocklistName, options] + () => _listTextBlocklistItemsSend(context, blocklistName, options), + _listTextBlocklistItemsDeserialize ); } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 01fbf65b80..f0ee8fc109 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -43,9 +43,8 @@ export function buildPagedAsyncIterator< TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -55,7 +54,7 @@ export function buildPagedAsyncIterator< getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -64,7 +63,7 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { 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 7e97db8617..b4d247515f 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 @@ -787,9 +787,8 @@ export function listTestFiles( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTestFilesSend, - _listTestFilesDeserialize, - [context, testId, options] + () => _listTestFilesSend(context, testId, options), + _listTestFilesDeserialize ); } @@ -971,9 +970,8 @@ export function listTests( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTestsSend, - _listTestsDeserialize, - [context, options] + () => _listTestsSend(context, options), + _listTestsDeserialize ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index 01fbf65b80..f0ee8fc109 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -43,9 +43,8 @@ export function buildPagedAsyncIterator< TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -55,7 +54,7 @@ export function buildPagedAsyncIterator< getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -64,7 +63,7 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { 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 ccf9bfeb8e..352865d651 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 @@ -983,9 +983,15 @@ export function listMetricDimensionValues( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listMetricDimensionValuesSend, - _listMetricDimensionValuesDeserialize, - [context, testRunId, name, metricNamespace, options] + () => + _listMetricDimensionValuesSend( + context, + testRunId, + name, + metricNamespace, + options + ), + _listMetricDimensionValuesDeserialize ); } @@ -1152,9 +1158,8 @@ export function listMetrics( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listMetricsSend, - _listMetricsDeserialize, - [context, testRunId, body, options] + () => _listMetricsSend(context, testRunId, body, options), + _listMetricsDeserialize ); } @@ -1451,9 +1456,8 @@ export function listTestRuns( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listTestRunsSend, - _listTestRunsDeserialize, - [context, options] + () => _listTestRunsSend(context, options), + _listTestRunsDeserialize ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index 01fbf65b80..f0ee8fc109 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -43,9 +43,8 @@ export function buildPagedAsyncIterator< TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -55,7 +54,7 @@ export function buildPagedAsyncIterator< getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -64,7 +63,7 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index 53036ce941..ccf051859e 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -56,7 +56,7 @@ import { ModularCodeModel } from "./modular/modularCodeModel.js"; import { getClientName } from "@azure-tools/rlc-common"; import { buildPagingTypes, - buildPagingHelpers as buildModularPaginateHelper + buildPagingHelpers as buildModularPagingHelpers } from "./modular/buildPagingFiles.js"; export * from "./lib.js"; @@ -181,7 +181,7 @@ export async function $onEmit(context: EmitContext) { const hasClientUnexpectedHelper = needUnexpectedHelper.get(subClient.rlcClientName) ?? false; buildPagingTypes(modularCodeModel, subClient); - buildModularPaginateHelper(modularCodeModel, subClient); + buildModularPagingHelpers(modularCodeModel, subClient); buildOperationFiles( dpgContext, modularCodeModel, diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 0a603ff95f..585145ef61 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -641,6 +641,16 @@ function emitOperation( operationGroupName: string, rlcModels: RLCModel ): HrlcOperation { + const isBranded = rlcModels.options?.branded ?? true; + // Skip to extract paging and lro information for non-branded clients. + if (!isBranded) { + return emitBasicOperation( + context, + operation, + operationGroupName, + rlcModels + ); + } const lro = isLongRunningOperation( context.program, ignoreDiagnostics(getHttpOperation(context.program, operation)) diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 8db31b39d0..fd8e712e15 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -141,9 +141,8 @@ export function buildPagingHelpers( TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -153,7 +152,7 @@ export function buildPagingHelpers( getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -162,7 +161,7 @@ export function buildPagingHelpers( } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index be1c21b83a..9524051575 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -279,9 +279,9 @@ export function getOperationFunction( const statements: string[] = []; if (isPaging) { statements.push( - `return buildPagedAsyncIterator(context, _${name}Send, _${name}Deserialize, [${parameters + `return buildPagedAsyncIterator(context, () => _${name}Send(${parameters .map((p) => p.name) - .join(", ")}]) ;` + .join(", ")}), _${name}Deserialize) ;` ); } else { statements.push( diff --git a/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts b/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts index e9f9fe21ae..5895c11503 100644 --- a/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts +++ b/packages/typespec-ts/src/transform/transformHelperFunctionDetails.ts @@ -18,19 +18,29 @@ import { SdkContext } from "../utils/interfaces.js"; export function transformHelperFunctionDetails( client: SdkClient, - dpgContext: SdkContext + dpgContext: SdkContext, + isBranded: boolean = true ): HelperFunctionDetails { const program = dpgContext.program; - // Extract paged metadata from Azure.Core.Page - const annotationDetails = { - hasLongRunning: hasPollingOperations(program, client, dpgContext) - }; - const details = extractPageDetailFromCore(program, client, dpgContext); const serializeInfo = extractSpecialSerializeInfo( program, client, dpgContext ); + // Disbale paging and long running for non-branded clients. + if (!isBranded) { + return { + hasLongRunning: false, + hasPaging: false, + ...serializeInfo + }; + } + + // Extract paged metadata from Azure.Core.Page + const annotationDetails = { + hasLongRunning: hasPollingOperations(program, client, dpgContext) + }; + const details = extractPageDetailFromCore(program, client, dpgContext); if (details) { return { ...details, diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 4a41295be8..ce61211e6f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -265,10 +265,11 @@ export function list( context: Client, options: ListOptions = { requestOptions: {} } ): PagedAsyncIterableIterator { - return buildPagedAsyncIterator(context, _listSend, _listDeserialize, [ + return buildPagedAsyncIterator( context, - options, - ]); + () => _listSend(context, options), + _listDeserialize + ); } export function _listWithPageSend( @@ -311,9 +312,8 @@ export function listWithPage( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listWithPageSend, - _listWithPageDeserialize, - [context, options] + () => _listWithPageSend(context, options), + _listWithPageDeserialize ); } @@ -361,9 +361,8 @@ export function listWithCustomPageModel( ): PagedAsyncIterableIterator { return buildPagedAsyncIterator( context, - _listWithCustomPageModelSend, - _listWithCustomPageModelDeserialize, - [context, options] + () => _listWithCustomPageModelSend(context, options), + _listWithCustomPageModelDeserialize ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index 01fbf65b80..f0ee8fc109 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -43,9 +43,8 @@ export function buildPagedAsyncIterator< TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -55,7 +54,7 @@ export function buildPagedAsyncIterator< getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -64,7 +63,7 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts index fe351800f0..9548b89d90 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts @@ -41,8 +41,9 @@ export function list( context: Client, options: ListOptions = { requestOptions: {} } ): PagedAsyncIterableIterator { - return buildPagedAsyncIterator(context, _listSend, _listDeserialize, [ + return buildPagedAsyncIterator( context, - options, - ]); + () => _listSend(context, options), + _listDeserialize + ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index 01fbf65b80..f0ee8fc109 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -43,9 +43,8 @@ export function buildPagedAsyncIterator< TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, - initialSendFunction: (...args: any[]) => PromiseLike, - deserializeFunction: (result: TResponse) => Promise, - sendFunctionArgs: any[] = [] + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise ): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; @@ -55,7 +54,7 @@ export function buildPagedAsyncIterator< getPage: async (pageLink: string) => { const result = firstRun && pageLink === firstPageLinkPlaceholder - ? await initialSendFunction(...sendFunctionArgs) + ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); if (firstRun) { const pageInfo = getPaginationProperties(result); @@ -64,7 +63,7 @@ export function buildPagedAsyncIterator< } firstRun = false; checkPagingRequest(result); - const results = await deserializeFunction(result as TResponse); + const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); const values = getElements(results, itemName); return { From fa5c2fbc567071553489d1ada0f47543eb7210e5 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 20 Nov 2023 15:18:50 +0800 Subject: [PATCH 40/60] Remove useless types in pagings --- .../typespec-ts/src/api/pagingHelpers.ts | 21 --------------- .../src/modular/buildPagingFiles.ts | 26 ------------------- .../azure/core/src/api/pagingHelpers.ts | 21 --------------- .../payload/pageable/src/api/pagingHelpers.ts | 21 --------------- 4 files changed, 89 deletions(-) diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 7dcf410724..ccec197a8b 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -16,27 +16,6 @@ import { PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; export function buildPagedAsyncIterator< TElement, diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index fd8e712e15..8872a9d4b2 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -110,32 +110,6 @@ export function buildPagingHelpers( } from "@azure-rest/core-client"; import { PageSettings, PagedAsyncIterableIterator } from "${pagingTypesPath}"; - export interface PageInfo { - continuationToken?: string; - } - - /** - * Helper type to extract the type of an array - */ - export type GetArrayType = T extends Array ? TData : never; - - /** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is \`value\`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ - export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; - export function buildPagedAsyncIterator< TElement, TResponse extends PathUncheckedResponse = PathUncheckedResponse diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index f0ee8fc109..a16eae414f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -16,27 +16,6 @@ import { PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; export function buildPagedAsyncIterator< TElement, diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index f0ee8fc109..a16eae414f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -16,27 +16,6 @@ import { PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; export function buildPagedAsyncIterator< TElement, From bd42574315d72e022ec98dd7c123eb05aa9caac9 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 20 Nov 2023 15:27:51 +0800 Subject: [PATCH 41/60] Remove useless types in pagings --- .../typespec-ts/src/api/pagingHelpers.ts | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index f0ee8fc109..a16eae414f 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -16,27 +16,6 @@ import { PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; export function buildPagedAsyncIterator< TElement, From 4e95ced55eb52a262eab4fc90acfa107f479b565 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 20 Nov 2023 15:31:30 +0800 Subject: [PATCH 42/60] Regen for paging in load testing modular --- .../api/pagingHelpers.ts | 21 ------------------- .../src/loadTestRun/api/pagingHelpers.ts | 21 ------------------- 2 files changed, 42 deletions(-) diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index f0ee8fc109..a16eae414f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -16,27 +16,6 @@ import { PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; export function buildPagedAsyncIterator< TElement, diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index f0ee8fc109..a16eae414f 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -16,27 +16,6 @@ import { PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; -/** - * Helper type to extract the type of an array - */ -export type GetArrayType = T extends Array ? TData : never; - -/** - * Helper type to infer the Type of the paged elements from the response type - * This type is generated based on the swagger information for x-ms-pageable - * specifically on the itemName property which indicates the property of the response - * where the page items are found. The default value is `value`. - * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter - */ -export type PaginateReturn = TResult extends - | { - body: { value?: infer TPage }; - } - | { - body: { items?: infer TPage }; - } - ? GetArrayType - : Array; export function buildPagedAsyncIterator< TElement, From c7f7b7e24c4087d8d3412d6dda6a1500f8bbfb45 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 16:10:00 +0800 Subject: [PATCH 43/60] Regenerate the pagings not reference core's one --- .../generated/typespec-ts/review/batch.api.md | 11 +- .../typespec-ts/src/api/pagingHelpers.ts | 141 ++++-- .../generated/typespec-ts/src/index.ts | 1 + .../generated/typespec-ts/src/models/index.ts | 6 +- .../typespec-ts/src/models/pagingTypes.ts | 18 +- .../review/ai-content-safety.api.md | 11 +- .../typespec-ts/src/api/pagingHelpers.ts | 141 ++++-- .../generated/typespec-ts/src/index.ts | 1 + .../generated/typespec-ts/src/models/index.ts | 6 +- .../typespec-ts/src/models/pagingTypes.ts | 18 +- .../typespec-ts/review/load-testing.api.md | 22 +- .../generated/typespec-ts/src/index.ts | 2 + .../api/pagingHelpers.ts | 141 ++++-- .../src/loadTestAdministration/index.ts | 1 + .../loadTestAdministration/models/index.ts | 6 +- .../models/pagingTypes.ts | 18 +- .../src/loadTestRun/api/pagingHelpers.ts | 141 ++++-- .../typespec-ts/src/loadTestRun/index.ts | 1 + .../src/loadTestRun/models/index.ts | 6 +- .../src/loadTestRun/models/pagingTypes.ts | 18 +- .../src/modular/buildPagingFiles.ts | 463 +++++++++++------- .../azure/core/src/api/pagingHelpers.ts | 141 ++++-- .../generated/azure/core/src/index.ts | 1 + .../generated/azure/core/src/models/index.ts | 6 +- .../azure/core/src/models/pagingTypes.ts | 18 +- .../payload/pageable/src/api/pagingHelpers.ts | 141 ++++-- .../generated/payload/pageable/src/index.ts | 1 + .../payload/pageable/src/models/index.ts | 6 +- .../pageable/src/models/pagingTypes.ts | 18 +- 29 files changed, 1094 insertions(+), 411 deletions(-) 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 00ef0cc922..99a7141ac0 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 @@ -693,6 +693,11 @@ export type ContainerType = string; // @public export type ContainerWorkingDirectory = string; +// @public +export type ContinuablePage = TPage & { + continuationToken?: string; +}; + // @public (undocumented) export interface CreateCertificateOptions extends OperationOptions { contentType?: string; @@ -1647,10 +1652,8 @@ export interface OutputFileUploadOptions { // @public export interface PagedAsyncIterableIterator { - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - byPage: (settings?: TPageSettings) => AsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index ccec197a8b..47a612efec 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -1,34 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings, -} from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; import { + ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ export function buildPagedAsyncIterator< TElement, + TPage = TElement[], + TPageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, processResponseBody: (result: TResponse) => Promise -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { + const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, getPage: async (pageLink: string) => { const result = @@ -44,22 +75,36 @@ export function buildPagedAsyncIterator< checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); + const values = getElements(results, itemName) as TPage; return { page: values, nextPageLink: nextLink, }; }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; + byPage: (settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, - }) as any; + }); }, }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); return { next() { return iter.next(); @@ -67,22 +112,52 @@ export function buildPagedAsyncIterator< [Symbol.asyncIterator]() { return this; }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { pageLink?: string; } = {} -): AsyncIterableIterator { +): AsyncIterableIterator> { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -90,15 +165,17 @@ async function* getPageAsyncIterator( if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; } } @@ -133,7 +210,7 @@ function getElements(body: unknown, itemName: string): T[] { if (!Array.isArray(value)) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + Body doesn't contain an array property with name: ${itemName}` ); } @@ -200,9 +277,9 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 3d61a867f5..b7f832d522 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 @@ -284,5 +284,6 @@ export { GetNodeFilePropertiesOptions, ListNodeFilesOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts index d4a4972ad5..b9d5df8780 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/index.ts @@ -285,4 +285,8 @@ export { GetNodeFilePropertiesOptions, ListNodeFilesOptions, } from "./options.js"; -export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts index cba454057d..e4b49c8b7e 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -11,6 +11,16 @@ export interface PageSettings { 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. */ @@ -26,11 +36,15 @@ export interface PagedAsyncIterableIterator< /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } 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 80b897e165..d18df9dc80 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 @@ -85,6 +85,11 @@ export class ContentSafetyClient { export interface ContentSafetyClientOptions extends ClientOptions { } +// @public +export type ContinuablePage = TPage & { + continuationToken?: string; +}; + // @public (undocumented) export interface CreateOrUpdateTextBlocklistOptions extends OperationOptions { contentType?: string; @@ -131,10 +136,8 @@ export interface ListTextBlocklistsOptions extends OperationOptions { // @public export interface PagedAsyncIterableIterator { - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - byPage: (settings?: TPageSettings) => AsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index a16eae414f..5393be6ffd 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -1,34 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings, -} from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; import { + ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ export function buildPagedAsyncIterator< TElement, + TPage = TElement[], + TPageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, processResponseBody: (result: TResponse) => Promise -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { + const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, getPage: async (pageLink: string) => { const result = @@ -44,22 +75,36 @@ export function buildPagedAsyncIterator< checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); + const values = getElements(results, itemName) as TPage; return { page: values, nextPageLink: nextLink, }; }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; + byPage: (settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, - }) as any; + }); }, }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); return { next() { return iter.next(); @@ -67,22 +112,52 @@ export function buildPagedAsyncIterator< [Symbol.asyncIterator]() { return this; }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { pageLink?: string; } = {} -): AsyncIterableIterator { +): AsyncIterableIterator> { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -90,15 +165,17 @@ async function* getPageAsyncIterator( if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; } } @@ -133,7 +210,7 @@ function getElements(body: unknown, itemName: string): T[] { if (!Array.isArray(value)) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + Body doesn't contain an array property with name: ${itemName}` ); } @@ -200,9 +277,9 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 64bf083e26..83fb4b3902 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 @@ -37,5 +37,6 @@ export { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts index 8ee8a8abb9..7e794eecae 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/index.ts @@ -35,4 +35,8 @@ export { GetTextBlocklistItemOptions, ListTextBlocklistItemsOptions, } from "./options.js"; -export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index cba454057d..e4b49c8b7e 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -11,6 +11,16 @@ export interface PageSettings { 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. */ @@ -26,11 +36,15 @@ export interface PagedAsyncIterableIterator< /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } 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 b56460aaee..871a1592ae 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 @@ -33,6 +33,11 @@ export interface CertificateMetadata { // @public export type CertificateType = string; +// @public +export type ContinuablePage = TPage & { + continuationToken?: string; +}; + // @public (undocumented) export interface CreateOrUpdateAppComponentsOptions extends OperationOptions { // (undocumented) @@ -257,6 +262,11 @@ export interface LoadTestRunClientCertificateMetadata { // @public export type LoadTestRunClientCertificateType = string; +// @public +export type LoadTestRunClientContinuablePage = TPage & { + continuationToken?: string; +}; + // @public (undocumented) export interface LoadTestRunClientCreateOrUpdateAppComponentsOptions extends OperationOptions { // (undocumented) @@ -379,10 +389,8 @@ export interface LoadTestRunClientOptions extends ClientOptions { // @public export interface LoadTestRunClientPagedAsyncIterableIterator { - [Symbol.asyncIterator](): LoadTestRunClientPagedAsyncIterableIterator; - byPage: (settings?: TPageSettings) => AsyncIterableIterator; + [Symbol.asyncIterator](): LoadTestRunClientPagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; } @@ -601,10 +609,8 @@ export interface OptionalLoadTestConfig { // @public export interface PagedAsyncIterableIterator { - [Symbol.asyncIterator](): PagedAsyncIterableIterator; - byPage: (settings?: TPageSettings) => AsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; } 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 13c0e4402d..e9dc46c6f2 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 @@ -63,6 +63,7 @@ export { DeleteTestFileOptions, DeleteTestOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./loadTestAdministration/models/index.js"; export { @@ -125,5 +126,6 @@ export { ListTestRunsOptions, StopTestRunOptions, PageSettings as LoadTestRunClientPageSettings, + ContinuablePage as LoadTestRunClientContinuablePage, PagedAsyncIterableIterator as LoadTestRunClientPagedAsyncIterableIterator, } from "./loadTestRun/models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index a16eae414f..5393be6ffd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -1,34 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings, -} from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; import { + ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ export function buildPagedAsyncIterator< TElement, + TPage = TElement[], + TPageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, processResponseBody: (result: TResponse) => Promise -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { + const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, getPage: async (pageLink: string) => { const result = @@ -44,22 +75,36 @@ export function buildPagedAsyncIterator< checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); + const values = getElements(results, itemName) as TPage; return { page: values, nextPageLink: nextLink, }; }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; + byPage: (settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, - }) as any; + }); }, }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); return { next() { return iter.next(); @@ -67,22 +112,52 @@ export function buildPagedAsyncIterator< [Symbol.asyncIterator]() { return this; }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { pageLink?: string; } = {} -): AsyncIterableIterator { +): AsyncIterableIterator> { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -90,15 +165,17 @@ async function* getPageAsyncIterator( if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; } } @@ -133,7 +210,7 @@ function getElements(body: unknown, itemName: string): T[] { if (!Array.isArray(value)) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + Body doesn't contain an array property with name: ${itemName}` ); } @@ -200,9 +277,9 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 733f16c264..fcd4fdb5f3 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 @@ -63,5 +63,6 @@ export { DeleteTestFileOptions, DeleteTestOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts index a6f3105411..aacefc44c6 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/index.ts @@ -61,4 +61,8 @@ export { DeleteTestFileOptions, DeleteTestOptions, } from "./options.js"; -export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts index cba454057d..e4b49c8b7e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts @@ -11,6 +11,16 @@ export interface PageSettings { 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. */ @@ -26,11 +36,15 @@ export interface PagedAsyncIterableIterator< /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index a16eae414f..5393be6ffd 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -1,34 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings, -} from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; import { + ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ export function buildPagedAsyncIterator< TElement, + TPage = TElement[], + TPageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, processResponseBody: (result: TResponse) => Promise -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { + const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, getPage: async (pageLink: string) => { const result = @@ -44,22 +75,36 @@ export function buildPagedAsyncIterator< checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); + const values = getElements(results, itemName) as TPage; return { page: values, nextPageLink: nextLink, }; }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; + byPage: (settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, - }) as any; + }); }, }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); return { next() { return iter.next(); @@ -67,22 +112,52 @@ export function buildPagedAsyncIterator< [Symbol.asyncIterator]() { return this; }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { pageLink?: string; } = {} -): AsyncIterableIterator { +): AsyncIterableIterator> { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -90,15 +165,17 @@ async function* getPageAsyncIterator( if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; } } @@ -133,7 +210,7 @@ function getElements(body: unknown, itemName: string): T[] { if (!Array.isArray(value)) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + Body doesn't contain an array property with name: ${itemName}` ); } @@ -200,9 +277,9 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } 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 37ec63c818..cf465ed8cf 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 @@ -69,5 +69,6 @@ export { ListTestRunsOptions, StopTestRunOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts index 48d354af22..a9153d686d 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/index.ts @@ -67,4 +67,8 @@ export { ListTestRunsOptions, StopTestRunOptions, } from "./options.js"; -export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts index cba454057d..e4b49c8b7e 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts @@ -11,6 +11,16 @@ export interface PageSettings { 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. */ @@ -26,11 +36,15 @@ export interface PagedAsyncIterableIterator< /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 8872a9d4b2..a963d7ccdf 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -29,7 +29,17 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { */ 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. */ @@ -45,13 +55,17 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } ` ]); @@ -97,208 +111,287 @@ export function buildPagingHelpers( fileContent.addStatements([ ` - import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings - } from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse } from "@azure-rest/core-client"; - import { PageSettings, PagedAsyncIterableIterator } from "${pagingTypesPath}"; + import { ContinuablePage, PageSettings, PagedAsyncIterableIterator } from "${pagingTypesPath}"; - export function buildPagedAsyncIterator< + /** + * An interface that describes how to communicate with the service. + */ + interface PagedResult< TElement, - TResponse extends PathUncheckedResponse = PathUncheckedResponse - >( - client: Client, - getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise - ): PagedAsyncIterableIterator { - let firstRun = true; - let itemName: string, nextLinkName: string | undefined; - const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { - const result = - firstRun && pageLink === firstPageLinkPlaceholder - ? await getInitialResponse() - : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; + TPage = TElement[], + TPageSettings = 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) => unknown[]; + } + + /** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ + export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse + >( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise + ): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string) => { + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + 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 as PageSettings) ?? {}; + 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. + */ + + export function getPagedAsyncIterator( + pagedResult: PagedResult + ): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; + } + + async function* getItemAsyncIterator( + pagedResult: PagedResult + ): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // \`pages\` is of type \`AsyncIterableIterator\` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type \`AsyncIterableIterator\` so \`page\` is of type \`TPage\`. In this branch, + // it must be the case that \`TPage = TElement[]\` + yield* page as unknown as TElement[]; } - firstRun = false; - checkPagingRequest(result); - const results = await processResponseBody(result as TResponse); - const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); - return { - page: values, - nextPageLink: nextLink - }; - }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; - return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken - }) as any; - } - }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); - - return { - next() { - return iter.next(); - }, - [Symbol.asyncIterator]() { - return this; - }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; } - }; - } - - async function* getPageAsyncIterator( - pagedResult: PagedResult, - options: { - pageLink?: string; - } = {} - ): AsyncIterableIterator { - const { pageLink } = options; - let response = await pagedResult.getPage( - pageLink ?? pagedResult.firstPageLink - ); - if (!response) { - return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; - while (response.nextPageLink) { - response = await pagedResult.getPage(response.nextPageLink); + + async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} + ): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; - } - } - - /** - * 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") { - throw new Error( - \`Body Property \${nextLinkName} should be a string or 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[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn - if (!Array.isArray(value)) { - throw new Error( - \`Couldn't paginate response\n Body doesn't contain an array property with name: \${itemName}\` - ); + 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; + } } - - return value ?? []; - } - - /** - * Checks if a request failed - */ - function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226" - ]; - if (!Http2xxStatusCodes.includes(response.status)) { - throw createRestError( - \`Pagination failed with unexpected statusCode \${response.status}\`, - response - ); + + /** + * 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") { + throw new Error( + \`Body Property \${nextLinkName} should be a string or undefined\` + ); + } + + return nextLink; } - } - - /** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ - function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set([${nextLinkNamesStr}]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set([${itemNamesStr}]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; + + /** + * 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + \`Couldn't paginate response + Body doesn't contain an array property with name: \${itemName}\` + ); } + + return value ?? []; } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; + + /** + * Checks if a request failed + */ + function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + \`Pagination failed with unexpected statusCode \${response.status}\`, + response + ); } } - - if (!itemName) { - throw new Error( - \`Couldn't paginate response\n Body doesn't contain an array property with name: \${[ - ...itemNames - ].join(" OR ")}\` - ); + + /** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ + function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set([${nextLinkNamesStr}]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set([${itemNamesStr}]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + \`Couldn't paginate response + Body doesn't contain an array property with name: \${[...itemNames].join( + " OR " + )}\` + ); + } + + return { itemName, nextLinkName }; } - - return { itemName, nextLinkName }; - } + ` ]); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index a16eae414f..5393be6ffd 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -1,34 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings, -} from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; import { + ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ export function buildPagedAsyncIterator< TElement, + TPage = TElement[], + TPageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, processResponseBody: (result: TResponse) => Promise -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { + const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, getPage: async (pageLink: string) => { const result = @@ -44,22 +75,36 @@ export function buildPagedAsyncIterator< checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); + const values = getElements(results, itemName) as TPage; return { page: values, nextPageLink: nextLink, }; }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; + byPage: (settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, - }) as any; + }); }, }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); return { next() { return iter.next(); @@ -67,22 +112,52 @@ export function buildPagedAsyncIterator< [Symbol.asyncIterator]() { return this; }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { pageLink?: string; } = {} -): AsyncIterableIterator { +): AsyncIterableIterator> { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -90,15 +165,17 @@ async function* getPageAsyncIterator( if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; } } @@ -133,7 +210,7 @@ function getElements(body: unknown, itemName: string): T[] { if (!Array.isArray(value)) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + Body doesn't contain an array property with name: ${itemName}` ); } @@ -200,9 +277,9 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts index 52294d174d..3d48262604 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts @@ -16,5 +16,6 @@ export { DeleteOperationOptions, ExportOperationOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts index ad548f65f5..09fd9968e0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/index.ts @@ -12,4 +12,8 @@ export { DeleteOperationOptions, ExportOperationOptions, } from "./options.js"; -export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts index cba454057d..e4b49c8b7e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts @@ -11,6 +11,16 @@ export interface PageSettings { 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. */ @@ -26,11 +36,15 @@ export interface PagedAsyncIterableIterator< /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index a16eae414f..5393be6ffd 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -1,34 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - getPagedAsyncIterator, - PagedAsyncIterableIterator as CorePagedAsyncIterableIterator, - PagedResult, - PageSettings as CorePageSettings, -} from "@azure/core-paging"; import { Client, createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; import { + ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ export function buildPagedAsyncIterator< TElement, + TPage = TElement[], + TPageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, processResponseBody: (result: TResponse) => Promise -): PagedAsyncIterableIterator { +): PagedAsyncIterableIterator { let firstRun = true; let itemName: string, nextLinkName: string | undefined; const firstPageLinkPlaceholder = ""; - const pagedResult: PagedResult = { + const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, getPage: async (pageLink: string) => { const result = @@ -44,22 +75,36 @@ export function buildPagedAsyncIterator< checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); - const values = getElements(results, itemName); + const values = getElements(results, itemName) as TPage; return { page: values, nextPageLink: nextLink, }; }, - byPage: (settings?: PageSettings) => { - const { continuationToken } = settings ?? {}; + byPage: (settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, - }) as any; + }); }, }; - const iter: CorePagedAsyncIterableIterator = - getPagedAsyncIterator(pagedResult); + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); return { next() { return iter.next(); @@ -67,22 +112,52 @@ export function buildPagedAsyncIterator< [Symbol.asyncIterator]() { return this; }, - byPage: (settings?: PageSettings) => { - return iter.byPage( - settings as CorePageSettings - ) as unknown as AsyncIterableIterator< - TElement[] & { continuationToken?: string } - >; - }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), }; } -async function* getPageAsyncIterator( - pagedResult: PagedResult, +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, options: { pageLink?: string; } = {} -): AsyncIterableIterator { +): AsyncIterableIterator> { const { pageLink } = options; let response = await pagedResult.getPage( pageLink ?? pagedResult.firstPageLink @@ -90,15 +165,17 @@ async function* getPageAsyncIterator( if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; while (response.nextPageLink) { response = await pagedResult.getPage(response.nextPageLink); if (!response) { return; } - (response.page as any).continuationToken = response.nextPageLink; - yield response.page as any; + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; } } @@ -133,7 +210,7 @@ function getElements(body: unknown, itemName: string): T[] { if (!Array.isArray(value)) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + Body doesn't contain an array property with name: ${itemName}` ); } @@ -200,9 +277,9 @@ function getPaginationProperties(initialResponse: PathUncheckedResponse) { if (!itemName) { throw new Error( `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts index 257d09fd2f..9107e55f0e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/index.ts @@ -7,5 +7,6 @@ export { User, ListOptions, PageSettings, + ContinuablePage, PagedAsyncIterableIterator, } from "./models/index.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts index 332c7bf5e5..5bffc4d5ff 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/index.ts @@ -3,4 +3,8 @@ export { PagedUser, User } from "./models.js"; export { ListOptions } from "./options.js"; -export { PageSettings, PagedAsyncIterableIterator } from "./pagingTypes.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts index cba454057d..e4b49c8b7e 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts @@ -11,6 +11,16 @@ export interface PageSettings { 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. */ @@ -26,11 +36,15 @@ export interface PagedAsyncIterableIterator< /** * The connection to the async iterator, part of the iteration protocol */ - [Symbol.asyncIterator](): PagedAsyncIterableIterator; + [Symbol.asyncIterator](): PagedAsyncIterableIterator< + TElement, + TPage, + TPageSettings + >; /** * Return an AsyncIterableIterator that works a page at a time */ byPage: ( settings?: TPageSettings - ) => AsyncIterableIterator; + ) => AsyncIterableIterator>; } From e090a70ee4e095a9f23cf89087e7d7446f907a1c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 16:27:38 +0800 Subject: [PATCH 44/60] Update the paging cases in widget_dpg.api --- .../generated/typespec-ts/package.json | 1 + .../typespec-ts/review/widget_dpg.api.md | 29 ++ .../generated/src/api/pagingHelpers.ts | 287 ++++++++++++++++++ .../generated/src/api/widgets/index.ts | 52 ++++ .../generated/src/classic/widgets/index.ts | 13 + .../sources/generated/src/index.ts | 5 + .../sources/generated/src/models/index.ts | 14 +- .../sources/generated/src/models/models.ts | 7 + .../sources/generated/src/models/options.ts | 2 + .../generated/src/models/pagingTypes.ts | 50 +++ .../generated/src/rest/clientDefinitions.ts | 13 + .../sources/generated/src/rest/index.ts | 1 + .../generated/src/rest/isUnexpected.ts | 9 + .../generated/src/rest/outputModels.ts | 7 + .../generated/src/rest/paginateHelper.ts | 204 +++++++++++++ .../sources/generated/src/rest/parameters.ts | 12 + .../sources/generated/src/rest/responses.ts | 12 + .../typespec-ts/src/api/pagingHelpers.ts | 287 ++++++++++++++++++ .../typespec-ts/src/api/widgets/index.ts | 52 ++++ .../typespec-ts/src/classic/widgets/index.ts | 13 + .../generated/typespec-ts/src/index.ts | 5 + .../generated/typespec-ts/src/models/index.ts | 14 +- .../typespec-ts/src/models/models.ts | 7 + .../typespec-ts/src/models/options.ts | 2 + .../typespec-ts/src/models/pagingTypes.ts | 50 +++ .../typespec-ts/src/rest/clientDefinitions.ts | 13 + .../generated/typespec-ts/src/rest/index.ts | 1 + .../typespec-ts/src/rest/isUnexpected.ts | 9 + .../typespec-ts/src/rest/outputModels.ts | 7 + .../typespec-ts/src/rest/paginateHelper.ts | 204 +++++++++++++ .../typespec-ts/src/rest/parameters.ts | 12 + .../typespec-ts/src/rest/responses.ts | 12 + .../test/widget_dpg/spec/main.tsp | 19 ++ 33 files changed, 1423 insertions(+), 2 deletions(-) create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/paginateHelper.ts create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts create mode 100644 packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/paginateHelper.ts 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 97da0a213b..3eb566dba3 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 @@ -76,6 +76,7 @@ "@azure/core-rest-pipeline": "^1.12.0", "@azure/logger": "^1.0.0", "tslib": "^2.2.0", + "@azure/core-paging": "^1.5.0", "@azure/core-util": "^1.4.0" }, "devDependencies": { 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 59b244add6..90e5754f3a 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 @@ -14,12 +14,35 @@ export interface AnalyzeResult { summary: string; } +// @public +export type ContinuablePage = TPage & { + continuationToken?: string; +}; + // @public (undocumented) export interface CreateWidget { color: "red" | "blue"; weight: number; } +// @public (undocumented) +export interface ListWidgetsPagesResults { + "odata.nextLink"?: string; + results: Widget[]; +} + +// @public +export interface PagedAsyncIterableIterator { + [Symbol.asyncIterator](): PagedAsyncIterableIterator; + byPage: (settings?: TPageSettings) => AsyncIterableIterator>; + next(): Promise>; +} + +// @public +export interface PageSettings { + continuationToken?: string; +} + // @public (undocumented) export interface UpdateWidget { color?: "red" | "blue"; @@ -72,6 +95,10 @@ export interface WidgetsListWidgetsOptions extends OperationOptions { optionalHeader?: string; } +// @public (undocumented) +export interface WidgetsListWidgetsPagesOptions extends OperationOptions { +} + // @public (undocumented) export interface WidgetsOperations { // (undocumented) @@ -85,6 +112,8 @@ export interface WidgetsOperations { // (undocumented) listWidgets: (requiredHeader: string, bytesHeader: Uint8Array, value: Uint8Array, csvArrayHeader: Uint8Array[], utcDateHeader: Date, options?: WidgetsListWidgetsOptions) => Promise; // (undocumented) + listWidgetsPages: (page: number, pageSize: number, options?: WidgetsListWidgetsPagesOptions) => PagedAsyncIterableIterator; + // (undocumented) updateWidget: (id: string, body: UpdateWidget, options?: WidgetsUpdateWidgetOptions) => Promise; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts new file mode 100644 index 0000000000..d0c752d811 --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { + ContinuablePage, + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; + +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string) => { + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + 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 as PageSettings) ?? {}; + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items", "results"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` + ); + } + + return { itemName, nextLinkName }; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts index 31355e0f5f..43f05e437d 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts @@ -3,10 +3,13 @@ import { Widget, + ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, } from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "../pagingHelpers.js"; import { AnalyzeWidget200Response, AnalyzeWidgetDefaultResponse, @@ -20,6 +23,8 @@ import { isUnexpected, ListWidgets200Response, ListWidgetsDefaultResponse, + ListWidgetsPages200Response, + ListWidgetsPagesDefaultResponse, UpdateWidget200Response, UpdateWidgetDefaultResponse, WidgetServiceContext as Client, @@ -31,6 +36,7 @@ import { import { uint8ArrayToString } from "@azure/core-util"; import { WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, @@ -125,6 +131,52 @@ export async function listWidgets( return _listWidgetsDeserialize(result); } +export function _listWidgetsPagesSend( + context: Client, + page: number, + pageSize: number, + options: WidgetsListWidgetsPagesOptions = { requestOptions: {} } +): StreamableMethod< + ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse +> { + return context + .path("/widgets/widgets/pages") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { page: page, pageSize: pageSize }, + }); +} + +export async function _listWidgetsPagesDeserialize( + result: ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + results: result.body["results"].map((p) => ({ + id: p["id"], + weight: p["weight"], + color: p["color"] as any, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +export function listWidgetsPages( + context: Client, + page: number, + pageSize: number, + options: WidgetsListWidgetsPagesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listWidgetsPagesSend(context, page, pageSize, options), + _listWidgetsPagesDeserialize + ); +} + export function _getWidgetSend( context: Client, id: string, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts index 25cc81248f..c5908f19a5 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts @@ -10,6 +10,7 @@ import { } from "../../models/models.js"; import { listWidgets, + listWidgetsPages, getWidget, createWidget, updateWidget, @@ -18,12 +19,14 @@ import { } from "../../api/widgets/index.js"; import { WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, } from "../../models/options.js"; +import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; export interface WidgetsOperations { listWidgets: ( @@ -34,6 +37,11 @@ export interface WidgetsOperations { utcDateHeader: Date, options?: WidgetsListWidgetsOptions ) => Promise; + listWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsListWidgetsPagesOptions + ) => PagedAsyncIterableIterator; getWidget: (id: string, options?: WidgetsGetWidgetOptions) => Promise; createWidget: ( body: CreateWidget, @@ -73,6 +81,11 @@ export function getWidgets(context: WidgetServiceContext) { utcDateHeader, options ), + listWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsListWidgetsPagesOptions + ) => listWidgetsPages(context, page, pageSize, options), getWidget: (id: string, options?: WidgetsGetWidgetOptions) => getWidget(context, id, options), createWidget: (body: CreateWidget, options?: WidgetsCreateWidgetOptions) => diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts index 373189b51d..48aa7ef5fa 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts @@ -7,14 +7,19 @@ export { } from "./WidgetServiceClient.js"; export { Widget, + ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, } from "./models/index.js"; export { WidgetsOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts index 10a2c0c468..135b146744 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts @@ -1,12 +1,24 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -export { Widget, CreateWidget, UpdateWidget, AnalyzeResult } from "./models.js"; +export { + Widget, + ListWidgetsPagesResults, + CreateWidget, + UpdateWidget, + AnalyzeResult, +} from "./models.js"; export { WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, } from "./options.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/models.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/models.ts index 77cc3a2a8c..3a9d7d54db 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/models.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/models.ts @@ -10,6 +10,13 @@ export interface Widget { color: "red" | "blue"; } +export interface ListWidgetsPagesResults { + /** The current page of results. */ + results: Widget[]; + /** The URL to get the next set of results. */ + "odata.nextLink"?: string; +} + export interface CreateWidget { /** The weight of the widget. This is an int32, but must be greater than zero. */ weight: number; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts index 6268816de1..e2e3385172 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts @@ -10,6 +10,8 @@ export interface WidgetsListWidgetsOptions extends OperationOptions { nullableDateHeader?: Date | null; } +export interface WidgetsListWidgetsPagesOptions extends OperationOptions {} + export interface WidgetsGetWidgetOptions extends OperationOptions {} export interface WidgetsCreateWidgetOptions extends OperationOptions {} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts new file mode 100644 index 0000000000..e4b49c8b7e --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** + * An interface that tracks the settings for paged iteration + */ +export interface PageSettings { + /** + * The token that keeps track of where to continue the iterator + */ + 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 = 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>; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts index 4ae0b111ed..84536d620c 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts @@ -4,6 +4,7 @@ import { ListWidgetsParameters, CreateWidgetParameters, + ListWidgetsPagesParameters, GetWidgetParameters, UpdateWidgetParameters, DeleteWidgetParameters, @@ -14,6 +15,8 @@ import { ListWidgetsDefaultResponse, CreateWidget201Response, CreateWidgetDefaultResponse, + ListWidgetsPages200Response, + ListWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -45,6 +48,14 @@ export interface ListWidgets { ): StreamableMethod; } +export interface ListWidgetsPages { + get( + options: ListWidgetsPagesParameters + ): StreamableMethod< + ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse + >; +} + export interface GetWidget { /** Get a widget by ID. */ get( @@ -73,6 +84,8 @@ export interface AnalyzeWidget { export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): ListWidgets; + /** Resource for '/widgets/widgets/pages' has methods for the following verbs: get */ + (path: "/widgets/widgets/pages"): ListWidgetsPages; /** Resource for '/widgets/\{id\}' has methods for the following verbs: get, patch, delete */ (path: "/widgets/{id}", id: string): GetWidget; /** Resource for '/widgets/\{id\}/analyze' has methods for the following verbs: post */ diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/index.ts index ae9a8b1539..6a101accd4 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/index.ts @@ -10,6 +10,7 @@ export * from "./clientDefinitions.js"; export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; +export * from "./paginateHelper.js"; export * from "./serializeHelper.js"; export default WidgetServiceClient; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts index 5707c6381d..783190f740 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts @@ -6,6 +6,8 @@ import { ListWidgetsDefaultResponse, CreateWidget201Response, CreateWidgetDefaultResponse, + ListWidgetsPages200Response, + ListWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -19,6 +21,7 @@ import { const responseMap: Record = { "GET /widgets": ["200"], "POST /widgets": ["201"], + "GET /widgets/widgets/pages": ["200"], "GET /widgets/{id}": ["200"], "PATCH /widgets/{id}": ["200"], "DELETE /widgets/{id}": ["204"], @@ -31,6 +34,9 @@ export function isUnexpected( export function isUnexpected( response: CreateWidget201Response | CreateWidgetDefaultResponse ): response is CreateWidgetDefaultResponse; +export function isUnexpected( + response: ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse +): response is ListWidgetsPagesDefaultResponse; export function isUnexpected( response: GetWidget200Response | GetWidgetDefaultResponse ): response is GetWidgetDefaultResponse; @@ -49,6 +55,8 @@ export function isUnexpected( | ListWidgetsDefaultResponse | CreateWidget201Response | CreateWidgetDefaultResponse + | ListWidgetsPages200Response + | ListWidgetsPagesDefaultResponse | GetWidget200Response | GetWidgetDefaultResponse | UpdateWidget200Response @@ -60,6 +68,7 @@ export function isUnexpected( ): response is | ListWidgetsDefaultResponse | CreateWidgetDefaultResponse + | ListWidgetsPagesDefaultResponse | GetWidgetDefaultResponse | UpdateWidgetDefaultResponse | DeleteWidgetDefaultResponse diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/outputModels.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/outputModels.ts index 9df9238a04..43e9648f37 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/outputModels.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/outputModels.ts @@ -17,6 +17,13 @@ export interface WidgetErrorOutput { message: string; } +export interface ListWidgetsPagesResultsOutput { + /** The current page of results. */ + results: Array; + /** The URL to get the next set of results. */ + "odata.nextLink"?: string; +} + export interface AnalyzeResultOutput { summary: string; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/paginateHelper.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/paginateHelper.ts new file mode 100644 index 0000000000..bea7a77a07 --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/paginateHelper.ts @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = ( + pageLink: string, + maxPageSize?: number +) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { results?: infer TPage }; + } + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {} +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + // We need to check the response for success before trying to inspect it looking for + // the properties to use for nextLink and itemName + checkPagingRequest(initialResponse); + const { itemName, nextLinkName } = getPaginationProperties(initialResponse); + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "results"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts index 7db3c5c9a8..30b85fb0ae 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts @@ -23,6 +23,18 @@ export interface ListWidgetsHeaderParam { } export type ListWidgetsParameters = ListWidgetsHeaderParam & RequestParameters; + +export interface ListWidgetsPagesQueryParamProperties { + page: number; + pageSize: number; +} + +export interface ListWidgetsPagesQueryParam { + queryParameters: ListWidgetsPagesQueryParamProperties; +} + +export type ListWidgetsPagesParameters = ListWidgetsPagesQueryParam & + RequestParameters; export type GetWidgetParameters = RequestParameters; export interface CreateWidgetBodyParam { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts index d7da1e8ace..c84b098dd5 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts @@ -5,6 +5,7 @@ import { HttpResponse } from "@azure-rest/core-client"; import { WidgetOutput, WidgetErrorOutput, + ListWidgetsPagesResultsOutput, AnalyzeResultOutput, } from "./outputModels.js"; @@ -19,6 +20,17 @@ export interface ListWidgetsDefaultResponse extends HttpResponse { body: WidgetErrorOutput; } +/** The request has succeeded. */ +export interface ListWidgetsPages200Response extends HttpResponse { + status: "200"; + body: ListWidgetsPagesResultsOutput; +} + +export interface ListWidgetsPagesDefaultResponse extends HttpResponse { + status: string; + body: WidgetErrorOutput; +} + /** The request has succeeded. */ export interface GetWidget200Response extends HttpResponse { status: "200"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts new file mode 100644 index 0000000000..d0c752d811 --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -0,0 +1,287 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; +import { + ContinuablePage, + PageSettings, + PagedAsyncIterableIterator, +} from "../models/pagingTypes.js"; + +/** + * An interface that describes how to communicate with the service. + */ +interface PagedResult< + TElement, + TPage = TElement[], + TPageSettings = 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) => unknown[]; +} + +/** + * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator + */ +export function buildPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings = PageSettings, + TResponse extends PathUncheckedResponse = PathUncheckedResponse +>( + client: Client, + getInitialResponse: () => PromiseLike, + processResponseBody: (result: TResponse) => Promise +): PagedAsyncIterableIterator { + let firstRun = true; + let itemName: string, nextLinkName: string | undefined; + const firstPageLinkPlaceholder = ""; + const pagedResult: PagedResult = { + firstPageLink: firstPageLinkPlaceholder, + getPage: async (pageLink: string) => { + const result = + firstRun && pageLink === firstPageLinkPlaceholder + ? await getInitialResponse() + : await client.pathUnchecked(pageLink).get(); + if (firstRun) { + const pageInfo = getPaginationProperties(result); + itemName = pageInfo.itemName; + nextLinkName = pageInfo.nextLinkName; + } + firstRun = false; + checkPagingRequest(result); + 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 as PageSettings) ?? {}; + 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. + */ + +export function getPagedAsyncIterator( + pagedResult: PagedResult +): PagedAsyncIterableIterator { + const iter = getItemAsyncIterator( + pagedResult + ); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: + pagedResult?.byPage ?? + ((settings?: TPageSettings) => { + const { continuationToken } = (settings as PageSettings) ?? {}; + return getPageAsyncIterator(pagedResult, { + pageLink: continuationToken, + }); + }), + }; +} + +async function* getItemAsyncIterator( + pagedResult: PagedResult +): AsyncIterableIterator { + const pages = getPageAsyncIterator(pagedResult); + const firstVal = await pages.next(); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + // can extract elements from this page + const { toElements } = pagedResult; + if (toElements) { + yield* toElements(firstVal.value) as TElement[]; + for await (const page of pages) { + yield* toElements(page) as TElement[]; + } + } else { + yield firstVal.value; + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield* pages as unknown as AsyncIterableIterator; + } + } else { + yield* firstVal.value; + for await (const page of pages) { + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield* page as unknown as TElement[]; + } + } +} + +async function* getPageAsyncIterator( + pagedResult: PagedResult, + options: { + pageLink?: string; + } = {} +): AsyncIterableIterator> { + const { pageLink } = options; + let response = await pagedResult.getPage( + pageLink ?? pagedResult.firstPageLink + ); + if (!response) { + return; + } + let result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + while (response.nextPageLink) { + response = await pagedResult.getPage(response.nextPageLink); + if (!response) { + return; + } + result = response.page as ContinuablePage; + result.continuationToken = response.nextPageLink; + yield result; + } +} + +/** + * Gets for the value of nextLink in the body + */ +function getNextLink(body: unknown, nextLinkName?: string): string | undefined { + if (!nextLinkName) { + return undefined; + } + + const nextLink = (body as Record)[nextLinkName]; + + if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `Couldn't paginate response + Body doesn't contain an array property with name: ${itemName}` + ); + } + + return value ?? []; +} + +/** + * Checks if a request failed + */ +function checkPagingRequest(response: PathUncheckedResponse): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "items", "results"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response + Body doesn't contain an array property with name: ${[...itemNames].join( + " OR " + )}` + ); + } + + return { itemName, nextLinkName }; +} 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 31355e0f5f..43f05e437d 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 @@ -3,10 +3,13 @@ import { Widget, + ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, } from "../../models/models.js"; +import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "../pagingHelpers.js"; import { AnalyzeWidget200Response, AnalyzeWidgetDefaultResponse, @@ -20,6 +23,8 @@ import { isUnexpected, ListWidgets200Response, ListWidgetsDefaultResponse, + ListWidgetsPages200Response, + ListWidgetsPagesDefaultResponse, UpdateWidget200Response, UpdateWidgetDefaultResponse, WidgetServiceContext as Client, @@ -31,6 +36,7 @@ import { import { uint8ArrayToString } from "@azure/core-util"; import { WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, @@ -125,6 +131,52 @@ export async function listWidgets( return _listWidgetsDeserialize(result); } +export function _listWidgetsPagesSend( + context: Client, + page: number, + pageSize: number, + options: WidgetsListWidgetsPagesOptions = { requestOptions: {} } +): StreamableMethod< + ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse +> { + return context + .path("/widgets/widgets/pages") + .get({ + ...operationOptionsToRequestParameters(options), + queryParameters: { page: page, pageSize: pageSize }, + }); +} + +export async function _listWidgetsPagesDeserialize( + result: ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + results: result.body["results"].map((p) => ({ + id: p["id"], + weight: p["weight"], + color: p["color"] as any, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +export function listWidgetsPages( + context: Client, + page: number, + pageSize: number, + options: WidgetsListWidgetsPagesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listWidgetsPagesSend(context, page, pageSize, options), + _listWidgetsPagesDeserialize + ); +} + export function _getWidgetSend( context: Client, id: string, 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 25cc81248f..c5908f19a5 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 @@ -10,6 +10,7 @@ import { } from "../../models/models.js"; import { listWidgets, + listWidgetsPages, getWidget, createWidget, updateWidget, @@ -18,12 +19,14 @@ import { } from "../../api/widgets/index.js"; import { WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, } from "../../models/options.js"; +import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; export interface WidgetsOperations { listWidgets: ( @@ -34,6 +37,11 @@ export interface WidgetsOperations { utcDateHeader: Date, options?: WidgetsListWidgetsOptions ) => Promise; + listWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsListWidgetsPagesOptions + ) => PagedAsyncIterableIterator; getWidget: (id: string, options?: WidgetsGetWidgetOptions) => Promise; createWidget: ( body: CreateWidget, @@ -73,6 +81,11 @@ export function getWidgets(context: WidgetServiceContext) { utcDateHeader, options ), + listWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsListWidgetsPagesOptions + ) => listWidgetsPages(context, page, pageSize, options), getWidget: (id: string, options?: WidgetsGetWidgetOptions) => getWidget(context, id, options), createWidget: (body: CreateWidget, options?: WidgetsCreateWidgetOptions) => 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 373189b51d..48aa7ef5fa 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 @@ -7,14 +7,19 @@ export { } from "./WidgetServiceClient.js"; export { Widget, + ListWidgetsPagesResults, CreateWidget, UpdateWidget, AnalyzeResult, WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, } from "./models/index.js"; export { WidgetsOperations } from "./classic/index.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts index 10a2c0c468..135b146744 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts @@ -1,12 +1,24 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -export { Widget, CreateWidget, UpdateWidget, AnalyzeResult } from "./models.js"; +export { + Widget, + ListWidgetsPagesResults, + CreateWidget, + UpdateWidget, + AnalyzeResult, +} from "./models.js"; export { WidgetsListWidgetsOptions, + WidgetsListWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, } from "./options.js"; +export { + PageSettings, + ContinuablePage, + PagedAsyncIterableIterator, +} from "./pagingTypes.js"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts index 77cc3a2a8c..3a9d7d54db 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/models.ts @@ -10,6 +10,13 @@ export interface Widget { color: "red" | "blue"; } +export interface ListWidgetsPagesResults { + /** The current page of results. */ + results: Widget[]; + /** The URL to get the next set of results. */ + "odata.nextLink"?: string; +} + export interface CreateWidget { /** The weight of the widget. This is an int32, but must be greater than zero. */ weight: number; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts index 6268816de1..e2e3385172 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts @@ -10,6 +10,8 @@ export interface WidgetsListWidgetsOptions extends OperationOptions { nullableDateHeader?: Date | null; } +export interface WidgetsListWidgetsPagesOptions extends OperationOptions {} + export interface WidgetsGetWidgetOptions extends OperationOptions {} export interface WidgetsCreateWidgetOptions extends OperationOptions {} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts new file mode 100644 index 0000000000..e4b49c8b7e --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +/** + * An interface that tracks the settings for paged iteration + */ +export interface PageSettings { + /** + * The token that keeps track of where to continue the iterator + */ + 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 = 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>; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts index 4ae0b111ed..84536d620c 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -4,6 +4,7 @@ import { ListWidgetsParameters, CreateWidgetParameters, + ListWidgetsPagesParameters, GetWidgetParameters, UpdateWidgetParameters, DeleteWidgetParameters, @@ -14,6 +15,8 @@ import { ListWidgetsDefaultResponse, CreateWidget201Response, CreateWidgetDefaultResponse, + ListWidgetsPages200Response, + ListWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -45,6 +48,14 @@ export interface ListWidgets { ): StreamableMethod; } +export interface ListWidgetsPages { + get( + options: ListWidgetsPagesParameters + ): StreamableMethod< + ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse + >; +} + export interface GetWidget { /** Get a widget by ID. */ get( @@ -73,6 +84,8 @@ export interface AnalyzeWidget { export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): ListWidgets; + /** Resource for '/widgets/widgets/pages' has methods for the following verbs: get */ + (path: "/widgets/widgets/pages"): ListWidgetsPages; /** Resource for '/widgets/\{id\}' has methods for the following verbs: get, patch, delete */ (path: "/widgets/{id}", id: string): GetWidget; /** Resource for '/widgets/\{id\}/analyze' has methods for the following verbs: post */ diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/index.ts index ae9a8b1539..6a101accd4 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/index.ts @@ -10,6 +10,7 @@ export * from "./clientDefinitions.js"; export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; +export * from "./paginateHelper.js"; export * from "./serializeHelper.js"; export default WidgetServiceClient; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts index 5707c6381d..783190f740 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts @@ -6,6 +6,8 @@ import { ListWidgetsDefaultResponse, CreateWidget201Response, CreateWidgetDefaultResponse, + ListWidgetsPages200Response, + ListWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -19,6 +21,7 @@ import { const responseMap: Record = { "GET /widgets": ["200"], "POST /widgets": ["201"], + "GET /widgets/widgets/pages": ["200"], "GET /widgets/{id}": ["200"], "PATCH /widgets/{id}": ["200"], "DELETE /widgets/{id}": ["204"], @@ -31,6 +34,9 @@ export function isUnexpected( export function isUnexpected( response: CreateWidget201Response | CreateWidgetDefaultResponse ): response is CreateWidgetDefaultResponse; +export function isUnexpected( + response: ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse +): response is ListWidgetsPagesDefaultResponse; export function isUnexpected( response: GetWidget200Response | GetWidgetDefaultResponse ): response is GetWidgetDefaultResponse; @@ -49,6 +55,8 @@ export function isUnexpected( | ListWidgetsDefaultResponse | CreateWidget201Response | CreateWidgetDefaultResponse + | ListWidgetsPages200Response + | ListWidgetsPagesDefaultResponse | GetWidget200Response | GetWidgetDefaultResponse | UpdateWidget200Response @@ -60,6 +68,7 @@ export function isUnexpected( ): response is | ListWidgetsDefaultResponse | CreateWidgetDefaultResponse + | ListWidgetsPagesDefaultResponse | GetWidgetDefaultResponse | UpdateWidgetDefaultResponse | DeleteWidgetDefaultResponse diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/outputModels.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/outputModels.ts index 9df9238a04..43e9648f37 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/outputModels.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/outputModels.ts @@ -17,6 +17,13 @@ export interface WidgetErrorOutput { message: string; } +export interface ListWidgetsPagesResultsOutput { + /** The current page of results. */ + results: Array; + /** The URL to get the next set of results. */ + "odata.nextLink"?: string; +} + export interface AnalyzeResultOutput { summary: string; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/paginateHelper.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/paginateHelper.ts new file mode 100644 index 0000000000..bea7a77a07 --- /dev/null +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/paginateHelper.ts @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + getPagedAsyncIterator, + PagedAsyncIterableIterator, + PagedResult, +} from "@azure/core-paging"; +import { + Client, + createRestError, + PathUncheckedResponse, +} from "@azure-rest/core-client"; + +/** + * Helper type to extract the type of an array + */ +export type GetArrayType = T extends Array ? TData : never; + +/** + * The type of a custom function that defines how to get a page and a link to the next one if any. + */ +export type GetPage = ( + pageLink: string, + maxPageSize?: number +) => Promise<{ + page: TPage; + nextPageLink?: string; +}>; + +/** + * Options for the paging helper + */ +export interface PagingOptions { + /** + * Custom function to extract pagination details for crating the PagedAsyncIterableIterator + */ + customGetPage?: GetPage[]>; +} + +/** + * Helper type to infer the Type of the paged elements from the response type + * This type is generated based on the swagger information for x-ms-pageable + * specifically on the itemName property which indicates the property of the response + * where the page items are found. The default value is `value`. + * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter + */ +export type PaginateReturn = TResult extends + | { + body: { value?: infer TPage }; + } + | { + body: { results?: infer TPage }; + } + ? GetArrayType + : Array; + +/** + * Helper to paginate results from an initial response that follows the specification of Autorest `x-ms-pageable` extension + * @param client - Client to use for sending the next page requests + * @param initialResponse - Initial response containing the nextLink and current page of elements + * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results + * @returns - PagedAsyncIterableIterator to iterate the elements + */ +export function paginate( + client: Client, + initialResponse: TResponse, + options: PagingOptions = {} +): PagedAsyncIterableIterator> { + // Extract element type from initial response + type TElement = PaginateReturn; + let firstRun = true; + // We need to check the response for success before trying to inspect it looking for + // the properties to use for nextLink and itemName + checkPagingRequest(initialResponse); + const { itemName, nextLinkName } = getPaginationProperties(initialResponse); + const { customGetPage } = options; + const pagedResult: PagedResult = { + firstPageLink: "", + getPage: + typeof customGetPage === "function" + ? customGetPage + : async (pageLink: string) => { + const result = firstRun + ? initialResponse + : await client.pathUnchecked(pageLink).get(); + firstRun = false; + checkPagingRequest(result); + const nextLink = getNextLink(result.body, nextLinkName); + const values = getElements(result.body, itemName); + return { + page: values, + nextPageLink: nextLink, + }; + }, + }; + + return getPagedAsyncIterator(pagedResult); +} + +/** + * 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") { + throw new Error( + `Body Property ${nextLinkName} should be a string or 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[]; + + // value has to be an array according to the x-ms-pageable extension. + // The fact that this must be an array is used above to calculate the + // type of elements in the page in PaginateReturn + if (!Array.isArray(value)) { + throw new Error( + `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): void { + const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + `Pagination failed with unexpected statusCode ${response.status}`, + response + ); + } +} + +/** + * Extracts the itemName and nextLinkName from the initial response to use them for pagination + */ +function getPaginationProperties(initialResponse: PathUncheckedResponse) { + // Build a set with the passed custom nextLinkNames + const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); + + // Build a set with the passed custom set of itemNames + const itemNames = new Set(["value", "results"]); + + let nextLinkName: string | undefined; + let itemName: string | undefined; + + for (const name of nextLinkNames) { + const nextLink = (initialResponse.body as Record)[ + name + ] as string; + if (nextLink) { + nextLinkName = name; + break; + } + } + + for (const name of itemNames) { + const item = (initialResponse.body as Record)[ + name + ] as string; + if (item) { + itemName = name; + break; + } + } + + if (!itemName) { + throw new Error( + `Couldn't paginate response\n Body doesn't contain an array property with name: ${[ + ...itemNames, + ].join(" OR ")}` + ); + } + + return { itemName, nextLinkName }; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts index 7db3c5c9a8..30b85fb0ae 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts @@ -23,6 +23,18 @@ export interface ListWidgetsHeaderParam { } export type ListWidgetsParameters = ListWidgetsHeaderParam & RequestParameters; + +export interface ListWidgetsPagesQueryParamProperties { + page: number; + pageSize: number; +} + +export interface ListWidgetsPagesQueryParam { + queryParameters: ListWidgetsPagesQueryParamProperties; +} + +export type ListWidgetsPagesParameters = ListWidgetsPagesQueryParam & + RequestParameters; export type GetWidgetParameters = RequestParameters; export interface CreateWidgetBodyParam { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts index d7da1e8ace..c84b098dd5 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts @@ -5,6 +5,7 @@ import { HttpResponse } from "@azure-rest/core-client"; import { WidgetOutput, WidgetErrorOutput, + ListWidgetsPagesResultsOutput, AnalyzeResultOutput, } from "./outputModels.js"; @@ -19,6 +20,17 @@ export interface ListWidgetsDefaultResponse extends HttpResponse { body: WidgetErrorOutput; } +/** The request has succeeded. */ +export interface ListWidgetsPages200Response extends HttpResponse { + status: "200"; + body: ListWidgetsPagesResultsOutput; +} + +export interface ListWidgetsPagesDefaultResponse extends HttpResponse { + status: string; + body: WidgetErrorOutput; +} + /** The request has succeeded. */ export interface GetWidget200Response extends HttpResponse { status: "200"; diff --git a/packages/typespec-test/test/widget_dpg/spec/main.tsp b/packages/typespec-test/test/widget_dpg/spec/main.tsp index 118d2ca661..efea8b2bd1 100644 --- a/packages/typespec-test/test/widget_dpg/spec/main.tsp +++ b/packages/typespec-test/test/widget_dpg/spec/main.tsp @@ -1,6 +1,8 @@ import "@typespec/http"; +import "@azure-tools/typespec-azure-core"; using TypeSpec.Http; +using Azure.Core; @service({ title: "Widget Service", version: "1.0.0", @@ -48,6 +50,16 @@ model WidgetError { message: string; } +@pagedResult +model ListWidgetsPagesResults { + @doc("The current page of results.") + @items + results: Widget[]; + @doc("The URL to get the next set of results.") + @nextLink + `odata.nextLink`?: string; +} + @route("/widgets") @tag("Widgets") interface Widgets { @@ -72,6 +84,13 @@ It does not accept any options or parameters. @header nullableDateHeader?: utcDateTime | null, ): Widget[] | WidgetError; + @get + @route("/widgets/pages") + listWidgetsPages( + @query page: int32, + @query pageSize: int32, + ): ListWidgetsPagesResults | WidgetError; + @doc("Get a widget by ID.") @get getWidget(@path id: string): Widget | WidgetError; From f8cf5a30817fc9278987410fdf1e7c490c0547b9 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 18:26:08 +0800 Subject: [PATCH 45/60] Resolve some comments --- .../typespec-ts/review/widget_dpg.api.md | 6 + .../generated/src/api/pagingHelpers.ts | 85 +++--------- .../generated/src/api/widgets/index.ts | 53 ++++++- .../generated/src/classic/widgets/index.ts | 14 +- .../sources/generated/src/index.ts | 1 + .../sources/generated/src/models/index.ts | 1 + .../sources/generated/src/models/options.ts | 2 + .../generated/src/rest/clientDefinitions.ts | 10 +- .../generated/src/rest/isUnexpected.ts | 9 ++ .../sources/generated/src/rest/parameters.ts | 12 ++ .../sources/generated/src/rest/responses.ts | 11 ++ .../typespec-ts/src/api/pagingHelpers.ts | 85 +++--------- .../typespec-ts/src/api/widgets/index.ts | 53 ++++++- .../typespec-ts/src/classic/widgets/index.ts | 14 +- .../generated/typespec-ts/src/index.ts | 1 + .../generated/typespec-ts/src/models/index.ts | 1 + .../typespec-ts/src/models/options.ts | 2 + .../typespec-ts/src/rest/clientDefinitions.ts | 10 +- .../typespec-ts/src/rest/isUnexpected.ts | 9 ++ .../typespec-ts/src/rest/parameters.ts | 12 ++ .../typespec-ts/src/rest/responses.ts | 11 ++ .../test/widget_dpg/spec/main.tsp | 7 + packages/typespec-ts/src/index.ts | 10 +- .../modular/buildClassicalOperationGroups.ts | 18 ++- .../typespec-ts/src/modular/buildCodeModel.ts | 7 +- .../src/modular/buildOperations.ts | 2 +- .../src/modular/buildPagingFiles.ts | 130 +++++++----------- .../src/modular/helpers/operationHelpers.ts | 16 ++- .../azure/core/src/api/operations.ts | 9 +- .../azure/core/src/api/pagingHelpers.ts | 85 +++--------- .../payload/pageable/src/api/operations.ts | 3 +- .../payload/pageable/src/api/pagingHelpers.ts | 70 ++-------- 32 files changed, 403 insertions(+), 356 deletions(-) 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 90e5754f3a..addf234456 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 @@ -114,9 +114,15 @@ export interface WidgetsOperations { // (undocumented) listWidgetsPages: (page: number, pageSize: number, options?: WidgetsListWidgetsPagesOptions) => PagedAsyncIterableIterator; // (undocumented) + queryWidgetsPages: (page: number, pageSize: number, options?: WidgetsQueryWidgetsPagesOptions) => PagedAsyncIterableIterator; + // (undocumented) updateWidget: (id: string, body: UpdateWidget, options?: WidgetsUpdateWidgetOptions) => Promise; } +// @public (undocumented) +export interface WidgetsQueryWidgetsPagesOptions extends OperationOptions { +} + // @public (undocumented) export interface WidgetsUpdateWidgetOptions extends OperationOptions { } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index d0c752d811..e65898832b 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,10 +64,12 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { let firstRun = true; - let itemName: string, nextLinkName: string | undefined; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, @@ -66,12 +78,6 @@ export function buildPagedAsyncIterator< firstRun && pageLink === firstPageLinkPlaceholder ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +196,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +214,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +227,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items", "results"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts index 43f05e437d..3cfb9ba82b 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/widgets/index.ts @@ -25,6 +25,8 @@ import { ListWidgetsDefaultResponse, ListWidgetsPages200Response, ListWidgetsPagesDefaultResponse, + QueryWidgetsPages200Response, + QueryWidgetsPagesDefaultResponse, UpdateWidget200Response, UpdateWidgetDefaultResponse, WidgetServiceContext as Client, @@ -37,6 +39,7 @@ import { uint8ArrayToString } from "@azure/core-util"; import { WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, @@ -173,7 +176,55 @@ export function listWidgetsPages( return buildPagedAsyncIterator( context, () => _listWidgetsPagesSend(context, page, pageSize, options), - _listWidgetsPagesDeserialize + _listWidgetsPagesDeserialize, + { itemName: "results", nextLinkName: "odata.nextLink" } + ); +} + +export function _queryWidgetsPagesSend( + context: Client, + page: number, + pageSize: number, + options: WidgetsQueryWidgetsPagesOptions = { requestOptions: {} } +): StreamableMethod< + QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse +> { + return context + .path("/widgets/widgets/pages") + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { page: page, pageSize: pageSize }, + }); +} + +export async function _queryWidgetsPagesDeserialize( + result: QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + results: result.body["results"].map((p) => ({ + id: p["id"], + weight: p["weight"], + color: p["color"] as any, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +export function queryWidgetsPages( + context: Client, + page: number, + pageSize: number, + options: WidgetsQueryWidgetsPagesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _queryWidgetsPagesSend(context, page, pageSize, options), + _queryWidgetsPagesDeserialize, + { itemName: "results", nextLinkName: "odata.nextLink" } ); } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts index c5908f19a5..32365f9427 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/classic/widgets/index.ts @@ -11,22 +11,24 @@ import { import { listWidgets, listWidgetsPages, + queryWidgetsPages, getWidget, createWidget, updateWidget, deleteWidget, analyzeWidget, } from "../../api/widgets/index.js"; +import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, } from "../../models/options.js"; -import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; export interface WidgetsOperations { listWidgets: ( @@ -42,6 +44,11 @@ export interface WidgetsOperations { pageSize: number, options?: WidgetsListWidgetsPagesOptions ) => PagedAsyncIterableIterator; + queryWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsQueryWidgetsPagesOptions + ) => PagedAsyncIterableIterator; getWidget: (id: string, options?: WidgetsGetWidgetOptions) => Promise; createWidget: ( body: CreateWidget, @@ -86,6 +93,11 @@ export function getWidgets(context: WidgetServiceContext) { pageSize: number, options?: WidgetsListWidgetsPagesOptions ) => listWidgetsPages(context, page, pageSize, options), + queryWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsQueryWidgetsPagesOptions + ) => queryWidgetsPages(context, page, pageSize, options), getWidget: (id: string, options?: WidgetsGetWidgetOptions) => getWidget(context, id, options), createWidget: (body: CreateWidget, options?: WidgetsCreateWidgetOptions) => diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts index 48aa7ef5fa..f2bcec7681 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/index.ts @@ -13,6 +13,7 @@ export { AnalyzeResult, WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts index 135b146744..01aebc04be 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/index.ts @@ -11,6 +11,7 @@ export { export { WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts index e2e3385172..b372ec8bed 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/options.ts @@ -12,6 +12,8 @@ export interface WidgetsListWidgetsOptions extends OperationOptions { export interface WidgetsListWidgetsPagesOptions extends OperationOptions {} +export interface WidgetsQueryWidgetsPagesOptions extends OperationOptions {} + export interface WidgetsGetWidgetOptions extends OperationOptions {} export interface WidgetsCreateWidgetOptions extends OperationOptions {} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts index 84536d620c..dca0f6358c 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/clientDefinitions.ts @@ -5,6 +5,7 @@ import { ListWidgetsParameters, CreateWidgetParameters, ListWidgetsPagesParameters, + QueryWidgetsPagesParameters, GetWidgetParameters, UpdateWidgetParameters, DeleteWidgetParameters, @@ -17,6 +18,8 @@ import { CreateWidgetDefaultResponse, ListWidgetsPages200Response, ListWidgetsPagesDefaultResponse, + QueryWidgetsPages200Response, + QueryWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -54,6 +57,11 @@ export interface ListWidgetsPages { ): StreamableMethod< ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse >; + post( + options: QueryWidgetsPagesParameters + ): StreamableMethod< + QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse + >; } export interface GetWidget { @@ -84,7 +92,7 @@ export interface AnalyzeWidget { export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): ListWidgets; - /** Resource for '/widgets/widgets/pages' has methods for the following verbs: get */ + /** Resource for '/widgets/widgets/pages' has methods for the following verbs: get, post */ (path: "/widgets/widgets/pages"): ListWidgetsPages; /** Resource for '/widgets/\{id\}' has methods for the following verbs: get, patch, delete */ (path: "/widgets/{id}", id: string): GetWidget; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts index 783190f740..91f5d9c532 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/isUnexpected.ts @@ -8,6 +8,8 @@ import { CreateWidgetDefaultResponse, ListWidgetsPages200Response, ListWidgetsPagesDefaultResponse, + QueryWidgetsPages200Response, + QueryWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -22,6 +24,7 @@ const responseMap: Record = { "GET /widgets": ["200"], "POST /widgets": ["201"], "GET /widgets/widgets/pages": ["200"], + "POST /widgets/widgets/pages": ["200"], "GET /widgets/{id}": ["200"], "PATCH /widgets/{id}": ["200"], "DELETE /widgets/{id}": ["204"], @@ -37,6 +40,9 @@ export function isUnexpected( export function isUnexpected( response: ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse ): response is ListWidgetsPagesDefaultResponse; +export function isUnexpected( + response: QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse +): response is QueryWidgetsPagesDefaultResponse; export function isUnexpected( response: GetWidget200Response | GetWidgetDefaultResponse ): response is GetWidgetDefaultResponse; @@ -57,6 +63,8 @@ export function isUnexpected( | CreateWidgetDefaultResponse | ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse + | QueryWidgetsPages200Response + | QueryWidgetsPagesDefaultResponse | GetWidget200Response | GetWidgetDefaultResponse | UpdateWidget200Response @@ -69,6 +77,7 @@ export function isUnexpected( | ListWidgetsDefaultResponse | CreateWidgetDefaultResponse | ListWidgetsPagesDefaultResponse + | QueryWidgetsPagesDefaultResponse | GetWidgetDefaultResponse | UpdateWidgetDefaultResponse | DeleteWidgetDefaultResponse diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts index 30b85fb0ae..74ea7dfc40 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/parameters.ts @@ -35,6 +35,18 @@ export interface ListWidgetsPagesQueryParam { export type ListWidgetsPagesParameters = ListWidgetsPagesQueryParam & RequestParameters; + +export interface QueryWidgetsPagesQueryParamProperties { + page: number; + pageSize: number; +} + +export interface QueryWidgetsPagesQueryParam { + queryParameters: QueryWidgetsPagesQueryParamProperties; +} + +export type QueryWidgetsPagesParameters = QueryWidgetsPagesQueryParam & + RequestParameters; export type GetWidgetParameters = RequestParameters; export interface CreateWidgetBodyParam { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts index c84b098dd5..77a8954ac9 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/rest/responses.ts @@ -31,6 +31,17 @@ export interface ListWidgetsPagesDefaultResponse extends HttpResponse { body: WidgetErrorOutput; } +/** The request has succeeded. */ +export interface QueryWidgetsPages200Response extends HttpResponse { + status: "200"; + body: ListWidgetsPagesResultsOutput; +} + +export interface QueryWidgetsPagesDefaultResponse extends HttpResponse { + status: string; + body: WidgetErrorOutput; +} + /** The request has succeeded. */ export interface GetWidget200Response extends HttpResponse { status: "200"; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index d0c752d811..e65898832b 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,10 +64,12 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { let firstRun = true; - let itemName: string, nextLinkName: string | undefined; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, @@ -66,12 +78,6 @@ export function buildPagedAsyncIterator< firstRun && pageLink === firstPageLinkPlaceholder ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +196,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +214,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +227,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items", "results"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} 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 43f05e437d..3cfb9ba82b 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 @@ -25,6 +25,8 @@ import { ListWidgetsDefaultResponse, ListWidgetsPages200Response, ListWidgetsPagesDefaultResponse, + QueryWidgetsPages200Response, + QueryWidgetsPagesDefaultResponse, UpdateWidget200Response, UpdateWidgetDefaultResponse, WidgetServiceContext as Client, @@ -37,6 +39,7 @@ import { uint8ArrayToString } from "@azure/core-util"; import { WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, @@ -173,7 +176,55 @@ export function listWidgetsPages( return buildPagedAsyncIterator( context, () => _listWidgetsPagesSend(context, page, pageSize, options), - _listWidgetsPagesDeserialize + _listWidgetsPagesDeserialize, + { itemName: "results", nextLinkName: "odata.nextLink" } + ); +} + +export function _queryWidgetsPagesSend( + context: Client, + page: number, + pageSize: number, + options: WidgetsQueryWidgetsPagesOptions = { requestOptions: {} } +): StreamableMethod< + QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse +> { + return context + .path("/widgets/widgets/pages") + .post({ + ...operationOptionsToRequestParameters(options), + queryParameters: { page: page, pageSize: pageSize }, + }); +} + +export async function _queryWidgetsPagesDeserialize( + result: QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse +): Promise { + if (isUnexpected(result)) { + throw result.body; + } + + return { + results: result.body["results"].map((p) => ({ + id: p["id"], + weight: p["weight"], + color: p["color"] as any, + })), + "odata.nextLink": result.body["odata.nextLink"], + }; +} + +export function queryWidgetsPages( + context: Client, + page: number, + pageSize: number, + options: WidgetsQueryWidgetsPagesOptions = { requestOptions: {} } +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _queryWidgetsPagesSend(context, page, pageSize, options), + _queryWidgetsPagesDeserialize, + { itemName: "results", nextLinkName: "odata.nextLink" } ); } 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 c5908f19a5..32365f9427 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 @@ -11,22 +11,24 @@ import { import { listWidgets, listWidgetsPages, + queryWidgetsPages, getWidget, createWidget, updateWidget, deleteWidget, analyzeWidget, } from "../../api/widgets/index.js"; +import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; import { WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, WidgetsDeleteWidgetOptions, WidgetsAnalyzeWidgetOptions, } from "../../models/options.js"; -import { PagedAsyncIterableIterator } from "../../models/pagingTypes.js"; export interface WidgetsOperations { listWidgets: ( @@ -42,6 +44,11 @@ export interface WidgetsOperations { pageSize: number, options?: WidgetsListWidgetsPagesOptions ) => PagedAsyncIterableIterator; + queryWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsQueryWidgetsPagesOptions + ) => PagedAsyncIterableIterator; getWidget: (id: string, options?: WidgetsGetWidgetOptions) => Promise; createWidget: ( body: CreateWidget, @@ -86,6 +93,11 @@ export function getWidgets(context: WidgetServiceContext) { pageSize: number, options?: WidgetsListWidgetsPagesOptions ) => listWidgetsPages(context, page, pageSize, options), + queryWidgetsPages: ( + page: number, + pageSize: number, + options?: WidgetsQueryWidgetsPagesOptions + ) => queryWidgetsPages(context, page, pageSize, options), getWidget: (id: string, options?: WidgetsGetWidgetOptions) => getWidget(context, id, options), createWidget: (body: CreateWidget, options?: WidgetsCreateWidgetOptions) => 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 48aa7ef5fa..f2bcec7681 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 @@ -13,6 +13,7 @@ export { AnalyzeResult, WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts index 135b146744..01aebc04be 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/index.ts @@ -11,6 +11,7 @@ export { export { WidgetsListWidgetsOptions, WidgetsListWidgetsPagesOptions, + WidgetsQueryWidgetsPagesOptions, WidgetsGetWidgetOptions, WidgetsCreateWidgetOptions, WidgetsUpdateWidgetOptions, diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts index e2e3385172..b372ec8bed 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/options.ts @@ -12,6 +12,8 @@ export interface WidgetsListWidgetsOptions extends OperationOptions { export interface WidgetsListWidgetsPagesOptions extends OperationOptions {} +export interface WidgetsQueryWidgetsPagesOptions extends OperationOptions {} + export interface WidgetsGetWidgetOptions extends OperationOptions {} export interface WidgetsCreateWidgetOptions extends OperationOptions {} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts index 84536d620c..dca0f6358c 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/clientDefinitions.ts @@ -5,6 +5,7 @@ import { ListWidgetsParameters, CreateWidgetParameters, ListWidgetsPagesParameters, + QueryWidgetsPagesParameters, GetWidgetParameters, UpdateWidgetParameters, DeleteWidgetParameters, @@ -17,6 +18,8 @@ import { CreateWidgetDefaultResponse, ListWidgetsPages200Response, ListWidgetsPagesDefaultResponse, + QueryWidgetsPages200Response, + QueryWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -54,6 +57,11 @@ export interface ListWidgetsPages { ): StreamableMethod< ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse >; + post( + options: QueryWidgetsPagesParameters + ): StreamableMethod< + QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse + >; } export interface GetWidget { @@ -84,7 +92,7 @@ export interface AnalyzeWidget { export interface Routes { /** Resource for '/widgets' has methods for the following verbs: get, post */ (path: "/widgets"): ListWidgets; - /** Resource for '/widgets/widgets/pages' has methods for the following verbs: get */ + /** Resource for '/widgets/widgets/pages' has methods for the following verbs: get, post */ (path: "/widgets/widgets/pages"): ListWidgetsPages; /** Resource for '/widgets/\{id\}' has methods for the following verbs: get, patch, delete */ (path: "/widgets/{id}", id: string): GetWidget; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts index 783190f740..91f5d9c532 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/isUnexpected.ts @@ -8,6 +8,8 @@ import { CreateWidgetDefaultResponse, ListWidgetsPages200Response, ListWidgetsPagesDefaultResponse, + QueryWidgetsPages200Response, + QueryWidgetsPagesDefaultResponse, GetWidget200Response, GetWidgetDefaultResponse, UpdateWidget200Response, @@ -22,6 +24,7 @@ const responseMap: Record = { "GET /widgets": ["200"], "POST /widgets": ["201"], "GET /widgets/widgets/pages": ["200"], + "POST /widgets/widgets/pages": ["200"], "GET /widgets/{id}": ["200"], "PATCH /widgets/{id}": ["200"], "DELETE /widgets/{id}": ["204"], @@ -37,6 +40,9 @@ export function isUnexpected( export function isUnexpected( response: ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse ): response is ListWidgetsPagesDefaultResponse; +export function isUnexpected( + response: QueryWidgetsPages200Response | QueryWidgetsPagesDefaultResponse +): response is QueryWidgetsPagesDefaultResponse; export function isUnexpected( response: GetWidget200Response | GetWidgetDefaultResponse ): response is GetWidgetDefaultResponse; @@ -57,6 +63,8 @@ export function isUnexpected( | CreateWidgetDefaultResponse | ListWidgetsPages200Response | ListWidgetsPagesDefaultResponse + | QueryWidgetsPages200Response + | QueryWidgetsPagesDefaultResponse | GetWidget200Response | GetWidgetDefaultResponse | UpdateWidget200Response @@ -69,6 +77,7 @@ export function isUnexpected( | ListWidgetsDefaultResponse | CreateWidgetDefaultResponse | ListWidgetsPagesDefaultResponse + | QueryWidgetsPagesDefaultResponse | GetWidgetDefaultResponse | UpdateWidgetDefaultResponse | DeleteWidgetDefaultResponse diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts index 30b85fb0ae..74ea7dfc40 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/parameters.ts @@ -35,6 +35,18 @@ export interface ListWidgetsPagesQueryParam { export type ListWidgetsPagesParameters = ListWidgetsPagesQueryParam & RequestParameters; + +export interface QueryWidgetsPagesQueryParamProperties { + page: number; + pageSize: number; +} + +export interface QueryWidgetsPagesQueryParam { + queryParameters: QueryWidgetsPagesQueryParamProperties; +} + +export type QueryWidgetsPagesParameters = QueryWidgetsPagesQueryParam & + RequestParameters; export type GetWidgetParameters = RequestParameters; export interface CreateWidgetBodyParam { diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts index c84b098dd5..77a8954ac9 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/rest/responses.ts @@ -31,6 +31,17 @@ export interface ListWidgetsPagesDefaultResponse extends HttpResponse { body: WidgetErrorOutput; } +/** The request has succeeded. */ +export interface QueryWidgetsPages200Response extends HttpResponse { + status: "200"; + body: ListWidgetsPagesResultsOutput; +} + +export interface QueryWidgetsPagesDefaultResponse extends HttpResponse { + status: string; + body: WidgetErrorOutput; +} + /** The request has succeeded. */ export interface GetWidget200Response extends HttpResponse { status: "200"; diff --git a/packages/typespec-test/test/widget_dpg/spec/main.tsp b/packages/typespec-test/test/widget_dpg/spec/main.tsp index efea8b2bd1..8aabf397b9 100644 --- a/packages/typespec-test/test/widget_dpg/spec/main.tsp +++ b/packages/typespec-test/test/widget_dpg/spec/main.tsp @@ -91,6 +91,13 @@ It does not accept any options or parameters. @query pageSize: int32, ): ListWidgetsPagesResults | WidgetError; + @post + @route("/widgets/pages") + queryWidgetsPages( + @query page: int32, + @query pageSize: int32, + ): ListWidgetsPagesResults | WidgetError; + @doc("Get a widget by ID.") @get getWidget(@path id: string): Widget | WidgetError; diff --git a/packages/typespec-ts/src/index.ts b/packages/typespec-ts/src/index.ts index ccf051859e..be3d31c3c9 100644 --- a/packages/typespec-ts/src/index.ts +++ b/packages/typespec-ts/src/index.ts @@ -175,13 +175,19 @@ export async function $onEmit(context: EmitContext) { } ); + const isMultiClients = modularCodeModel.clients.length > 1; for (const subClient of modularCodeModel.clients) { buildModels(modularCodeModel, subClient); buildModelsOptions(modularCodeModel, subClient); const hasClientUnexpectedHelper = needUnexpectedHelper.get(subClient.rlcClientName) ?? false; buildPagingTypes(modularCodeModel, subClient); - buildModularPagingHelpers(modularCodeModel, subClient); + buildModularPagingHelpers( + modularCodeModel, + subClient, + hasClientUnexpectedHelper, + isMultiClients + ); buildOperationFiles( dpgContext, modularCodeModel, @@ -204,7 +210,7 @@ export async function $onEmit(context: EmitContext) { exportIndex: true, interfaceOnly: true }); - if (modularCodeModel.clients.length > 1) { + if (isMultiClients) { buildSubClientIndexFile(modularCodeModel, subClient); } buildRootIndex(modularCodeModel, subClient, rootIndexFile); diff --git a/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts b/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts index 24cb5575b9..0a1dc6633d 100644 --- a/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts +++ b/packages/typespec-ts/src/modular/buildClassicalOperationGroups.ts @@ -7,7 +7,7 @@ import { NameType } from "@azure-tools/rlc-common"; import { getClassicalOperation } from "./helpers/classicalOperationHelpers.js"; import { getClassicalLayerPrefix } from "./helpers/namingHelpers.js"; import { SourceFile } from "ts-morph"; -import { importModels } from "./buildOperations.js"; +import { importModels, importPagingDependencies } from "./buildOperations.js"; export function buildClassicOperationFiles( codeModel: ModularCodeModel, @@ -52,6 +52,14 @@ export function buildClassicOperationFiles( operationGroup.namespaceHierarchies.length ); importApis(classicFile, client, codeModel, operationGroup); + // We need to import the paging helpers and types explicitly because ts-morph may not be able to find them. + importPagingDependencies( + srcPath, + classicFile, + codeModel.project, + subfolder, + operationGroup.namespaceHierarchies.length + ); classicFile.fixMissingImports(); classicFile.fixUnusedIdentifiers(); classicOperationFiles.set(classicOperationFileName, classicFile); @@ -91,6 +99,14 @@ export function buildClassicOperationFiles( // We SHOULD keep this because otherwise ts-morph will "helpfully" try to import models from the rest layer when we call fixMissingImports(). importModels(srcPath, classicFile, codeModel.project, subfolder, layer); importApis(classicFile, client, codeModel, operationGroup, layer); + // We need to import the paging helpers and types explicitly because ts-morph may not be able to find them. + importPagingDependencies( + srcPath, + classicFile, + codeModel.project, + subfolder, + operationGroup.namespaceHierarchies.length + ); classicFile.fixMissingImports(); classicFile.fixUnusedIdentifiers(); classicOperationFiles.set(classicOperationFileName, classicFile); diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 585145ef61..1c54f81f5e 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -655,7 +655,12 @@ function emitOperation( context.program, ignoreDiagnostics(getHttpOperation(context.program, operation)) ); - const paging = getPagedResult(context.program, operation); + const pagingMetadata = getPagedResult(context.program, operation); + // Disable the paging feature if no itemsSegments is found. + let paging = + pagingMetadata && + pagingMetadata.itemsSegments && + pagingMetadata.itemsSegments.length > 0; if (lro && paging) { return emitLroPagingOperation( context, diff --git a/packages/typespec-ts/src/modular/buildOperations.ts b/packages/typespec-ts/src/modular/buildOperations.ts index 1838cec085..f3e748d583 100644 --- a/packages/typespec-ts/src/modular/buildOperations.ts +++ b/packages/typespec-ts/src/modular/buildOperations.ts @@ -184,7 +184,7 @@ export function importModels( // sourceFile.fixUnusedIdentifiers(); } -function importPagingDependencies( +export function importPagingDependencies( srcPath: string, sourceFile: SourceFile, project: Project, diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index a963d7ccdf..a0c8de0f8d 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -75,7 +75,9 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { export function buildPagingHelpers( codeModel: ModularCodeModel, - client: Client + client: Client, + needUnexpectedHelper: boolean = true, + isMultiClients: boolean = false ) { const pagingOperstions = client.operationGroups .flatMap((op) => op.operations) @@ -94,10 +96,37 @@ export function buildPagingHelpers( itemNames.add(op.itemName); } } - const nextLinkNamesStr = [...nextLinkNames] - .map((name) => `"${name}"`) - .join(", "); - const itemNamesStr = [...itemNames].map((name) => `"${name}"`).join(", "); + const checkingPagingRequestContent = needUnexpectedHelper + ? `if (isUnexpected(response)) { + throw createRestError( + \`Pagination failed with unexpected statusCode \${response.status}\`, + response + ); + }` + : `const Http2xxStatusCodes = [ + "200", + "201", + "202", + "203", + "204", + "205", + "206", + "207", + "208", + "226", + ]; + if (!Http2xxStatusCodes.includes(response.status)) { + throw createRestError( + \`Pagination failed with unexpected statusCode \${response.status}\`, + response + ); + }`; + + const unexpectedHelperImport = needUnexpectedHelper + ? `import { isUnexpected } from "${ + isMultiClients ? "../" : "" + }../rest/index.js";` + : ""; const pagingTypesPath = `../models/pagingTypes.js`; const filePath = path.join( codeModel.modularOptions.sourceRoot, @@ -116,7 +145,9 @@ export function buildPagingHelpers( createRestError, PathUncheckedResponse } from "@azure-rest/core-client"; + import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator } from "${pagingTypesPath}"; + ${unexpectedHelperImport} /** * An interface that describes how to communicate with the service. @@ -149,6 +180,14 @@ export function buildPagingHelpers( toElements?: (page: TPage) => unknown[]; } + /** + * Options for the paging helper + */ + export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; + } + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -160,10 +199,12 @@ export function buildPagingHelpers( >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { let firstRun = true; - let itemName: string, nextLinkName: string | undefined; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, @@ -172,12 +213,6 @@ export function buildPagingHelpers( firstRun && pageLink === firstPageLinkPlaceholder ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -296,7 +331,7 @@ export function buildPagingHelpers( const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( \`Body Property \${nextLinkName} should be a string or undefined\` ); } @@ -314,7 +349,7 @@ export function buildPagingHelpers( // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( \`Couldn't paginate response Body doesn't contain an array property with name: \${itemName}\` ); @@ -327,71 +362,8 @@ export function buildPagingHelpers( * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { - throw createRestError( - \`Pagination failed with unexpected statusCode \${response.status}\`, - response - ); - } - } - - /** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ - function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set([${nextLinkNamesStr}]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set([${itemNamesStr}]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - \`Couldn't paginate response - Body doesn't contain an array property with name: \${[...itemNames].join( - " OR " - )}\` - ); - } - - return { itemName, nextLinkName }; + ${checkingPagingRequestContent} } - ` ]); } diff --git a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts index 9524051575..c9eba25fb4 100644 --- a/packages/typespec-ts/src/modular/helpers/operationHelpers.ts +++ b/packages/typespec-ts/src/modular/helpers/operationHelpers.ts @@ -278,10 +278,20 @@ export function getOperationFunction( const statements: string[] = []; if (isPaging) { + const options = []; + if (operation.itemName) { + options.push(`itemName: "${operation.itemName}"`); + } + if (operation.continuationTokenName) { + options.push(`nextLinkName: "${operation.continuationTokenName}"`); + } statements.push( - `return buildPagedAsyncIterator(context, () => _${name}Send(${parameters - .map((p) => p.name) - .join(", ")}), _${name}Deserialize) ;` + `return buildPagedAsyncIterator( + context, + () => _${name}Send(${parameters.map((p) => p.name).join(", ")}), + _${name}Deserialize, + ${options.length > 0 ? `{${options.join(", ")}}` : ``} + );` ); } else { statements.push( diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index ce61211e6f..e78e119b38 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -268,7 +268,8 @@ export function list( return buildPagedAsyncIterator( context, () => _listSend(context, options), - _listDeserialize + _listDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } @@ -313,7 +314,8 @@ export function listWithPage( return buildPagedAsyncIterator( context, () => _listWithPageSend(context, options), - _listWithPageDeserialize + _listWithPageDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } @@ -362,7 +364,8 @@ export function listWithCustomPageModel( return buildPagedAsyncIterator( context, () => _listWithCustomPageModelSend(context, options), - _listWithCustomPageModelDeserialize + _listWithCustomPageModelDeserialize, + { itemName: "items", nextLinkName: "nextLink" } ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index 5393be6ffd..e65898832b 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,10 +64,12 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { let firstRun = true; - let itemName: string, nextLinkName: string | undefined; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, @@ -66,12 +78,6 @@ export function buildPagedAsyncIterator< firstRun && pageLink === firstPageLinkPlaceholder ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +196,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +214,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +227,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts index 9548b89d90..ae7335d1d7 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/operations.ts @@ -44,6 +44,7 @@ export function list( return buildPagedAsyncIterator( context, () => _listSend(context, options), - _listDeserialize + _listDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index 5393be6ffd..96045d0b08 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -6,6 +6,7 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, @@ -43,6 +44,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,10 +63,12 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { let firstRun = true; - let itemName: string, nextLinkName: string | undefined; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { firstPageLink: firstPageLinkPlaceholder, @@ -66,12 +77,6 @@ export function buildPagedAsyncIterator< firstRun && pageLink === firstPageLinkPlaceholder ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +195,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +213,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -240,48 +245,3 @@ function checkPagingRequest(response: PathUncheckedResponse): void { ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} From 677c526f3db5baf7760a1c92479dd3d49929549c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 18:30:03 +0800 Subject: [PATCH 46/60] Resolve some comments --- packages/typespec-ts/src/utils/operationUtil.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/typespec-ts/src/utils/operationUtil.ts b/packages/typespec-ts/src/utils/operationUtil.ts index 60a2ff503f..5e110f5e8b 100644 --- a/packages/typespec-ts/src/utils/operationUtil.ts +++ b/packages/typespec-ts/src/utils/operationUtil.ts @@ -538,10 +538,6 @@ export function parseNextLinkName( } export function parseItemName(paged: PagedResultMetadata): string | undefined { - const pathComponents = paged.itemsPath?.split("."); - if (pathComponents) { - // TODO: This logic breaks down if there actually is a dotted path. - return pathComponents[pathComponents.length - 1]; - } - return undefined; + // TODO: support the nested item names + return (paged.itemsSegments ?? [])[0]; } From 40dfbf1c5335806b2f0ce75667ec64b1eb123f6e Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 18:38:08 +0800 Subject: [PATCH 47/60] Resolve some comments --- packages/typespec-ts/test/commands/cadl-ranch-list.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/typespec-ts/test/commands/cadl-ranch-list.ts b/packages/typespec-ts/test/commands/cadl-ranch-list.ts index 0d269505ec..3fddf43cca 100644 --- a/packages/typespec-ts/test/commands/cadl-ranch-list.ts +++ b/packages/typespec-ts/test/commands/cadl-ranch-list.ts @@ -247,6 +247,10 @@ export const modularTsps: TypeSpecRanchConfig[] = [ outputPath: "payload/pageable", inputPath: "payload/pageable" }, + { + outputPath: "encode/bytes", + inputPath: "encode/bytes" + }, { outputPath: "encode/duration", inputPath: "encode/duration" From d39aa9eb5ee10eec5a0efeec3a976dc08093b74f Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 20:33:53 +0800 Subject: [PATCH 48/60] Regenerate the paging helpers --- .../typespec-ts/src/api/operations.ts | 45 ++++++--- .../typespec-ts/src/api/pagingHelpers.ts | 96 ++++--------------- .../typespec-ts/src/api/operations.ts | 6 +- .../typespec-ts/src/api/pagingHelpers.ts | 96 ++++--------------- .../loadTestAdministration/api/operations.ts | 6 +- .../api/pagingHelpers.ts | 96 ++++--------------- .../src/loadTestRun/api/operations.ts | 9 +- .../src/loadTestRun/api/pagingHelpers.ts | 96 ++++--------------- .../generated/src/api/pagingHelpers.ts | 11 +-- .../typespec-ts/src/api/pagingHelpers.ts | 11 +-- .../src/modular/buildPagingFiles.ts | 23 +---- .../azure/core/src/api/pagingHelpers.ts | 11 +-- .../payload/pageable/src/api/pagingHelpers.ts | 11 +-- .../payloadPageable.spec.ts | 4 + 14 files changed, 153 insertions(+), 368 deletions(-) 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 79b4cf7b08..1c094a2bfc 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 @@ -350,7 +350,8 @@ export function listApplications( return buildPagedAsyncIterator( context, () => _listApplicationsSend(context, options), - _listApplicationsDeserialize + _listApplicationsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -453,7 +454,8 @@ export function listPoolUsageMetrics( return buildPagedAsyncIterator( context, () => _listPoolUsageMetricsSend(context, options), - _listPoolUsageMetricsDeserialize + _listPoolUsageMetricsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -1348,7 +1350,8 @@ export function listPools( return buildPagedAsyncIterator( context, () => _listPoolsSend(context, options), - _listPoolsDeserialize + _listPoolsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -2687,7 +2690,8 @@ export function listSupportedImages( return buildPagedAsyncIterator( context, () => _listSupportedImagesSend(context, options), - _listSupportedImagesDeserialize + _listSupportedImagesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -2774,7 +2778,8 @@ export function listPoolNodeCounts( return buildPagedAsyncIterator( context, () => _listPoolNodeCountsSend(context, options), - _listPoolNodeCountsDeserialize + _listPoolNodeCountsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -7621,7 +7626,8 @@ export function listJobs( return buildPagedAsyncIterator( context, () => _listJobsSend(context, options), - _listJobsDeserialize + _listJobsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -8728,7 +8734,8 @@ export function listJobsFromSchedule( return buildPagedAsyncIterator( context, () => _listJobsFromScheduleSend(context, jobScheduleId, options), - _listJobsFromScheduleDeserialize + _listJobsFromScheduleDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -8917,7 +8924,8 @@ export function listJobPreparationAndReleaseTaskStatus( return buildPagedAsyncIterator( context, () => _listJobPreparationAndReleaseTaskStatusSend(context, jobId, options), - _listJobPreparationAndReleaseTaskStatusDeserialize + _listJobPreparationAndReleaseTaskStatusDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -9099,7 +9107,8 @@ export function listCertificates( return buildPagedAsyncIterator( context, () => _listCertificatesSend(context, options), - _listCertificatesDeserialize + _listCertificatesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -15591,7 +15600,8 @@ export function listJobSchedules( return buildPagedAsyncIterator( context, () => _listJobSchedulesSend(context, options), - _listJobSchedulesDeserialize + _listJobSchedulesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -16164,7 +16174,8 @@ export function listTasks( return buildPagedAsyncIterator( context, () => _listTasksSend(context, jobId, options), - _listTasksDeserialize + _listTasksDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -17342,7 +17353,8 @@ export function listTaskFiles( return buildPagedAsyncIterator( context, () => _listTaskFilesSend(context, jobId, taskId, options), - _listTaskFilesDeserialize + _listTaskFilesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -18470,7 +18482,8 @@ export function listNodes( return buildPagedAsyncIterator( context, () => _listNodesSend(context, poolId, options), - _listNodesDeserialize + _listNodesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -18651,7 +18664,8 @@ export function listNodeExtensions( return buildPagedAsyncIterator( context, () => _listNodeExtensionsSend(context, poolId, nodeId, options), - _listNodeExtensionsDeserialize + _listNodeExtensionsDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } @@ -18887,6 +18901,7 @@ export function listNodeFiles( return buildPagedAsyncIterator( context, () => _listNodeFilesSend(context, poolId, nodeId, options), - _listNodeFilesDeserialize + _listNodeFilesDeserialize, + { itemName: "value", nextLinkName: "odata.nextLink" } ); } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 47a612efec..6f77709048 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -23,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,24 +64,17 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; - let itemName: string, nextLinkName: string | undefined; - const firstPageLinkPlaceholder = ""; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +193,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +211,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +224,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink", "odata.nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} 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 fd994c248c..49838dc8d4 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 @@ -316,7 +316,8 @@ export function listTextBlocklists( return buildPagedAsyncIterator( context, () => _listTextBlocklistsSend(context, options), - _listTextBlocklistsDeserialize + _listTextBlocklistsDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } @@ -516,6 +517,7 @@ export function listTextBlocklistItems( return buildPagedAsyncIterator( context, () => _listTextBlocklistItemsSend(context, blocklistName, options), - _listTextBlocklistItemsDeserialize + _listTextBlocklistItemsDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 5393be6ffd..6f77709048 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -23,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,24 +64,17 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; - let itemName: string, nextLinkName: string | undefined; - const firstPageLinkPlaceholder = ""; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +193,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +211,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +224,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} 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 b4d247515f..9aa0405dc2 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 @@ -788,7 +788,8 @@ export function listTestFiles( return buildPagedAsyncIterator( context, () => _listTestFilesSend(context, testId, options), - _listTestFilesDeserialize + _listTestFilesDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } @@ -971,7 +972,8 @@ export function listTests( return buildPagedAsyncIterator( context, () => _listTestsSend(context, options), - _listTestsDeserialize + _listTestsDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index 5393be6ffd..76d7427951 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -23,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,24 +64,17 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; - let itemName: string, nextLinkName: string | undefined; - const firstPageLinkPlaceholder = ""; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +193,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +211,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +224,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} 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 352865d651..f6bea18bcf 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 @@ -991,7 +991,8 @@ export function listMetricDimensionValues( metricNamespace, options ), - _listMetricDimensionValuesDeserialize + _listMetricDimensionValuesDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } @@ -1159,7 +1160,8 @@ export function listMetrics( return buildPagedAsyncIterator( context, () => _listMetricsSend(context, testRunId, body, options), - _listMetricsDeserialize + _listMetricsDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } @@ -1457,7 +1459,8 @@ export function listTestRuns( return buildPagedAsyncIterator( context, () => _listTestRunsSend(context, options), - _listTestRunsDeserialize + _listTestRunsDeserialize, + { itemName: "value", nextLinkName: "nextLink" } ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index 5393be6ffd..76d7427951 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -6,11 +6,13 @@ import { createRestError, PathUncheckedResponse, } from "@azure-rest/core-client"; +import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, PagedAsyncIterableIterator, } from "../models/pagingTypes.js"; +import { isUnexpected } from "../../rest/index.js"; /** * An interface that describes how to communicate with the service. @@ -23,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -43,6 +45,14 @@ interface PagedResult< toElements?: (page: TPage) => unknown[]; } +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} + /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -54,24 +64,17 @@ export function buildPagedAsyncIterator< >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise + processResponseBody: (result: TResponse) => Promise, + options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; - let itemName: string, nextLinkName: string | undefined; - const firstPageLinkPlaceholder = ""; + const itemName = options.itemName ?? "value"; + const nextLinkName = options.nextLinkName ?? "nextLink"; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); - if (firstRun) { - const pageInfo = getPaginationProperties(result); - itemName = pageInfo.itemName; - nextLinkName = pageInfo.nextLinkName; - } - firstRun = false; checkPagingRequest(result); const results = await processResponseBody(result as TResponse); const nextLink = getNextLink(results, nextLinkName); @@ -190,7 +193,7 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { - throw new Error( + throw new RestError( `Body Property ${nextLinkName} should be a string or undefined` ); } @@ -208,7 +211,7 @@ function getElements(body: unknown, itemName: string): T[] { // The fact that this must be an array is used above to calculate the // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { - throw new Error( + throw new RestError( `Couldn't paginate response Body doesn't contain an array property with name: ${itemName}` ); @@ -221,67 +224,10 @@ function getElements(body: unknown, itemName: string): T[] { * Checks if a request failed */ function checkPagingRequest(response: PathUncheckedResponse): void { - const Http2xxStatusCodes = [ - "200", - "201", - "202", - "203", - "204", - "205", - "206", - "207", - "208", - "226", - ]; - if (!Http2xxStatusCodes.includes(response.status)) { + if (isUnexpected(response)) { throw createRestError( `Pagination failed with unexpected statusCode ${response.status}`, response ); } } - -/** - * Extracts the itemName and nextLinkName from the initial response to use them for pagination - */ -function getPaginationProperties(initialResponse: PathUncheckedResponse) { - // Build a set with the passed custom nextLinkNames - const nextLinkNames = new Set(["nextLink"]); - - // Build a set with the passed custom set of itemNames - const itemNames = new Set(["value", "items"]); - - let nextLinkName: string | undefined; - let itemName: string | undefined; - - for (const name of nextLinkNames) { - const nextLink = (initialResponse.body as Record)[ - name - ] as string; - if (nextLink) { - nextLinkName = name; - break; - } - } - - for (const name of itemNames) { - const item = (initialResponse.body as Record)[ - name - ] as string; - if (item) { - itemName = name; - break; - } - } - - if (!itemName) { - throw new Error( - `Couldn't paginate response - Body doesn't contain an array property with name: ${[...itemNames].join( - " OR " - )}` - ); - } - - return { itemName, nextLinkName }; -} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index e65898832b..6f77709048 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -25,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -67,15 +67,12 @@ export function buildPagedAsyncIterator< processResponseBody: (result: TResponse) => Promise, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; const itemName = options.itemName ?? "value"; const nextLinkName = options.nextLinkName ?? "nextLink"; - const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); checkPagingRequest(result); diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index e65898832b..6f77709048 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -25,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -67,15 +67,12 @@ export function buildPagedAsyncIterator< processResponseBody: (result: TResponse) => Promise, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; const itemName = options.itemName ?? "value"; const nextLinkName = options.nextLinkName ?? "nextLink"; - const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); checkPagingRequest(result); diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index a0c8de0f8d..286e0cb09b 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -85,17 +85,7 @@ export function buildPagingHelpers( if (!pagingOperstions || pagingOperstions.length === 0) { return; } - // prepare custom nextLinkNames and itemNames - const nextLinkNames = new Set(["nextLink"]); - const itemNames = new Set(["value", "items"]); - for (const op of pagingOperstions) { - if (op.continuationTokenName) { - nextLinkNames.add(op.continuationTokenName); - } - if (op.itemName) { - itemNames.add(op.itemName); - } - } + const checkingPagingRequestContent = needUnexpectedHelper ? `if (isUnexpected(response)) { throw createRestError( @@ -160,12 +150,12 @@ export function buildPagingHelpers( /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the \`byPage\` method on the paged async iterator. @@ -202,15 +192,12 @@ export function buildPagingHelpers( processResponseBody: (result: TResponse) => Promise, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; const itemName = options.itemName ?? "value"; const nextLinkName = options.nextLinkName ?? "nextLink"; - const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); checkPagingRequest(result); diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index e65898832b..6f77709048 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -25,12 +25,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -67,15 +67,12 @@ export function buildPagedAsyncIterator< processResponseBody: (result: TResponse) => Promise, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; const itemName = options.itemName ?? "value"; const nextLinkName = options.nextLinkName ?? "nextLink"; - const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); checkPagingRequest(result); diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index 96045d0b08..eab3a65de9 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -24,12 +24,12 @@ interface PagedResult< /** * Link to the first page of results. */ - firstPageLink: string; + firstPageLink?: string; /** * A method that returns a page of results. */ getPage: ( - pageLink: string + pageLink?: string ) => Promise<{ page: TPage; nextPageLink?: string } | undefined>; /** * a function to implement the `byPage` method on the paged async iterator. @@ -66,15 +66,12 @@ export function buildPagedAsyncIterator< processResponseBody: (result: TResponse) => Promise, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { - let firstRun = true; const itemName = options.itemName ?? "value"; const nextLinkName = options.nextLinkName ?? "nextLink"; - const firstPageLinkPlaceholder = ""; const pagedResult: PagedResult = { - firstPageLink: firstPageLinkPlaceholder, - getPage: async (pageLink: string) => { + getPage: async (pageLink?: string) => { const result = - firstRun && pageLink === firstPageLinkPlaceholder + pageLink === undefined ? await getInitialResponse() : await client.pathUnchecked(pageLink).get(); checkPagingRequest(result); diff --git a/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts b/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts index 012a2a7fbc..db00742160 100644 --- a/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/payloadPageable.spec.ts @@ -23,6 +23,10 @@ describe("PageableClient Classical Client", () => { assert.fail("Should throw exception"); } catch (err: any) { assert.isNotNull(err); + assert.strictEqual( + err.message, + "Pagination failed with unexpected statusCode 400" + ); } }); From 416064b0db1b519a8f39ac6e4fdddb65d92c43ad Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Tue, 21 Nov 2023 21:41:32 +0800 Subject: [PATCH 49/60] Report warning if no items defined --- packages/typespec-ts/src/lib.ts | 6 + .../typespec-ts/src/modular/buildCodeModel.ts | 16 ++- .../test/modularUnit/operations.spec.ts | 126 ++++++++++++++++++ packages/typespec-ts/test/util/emitUtil.ts | 10 +- 4 files changed, 155 insertions(+), 3 deletions(-) diff --git a/packages/typespec-ts/src/lib.ts b/packages/typespec-ts/src/lib.ts index 1a073ad168..6708c5b46f 100644 --- a/packages/typespec-ts/src/lib.ts +++ b/packages/typespec-ts/src/lib.ts @@ -192,6 +192,12 @@ const libDef = { default: "Required header cannot be nullable. Please remove the nullable modifier." } + }, + "no-paging-items-defined": { + severity: "warning", + messages: { + default: paramMessage`Please specify @items property for the paging operation - ${"operationName"}.` + } } }, emitter: { diff --git a/packages/typespec-ts/src/modular/buildCodeModel.ts b/packages/typespec-ts/src/modular/buildCodeModel.ts index 1c54f81f5e..2e3988c970 100644 --- a/packages/typespec-ts/src/modular/buildCodeModel.ts +++ b/packages/typespec-ts/src/modular/buildCodeModel.ts @@ -107,6 +107,7 @@ import { getModelNamespaceName, getOperationNamespaceInterfaceName } from "../utils/namespaceUtils.js"; +import { reportDiagnostic } from "../lib.js"; interface HttpServerParameter { type: "endpointPath"; @@ -657,10 +658,23 @@ function emitOperation( ); const pagingMetadata = getPagedResult(context.program, operation); // Disable the paging feature if no itemsSegments is found. - let paging = + 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 + }); + } + if (lro && paging) { return emitLroPagingOperation( context, diff --git a/packages/typespec-ts/test/modularUnit/operations.spec.ts b/packages/typespec-ts/test/modularUnit/operations.spec.ts index 4abcf79d1c..32b351e0ef 100644 --- a/packages/typespec-ts/test/modularUnit/operations.spec.ts +++ b/packages/typespec-ts/test/modularUnit/operations.spec.ts @@ -522,4 +522,130 @@ describe("operations", () => { ); }); }); + + describe("paging operations", () => { + it("should generate paging if @items defined", async () => { + const tspContent = ` + @error + model Error { + code: int32; + message: string; + } + + @pagedResult + model Bar { + @items + lists: string[]; + } + @post + op test(): Error | Bar; + `; + const operationFiles = await emitModularOperationsFromTypeSpec( + tspContent, + true, + true, + true + ); + assert.ok(operationFiles); + + assert.equal(operationFiles?.length, 1); + // console.log(operationFiles?.[0]?.getFullText()!); + assertEqualContent( + operationFiles?.[0]?.getFullText()!, + ` + import { TestingContext as Client } from "../rest/index.js"; + import { StreamableMethod, operationOptionsToRequestParameters } from "@azure-rest/core-client"; + + export function _testSend(context: Client, options: TestOptions = { requestOptions: {} }): StreamableMethod { + return context.path("/", ).post({...operationOptionsToRequestParameters(options), }) ; + } + + export async function _testDeserialize(result: Test200Response | TestDefaultResponse): Promise { + if(result.status !== "200"){ + throw result.body + } + + return { + "lists": result.body["lists"] + } + } + + export function test(context: Client, options: TestOptions = { requestOptions: {} }): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _testSend(context, options), + _testDeserialize, + {itemName: "lists"} + ); + }`, + true + ); + }); + + it("should generate paging if no @items defined", async () => { + const tspContent = ` + @error + model Error { + code: int32; + message: string; + } + + @pagedResult + model Bar { + lists: string[]; + } + @post + op test(): Error | Bar; + `; + + try { + await emitModularOperationsFromTypeSpec(tspContent, true, true, true); + assert.fail("Should throw diagnostic warnings"); + } catch (e) { + const diagnostics = e as Diagnostic[]; + // console.log(diagnostics); + assert.equal(diagnostics.length, 1); + assert.equal( + diagnostics[0]?.code, + "@azure-tools/typespec-ts/no-paging-items-defined" + ); + assert.equal(diagnostics[0]?.severity, "warning"); + } + const operationFiles = await emitModularOperationsFromTypeSpec( + tspContent, + false, + true, + true + ); + assert.ok(operationFiles); + assert.equal(operationFiles?.length, 1); + // console.log(operationFiles?.[0]?.getFullText()!); + assertEqualContent( + operationFiles?.[0]?.getFullText()!, + ` + import { TestingContext as Client } from "../rest/index.js"; + import { StreamableMethod, operationOptionsToRequestParameters } from "@azure-rest/core-client"; + + export function _testSend(context: Client, options: TestOptions = { requestOptions: {} }): StreamableMethod { + return context.path("/", ).post({...operationOptionsToRequestParameters(options), }) ; + } + + export async function _testDeserialize(result: Test200Response | TestDefaultResponse): Promise { + if(result.status !== "200"){ + throw result.body + } + + return { + "lists": result.body["lists"] + } + } + + export async function test(context: Client, options: TestOptions = { requestOptions: {} }): Promise { + const result = await _testSend(context, options); + return _testDeserialize(result); + }`, + true + ); + }); + }); }); diff --git a/packages/typespec-ts/test/util/emitUtil.ts b/packages/typespec-ts/test/util/emitUtil.ts index eeda96c5b5..ebe66e5d42 100644 --- a/packages/typespec-ts/test/util/emitUtil.ts +++ b/packages/typespec-ts/test/util/emitUtil.ts @@ -315,9 +315,15 @@ export async function emitModularModelsFromTypeSpec( export async function emitModularOperationsFromTypeSpec( tspContent: string, - mustEmptyDiagnostic = true + mustEmptyDiagnostic = true, + needNamespaces: boolean = true, + needAzureCore: boolean = false ) { - const context = await rlcEmitterFor(tspContent); + const context = await rlcEmitterFor( + tspContent, + needNamespaces, + needAzureCore + ); const dpgContext = createDpgContextTestHelper(context.program); const serviceNameToRlcModelsMap: Map = new Map< string, From 56c43ba60dab189dcd778f5f854b12848dcd0ec7 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 22 Nov 2023 20:55:18 +0800 Subject: [PATCH 50/60] Resolve conflicts --- common/config/rush/pnpm-lock.yaml | 49 +++++-------------------------- 1 file changed, 7 insertions(+), 42 deletions(-) diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 9fad181cc6..61af9f7941 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -402,8 +402,8 @@ packages: '@typespec/versioning': 0.50.0_@typespec+compiler@0.50.0 dev: true - /@azure-tools/cadl-ranch-expect/0.8.1_hyg5yyh7beodvmafzqxellnzky: - resolution: {integrity: sha512-ea2X6BlImkPmeCEaMUniTIkJRo7EfJy1SdHy4rrdhg2rTPRQUGQJHLdsWle2Stiy7uTkEQCXngg+RmpsQP9PRg==} + /@azure-tools/cadl-ranch-expect/0.8.0_34oeiyjczsyn4xxwbbzj3xeide: + resolution: {integrity: sha512-BjyiGorzaq7ejerrEgK4AiDrBgun5A/Q3U7kEGpK+lpjxON4nHkut07DnDqp3uEvxeHp4yZUIOX9MHd+nDPOPg==} engines: {node: '>=16.0.0'} peerDependencies: '@typespec/compiler': ~0.49.0 @@ -411,10 +411,10 @@ packages: '@typespec/rest': ~0.49.0 '@typespec/versioning': ~0.49.0 dependencies: - '@typespec/compiler': 0.49.0 - '@typespec/http': 0.49.0_@typespec+compiler@0.49.0 - '@typespec/rest': 0.49.0_eeytn2g3ek3zpawg2doqsgnp3y - '@typespec/versioning': 0.49.0_@typespec+compiler@0.49.0 + '@typespec/compiler': 0.50.0 + '@typespec/http': 0.50.0_@typespec+compiler@0.50.0 + '@typespec/rest': 0.50.0_bd5gaxunkvodklitr22kuzoinu + '@typespec/versioning': 0.50.0_@typespec+compiler@0.50.0 dev: true /@azure-tools/cadl-ranch-specs/0.24.0_df5542pgaiepvbqurepfmxhvmq: @@ -428,7 +428,7 @@ packages: '@typespec/rest': ~0.49.0 '@typespec/versioning': ~0.49.0 dependencies: - '@azure-tools/cadl-ranch': 0.9.1_tezp5rjfyokhpujhigtdeqwzp4 + '@azure-tools/cadl-ranch': 0.9.0_3hgbimueyj4cov2ejjvw37nlra '@azure-tools/cadl-ranch-api': 0.4.1 '@azure-tools/cadl-ranch-expect': 0.8.0_34oeiyjczsyn4xxwbbzj3xeide '@azure-tools/typespec-azure-core': 0.36.0_kbxqspk7ypiyd7ngrdjpxga3we @@ -477,41 +477,6 @@ packages: - supports-color dev: true - /@azure-tools/cadl-ranch/0.9.1_tezp5rjfyokhpujhigtdeqwzp4: - resolution: {integrity: sha512-tkfBrPKKKe7C0Wjkz7CvITUg+w5X9WPqFu3wqCCOirofZ/QB1MQboOUI6jPxODMNNiGXJkWPm045YY55ROTA1g==} - engines: {node: '>=16.0.0'} - hasBin: true - dependencies: - '@azure-tools/cadl-ranch-api': 0.4.1 - '@azure-tools/cadl-ranch-coverage-sdk': 0.4.0 - '@azure-tools/cadl-ranch-expect': 0.8.1_hyg5yyh7beodvmafzqxellnzky - '@azure/identity': 3.3.0 - '@types/js-yaml': 4.0.6 - '@typespec/compiler': 0.49.0 - '@typespec/http': 0.49.0_@typespec+compiler@0.49.0 - '@typespec/rest': 0.49.0_eeytn2g3ek3zpawg2doqsgnp3y - ajv: 8.12.0 - body-parser: 1.20.2 - deep-equal: 2.2.2 - express: 4.18.2 - express-promise-router: 4.1.1_express@4.18.2 - glob: 10.3.9 - jackspeak: 2.1.1 - js-yaml: 4.1.0 - morgan: 1.10.0 - node-fetch: 3.3.2 - picocolors: 1.0.0 - source-map-support: 0.5.21 - winston: 3.10.0 - xml2js: 0.5.0 - yargs: 17.7.2 - transitivePeerDependencies: - - '@types/express' - - '@typespec/versioning' - - encoding - - supports-color - dev: true - /@azure-tools/codegen/2.9.2: resolution: {integrity: sha512-brVLyffOtPiEijYYBYgV+4q7IyAfqXIec7XbdEqvv7As6SeEdq5WtbtN9N0LdGVHDWtEfc+JArwIx9aYGFdMUg==} engines: {node: '>=12.0.0'} From ec6444bbe6d65ee2ef8e5f48d1e410ff2450cbfa Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 22 Nov 2023 22:45:12 +0800 Subject: [PATCH 51/60] Update the changes --- .../typespec-ts/src/api/pagingHelpers.ts | 55 ++++++++----------- .../typespec-ts/src/api/pagingHelpers.ts | 55 ++++++++----------- .../api/pagingHelpers.ts | 55 ++++++++----------- .../src/loadTestRun/api/pagingHelpers.ts | 55 ++++++++----------- .../generated/src/api/pagingHelpers.ts | 55 ++++++++----------- .../typespec-ts/src/api/pagingHelpers.ts | 55 ++++++++----------- .../src/modular/buildPagingFiles.ts | 55 ++++++++----------- .../azure/core/src/api/pagingHelpers.ts | 55 ++++++++----------- .../payload/pageable/src/api/pagingHelpers.ts | 55 ++++++++----------- 9 files changed, 207 insertions(+), 288 deletions(-) diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 6f77709048..38ab26c168 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 6f77709048..38ab26c168 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index 76d7427951..9a81a5dac1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index 76d7427951..9a81a5dac1 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index 6f77709048..38ab26c168 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index 6f77709048..38ab26c168 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 286e0cb09b..a50cb3cff5 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -145,7 +145,7 @@ export function buildPagingHelpers( interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -184,12 +184,12 @@ export function buildPagingHelpers( export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -210,7 +210,7 @@ export function buildPagingHelpers( }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -227,7 +227,11 @@ export function buildPagingHelpers( * @returns a paged async iterator that iterates over results. */ - export function getPagedAsyncIterator( + export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings + >( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -243,7 +247,7 @@ export function buildPagingHelpers( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -251,36 +255,24 @@ export function buildPagingHelpers( }; } - async function* getItemAsyncIterator( + async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings + >( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // \`pages\` is of type \`AsyncIterableIterator\` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type \`AsyncIterableIterator\` so \`page\` is of type \`TPage\`. In this branch, - // it must be the case that \`TPage = TElement[]\` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } - async function* getPageAsyncIterator( + async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings + >( pagedResult: PagedResult, options: { pageLink?: string; @@ -337,8 +329,7 @@ export function buildPagingHelpers( // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - \`Couldn't paginate response - Body doesn't contain an array property with name: \${itemName}\` + \`Couldn't paginate response\\n Body doesn't contain an array property with name: \${itemName}\` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index 6f77709048..38ab26c168 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -20,7 +20,7 @@ import { isUnexpected } from "../rest/index.js"; interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -59,12 +59,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -85,7 +85,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -102,7 +102,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -118,7 +122,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -126,36 +130,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -212,8 +204,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index eab3a65de9..3812a472d0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -19,7 +19,7 @@ import { interface PagedResult< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * Link to the first page of results. @@ -58,12 +58,12 @@ export interface BuildPagedAsyncIteratorOptions { export function buildPagedAsyncIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings, + TPageSettings extends PageSettings = PageSettings, TResponse extends PathUncheckedResponse = PathUncheckedResponse >( client: Client, getInitialResponse: () => PromiseLike, - processResponseBody: (result: TResponse) => Promise, + processResponseBody: (result: TResponse) => PromiseLike, options: BuildPagedAsyncIteratorOptions = {} ): PagedAsyncIterableIterator { const itemName = options.itemName ?? "value"; @@ -84,7 +84,7 @@ export function buildPagedAsyncIterator< }; }, byPage: (settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -101,7 +101,11 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator( +export function getPagedAsyncIterator< + TElement, + TPage = TElement[], + TPageSettings extends PageSettings = PageSettings +>( pagedResult: PagedResult ): PagedAsyncIterableIterator { const iter = getItemAsyncIterator( @@ -117,7 +121,7 @@ export function getPagedAsyncIterator( byPage: pagedResult?.byPage ?? ((settings?: TPageSettings) => { - const { continuationToken } = (settings as PageSettings) ?? {}; + const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { pageLink: continuationToken, }); @@ -125,36 +129,24 @@ export function getPagedAsyncIterator( }; } -async function* getItemAsyncIterator( +async function* getItemAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult ): AsyncIterableIterator { const pages = getPageAsyncIterator(pagedResult); - const firstVal = await pages.next(); - // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is - if (!Array.isArray(firstVal.value)) { - // can extract elements from this page - const { toElements } = pagedResult; - if (toElements) { - yield* toElements(firstVal.value) as TElement[]; - for await (const page of pages) { - yield* toElements(page) as TElement[]; - } - } else { - yield firstVal.value; - // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case - yield* pages as unknown as AsyncIterableIterator; - } - } else { - yield* firstVal.value; - for await (const page of pages) { - // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, - // it must be the case that `TPage = TElement[]` - yield* page as unknown as TElement[]; - } + for await (const page of pages) { + yield* page as unknown as TElement[]; } } -async function* getPageAsyncIterator( +async function* getPageAsyncIterator< + TElement, + TPage, + TPageSettings extends PageSettings +>( pagedResult: PagedResult, options: { pageLink?: string; @@ -211,8 +203,7 @@ function getElements(body: unknown, itemName: string): T[] { // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( - `Couldn't paginate response - Body doesn't contain an array property with name: ${itemName}` + `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` ); } From 08843fb3f8037a31f9ab2d282c0a9ba57737bdbd Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 22 Nov 2023 23:09:52 +0800 Subject: [PATCH 52/60] Update the extension TPageSettings extends PageSettings --- .../generated/typespec-ts/src/models/pagingTypes.ts | 2 +- .../generated/typespec-ts/src/models/pagingTypes.ts | 2 +- .../src/loadTestAdministration/models/pagingTypes.ts | 2 +- .../generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts | 2 +- .../typespec-ts/sources/generated/src/models/pagingTypes.ts | 2 +- .../widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts | 2 +- packages/typespec-ts/src/modular/buildPagingFiles.ts | 2 +- .../generated/azure/core/src/models/pagingTypes.ts | 2 +- .../generated/payload/pageable/src/models/pagingTypes.ts | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index a50cb3cff5..a36b1844f4 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -46,7 +46,7 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts index e4b49c8b7e..c2b43c7d76 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts @@ -27,7 +27,7 @@ export type ContinuablePage = TPage & { export interface PagedAsyncIterableIterator< TElement, TPage = TElement[], - TPageSettings = PageSettings + TPageSettings extends PageSettings = PageSettings > { /** * The next method, part of the iteration protocol From fd1b1ee9e2a9186780d88e13f49bc38498208e0a Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 22 Nov 2023 23:20:16 +0800 Subject: [PATCH 53/60] Update the no need export --- .../typespec-ts/src/api/pagingHelpers.ts | 2 +- .../typespec-ts/src/api/pagingHelpers.ts | 2 +- .../api/pagingHelpers.ts | 2 +- .../src/loadTestRun/api/pagingHelpers.ts | 2 +- .../sources/generated/src/api/pagingHelpers.ts | 2 +- .../typespec-ts/src/api/pagingHelpers.ts | 2 +- .../src/modular/buildPagingFiles.ts | 2 +- .../azure/core/src/api/pagingHelpers.ts | 16 ++++++++-------- .../payload/pageable/src/api/pagingHelpers.ts | 18 +++++++++--------- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 38ab26c168..113d89a947 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 38ab26c168..113d89a947 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index 9a81a5dac1..ac6e556718 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index 9a81a5dac1..ac6e556718 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index 38ab26c168..113d89a947 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index 38ab26c168..113d89a947 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index a36b1844f4..6903f84829 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -227,7 +227,7 @@ export function buildPagingHelpers( * @returns a paged async iterator that iterates over results. */ - export function getPagedAsyncIterator< + function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index 38ab26c168..254cc7b4ac 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -4,13 +4,13 @@ import { Client, createRestError, - PathUncheckedResponse, + PathUncheckedResponse } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, - PagedAsyncIterableIterator, + PagedAsyncIterableIterator } from "../models/pagingTypes.js"; import { isUnexpected } from "../rest/index.js"; @@ -81,15 +81,15 @@ export function buildPagedAsyncIterator< const values = getElements(results, itemName) as TPage; return { page: values, - nextPageLink: nextLink, + nextPageLink: nextLink }; }, byPage: (settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, + pageLink: continuationToken }); - }, + } }; return getPagedAsyncIterator(pagedResult); } @@ -102,7 +102,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings @@ -124,9 +124,9 @@ export function getPagedAsyncIterator< ((settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, + pageLink: continuationToken }); - }), + }) }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index 3812a472d0..3485966d73 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -4,13 +4,13 @@ import { Client, createRestError, - PathUncheckedResponse, + PathUncheckedResponse } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { ContinuablePage, PageSettings, - PagedAsyncIterableIterator, + PagedAsyncIterableIterator } from "../models/pagingTypes.js"; /** @@ -80,15 +80,15 @@ export function buildPagedAsyncIterator< const values = getElements(results, itemName) as TPage; return { page: values, - nextPageLink: nextLink, + nextPageLink: nextLink }; }, byPage: (settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, + pageLink: continuationToken }); - }, + } }; return getPagedAsyncIterator(pagedResult); } @@ -101,7 +101,7 @@ export function buildPagedAsyncIterator< * @returns a paged async iterator that iterates over results. */ -export function getPagedAsyncIterator< +function getPagedAsyncIterator< TElement, TPage = TElement[], TPageSettings extends PageSettings = PageSettings @@ -123,9 +123,9 @@ export function getPagedAsyncIterator< ((settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken, + pageLink: continuationToken }); - }), + }) }; } @@ -224,7 +224,7 @@ function checkPagingRequest(response: PathUncheckedResponse): void { "206", "207", "208", - "226", + "226" ]; if (!Http2xxStatusCodes.includes(response.status)) { throw createRestError( From cf997fc14c85b094a3467f129bb59c9c3d2c2795 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Wed, 22 Nov 2023 23:29:15 +0800 Subject: [PATCH 54/60] Remove useless comments --- .../generated/typespec-ts/src/api/pagingHelpers.ts | 4 ---- .../generated/typespec-ts/src/api/pagingHelpers.ts | 4 ---- .../src/loadTestAdministration/api/pagingHelpers.ts | 4 ---- .../typespec-ts/src/loadTestRun/api/pagingHelpers.ts | 4 ---- .../typespec-ts/sources/generated/src/api/pagingHelpers.ts | 4 ---- .../widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts | 4 ---- packages/typespec-ts/src/modular/buildPagingFiles.ts | 4 ---- .../generated/azure/core/src/api/pagingHelpers.ts | 4 ---- .../generated/payload/pageable/src/api/pagingHelpers.ts | 4 ---- 9 files changed, 36 deletions(-) diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 113d89a947..2b1752d2c3 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 113d89a947..2b1752d2c3 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index ac6e556718..6a89c82dd7 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index ac6e556718..6a89c82dd7 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index 113d89a947..2b1752d2c3 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index 113d89a947..2b1752d2c3 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 6903f84829..962e851096 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -323,10 +323,6 @@ export function buildPagingHelpers( */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( \`Couldn't paginate response\\n Body doesn't contain an array property with name: \${itemName}\` diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index 254cc7b4ac..896e8f5864 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -198,10 +198,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index 3485966d73..a3dc2745cf 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -197,10 +197,6 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { */ function getElements(body: unknown, itemName: string): T[] { const value = (body as Record)[itemName] as T[]; - - // value has to be an array according to the x-ms-pageable extension. - // The fact that this must be an array is used above to calculate the - // type of elements in the page in PaginateReturn if (!Array.isArray(value)) { throw new RestError( `Couldn't paginate response\n Body doesn't contain an array property with name: ${itemName}` From 1af1421a94e79eec7e1c68993030cb7e9589817c Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 23 Nov 2023 00:18:10 +0800 Subject: [PATCH 55/60] Regenerate the codes --- .../generated/typespec-ts/review/batch.api.md | 2 +- .../typespec-ts/src/api/pagingHelpers.ts | 41 +-------- .../typespec-ts/src/models/pagingTypes.ts | 39 +++++++++ .../review/ai-content-safety.api.md | 2 +- .../typespec-ts/src/api/pagingHelpers.ts | 41 +-------- .../typespec-ts/src/models/pagingTypes.ts | 39 +++++++++ .../typespec-ts/review/load-testing.api.md | 4 +- .../api/pagingHelpers.ts | 41 +-------- .../models/pagingTypes.ts | 39 +++++++++ .../src/loadTestRun/api/pagingHelpers.ts | 41 +-------- .../src/loadTestRun/models/pagingTypes.ts | 39 +++++++++ .../typespec-ts/review/widget_dpg.api.md | 2 +- .../generated/src/api/pagingHelpers.ts | 41 +-------- .../generated/src/models/pagingTypes.ts | 39 +++++++++ .../typespec-ts/src/api/pagingHelpers.ts | 41 +-------- .../typespec-ts/src/models/pagingTypes.ts | 39 +++++++++ .../src/modular/buildPagingFiles.ts | 87 ++++++++++--------- .../src/modular/buildSubpathIndex.ts | 8 +- .../azure/core/src/api/pagingHelpers.ts | 55 ++---------- .../azure/core/src/models/pagingTypes.ts | 39 +++++++++ .../payload/pageable/src/api/pagingHelpers.ts | 57 +++--------- .../pageable/src/models/pagingTypes.ts | 39 +++++++++ 22 files changed, 401 insertions(+), 374 deletions(-) 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 99a7141ac0..41ee2288b7 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 @@ -1651,7 +1651,7 @@ export interface OutputFileUploadOptions { } // @public -export interface PagedAsyncIterableIterator { +export interface PagedAsyncIterableIterator { [Symbol.asyncIterator](): PagedAsyncIterableIterator; byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 2b1752d2c3..bbd96b160a 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -8,51 +8,14 @@ import { } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} 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 d18df9dc80..77e23bdc58 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 @@ -135,7 +135,7 @@ export interface ListTextBlocklistsOptions extends OperationOptions { } // @public -export interface PagedAsyncIterableIterator { +export interface PagedAsyncIterableIterator { [Symbol.asyncIterator](): PagedAsyncIterableIterator; byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index 2b1752d2c3..bbd96b160a 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -8,51 +8,14 @@ import { } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} 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 871a1592ae..f5707a7f5c 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 @@ -388,7 +388,7 @@ export interface LoadTestRunClientOptions extends ClientOptions { } // @public -export interface LoadTestRunClientPagedAsyncIterableIterator { +export interface LoadTestRunClientPagedAsyncIterableIterator { [Symbol.asyncIterator](): LoadTestRunClientPagedAsyncIterableIterator; byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; @@ -608,7 +608,7 @@ export interface OptionalLoadTestConfig { } // @public -export interface PagedAsyncIterableIterator { +export interface PagedAsyncIterableIterator { [Symbol.asyncIterator](): PagedAsyncIterableIterator; byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index 6a89c82dd7..1c4310af17 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -8,51 +8,14 @@ import { } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index 6a89c82dd7..1c4310af17 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -8,51 +8,14 @@ import { } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} 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 addf234456..76c2d51f8f 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 @@ -32,7 +32,7 @@ export interface ListWidgetsPagesResults { } // @public -export interface PagedAsyncIterableIterator { +export interface PagedAsyncIterableIterator { [Symbol.asyncIterator](): PagedAsyncIterableIterator; byPage: (settings?: TPageSettings) => AsyncIterableIterator>; next(): Promise>; diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index 2b1752d2c3..bbd96b160a 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -8,51 +8,14 @@ import { } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index 2b1752d2c3..bbd96b160a 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -8,51 +8,14 @@ import { } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index 962e851096..b8a1367f30 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -19,7 +19,6 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { }); fileContent.addStatements([ ` - /** * An interface that tracks the settings for paged iteration */ @@ -67,6 +66,45 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { 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) => unknown[]; + } + + /** + * Options for the paging helper + */ + export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; + } ` ]); @@ -136,47 +174,14 @@ export function buildPagingHelpers( PathUncheckedResponse } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; - import { ContinuablePage, PageSettings, PagedAsyncIterableIterator } from "${pagingTypesPath}"; + import { + BuildPagedAsyncIteratorOptions, + ContinuablePage, + PageSettings, + PagedAsyncIterableIterator, + PagedResult, + } from "${pagingTypesPath}"; ${unexpectedHelperImport} - - /** - * An interface that describes how to communicate with the service. - */ - 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) => unknown[]; - } - - /** - * Options for the paging helper - */ - export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; - } /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator diff --git a/packages/typespec-ts/src/modular/buildSubpathIndex.ts b/packages/typespec-ts/src/modular/buildSubpathIndex.ts index 3de96c12af..2dfbc67867 100644 --- a/packages/typespec-ts/src/modular/buildSubpathIndex.ts +++ b/packages/typespec-ts/src/modular/buildSubpathIndex.ts @@ -41,7 +41,7 @@ export function buildSubpathIndexFile( continue; } - const namedExports: string[] = [...file.getExportedDeclarations().entries()] + let namedExports: string[] = [...file.getExportedDeclarations().entries()] .filter((exDeclaration) => { if (exDeclaration[0].startsWith("_")) { return false; @@ -59,6 +59,12 @@ export function buildSubpathIndexFile( .map((exDeclaration) => { return exDeclaration[0]; }); + // Skip to export PagedResult and BuildPagedAsyncIteratorOptions + if (file.getFilePath().endsWith("pagingTypes.ts")) { + namedExports = namedExports.filter( + (ex) => !["PagedResult", "BuildPagedAsyncIteratorOptions"].includes(ex) + ); + } indexFile.addExportDeclaration({ moduleSpecifier: `.${file .getFilePath() diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index 896e8f5864..bbd96b160a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -4,55 +4,18 @@ import { Client, createRestError, - PathUncheckedResponse + PathUncheckedResponse, } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, - PagedAsyncIterableIterator + PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; import { isUnexpected } from "../rest/index.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -81,15 +44,15 @@ export function buildPagedAsyncIterator< const values = getElements(results, itemName) as TPage; return { page: values, - nextPageLink: nextLink + nextPageLink: nextLink, }; }, byPage: (settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken + pageLink: continuationToken, }); - } + }, }; return getPagedAsyncIterator(pagedResult); } @@ -124,9 +87,9 @@ function getPagedAsyncIterator< ((settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken + pageLink: continuationToken, }); - }) + }), }; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index a3dc2745cf..038cd377cb 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -4,54 +4,17 @@ import { Client, createRestError, - PathUncheckedResponse + PathUncheckedResponse, } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { + BuildPagedAsyncIteratorOptions, ContinuablePage, PageSettings, - PagedAsyncIterableIterator + PagedAsyncIterableIterator, + PagedResult, } from "../models/pagingTypes.js"; -/** - * An interface that describes how to communicate with the service. - */ -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) => unknown[]; -} - -/** - * Options for the paging helper - */ -export interface BuildPagedAsyncIteratorOptions { - itemName?: string; - nextLinkName?: string; -} - /** * Helper to paginate results in a generic way and return a PagedAsyncIterableIterator */ @@ -80,15 +43,15 @@ export function buildPagedAsyncIterator< const values = getElements(results, itemName) as TPage; return { page: values, - nextPageLink: nextLink + nextPageLink: nextLink, }; }, byPage: (settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken + pageLink: continuationToken, }); - } + }, }; return getPagedAsyncIterator(pagedResult); } @@ -123,9 +86,9 @@ function getPagedAsyncIterator< ((settings?: TPageSettings) => { const { continuationToken } = settings ?? {}; return getPageAsyncIterator(pagedResult, { - pageLink: continuationToken + pageLink: continuationToken, }); - }) + }), }; } @@ -220,7 +183,7 @@ function checkPagingRequest(response: PathUncheckedResponse): void { "206", "207", "208", - "226" + "226", ]; if (!Http2xxStatusCodes.includes(response.status)) { throw createRestError( diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts index c2b43c7d76..da561dd0b0 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts @@ -48,3 +48,42 @@ export interface PagedAsyncIterableIterator< 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) => unknown[]; +} + +/** + * Options for the paging helper + */ +export interface BuildPagedAsyncIteratorOptions { + itemName?: string; + nextLinkName?: string; +} From 2539366609185f56c0eca41806b54eb4c911a409 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 23 Nov 2023 11:15:10 +0800 Subject: [PATCH 56/60] Update packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts Co-authored-by: Deyaaeldeen Almahallawi --- .../generated/typespec-ts/src/models/pagingTypes.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index da561dd0b0..9720fbdc1a 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -2,7 +2,7 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** From b002b3b9b0d22c3ed215cf44a3e95932b8c67b70 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 23 Nov 2023 11:15:23 +0800 Subject: [PATCH 57/60] Update packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts Co-authored-by: Deyaaeldeen Almahallawi --- .../generated/typespec-ts/src/models/pagingTypes.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index 9720fbdc1a..653f633a20 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -6,7 +6,7 @@ */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } From 7d13c24c9b81bc637988738cd42c47a4874ebeba Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Thu, 23 Nov 2023 12:22:21 +0800 Subject: [PATCH 58/60] Regenerate codes to resolve comments --- .../typespec-ts/src/api/pagingHelpers.ts | 12 ++++++++++-- .../typespec-ts/src/models/pagingTypes.ts | 6 +++--- .../typespec-ts/src/api/pagingHelpers.ts | 12 ++++++++++-- .../typespec-ts/src/models/pagingTypes.ts | 2 +- .../api/pagingHelpers.ts | 12 ++++++++++-- .../models/pagingTypes.ts | 6 +++--- .../src/loadTestRun/api/pagingHelpers.ts | 12 ++++++++++-- .../src/loadTestRun/models/pagingTypes.ts | 6 +++--- .../sources/generated/src/api/pagingHelpers.ts | 12 ++++++++++-- .../generated/src/models/pagingTypes.ts | 6 +++--- .../typespec-ts/src/api/pagingHelpers.ts | 12 ++++++++++-- .../typespec-ts/src/models/pagingTypes.ts | 6 +++--- .../src/modular/buildPagingFiles.ts | 18 +++++++++++++----- .../azure/core/src/api/pagingHelpers.ts | 12 ++++++++++-- .../azure/core/src/models/pagingTypes.ts | 6 +++--- .../payload/pageable/src/api/pagingHelpers.ts | 12 ++++++++++-- .../payload/pageable/src/models/pagingTypes.ts | 6 +++--- 17 files changed, 115 insertions(+), 43 deletions(-) diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts index bbd96b160a..5ef48f6c4a 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/batch_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts index bbd96b160a..5ef48f6c4a 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts index 653f633a20..5618769059 100644 --- a/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/contentsafety_modular/generated/typespec-ts/src/models/pagingTypes.ts @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts index 1c4310af17..8a2730cfda 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestAdministration/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts index 1c4310af17..8a2730cfda 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts +++ b/packages/typespec-test/test/loadtesting_modular/generated/typespec-ts/src/loadTestRun/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts index bbd96b160a..5ef48f6c4a 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/sources/generated/src/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts index bbd96b160a..5ef48f6c4a 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts +++ b/packages/typespec-test/test/widget_dpg/generated/typespec-ts/src/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-ts/src/modular/buildPagingFiles.ts b/packages/typespec-ts/src/modular/buildPagingFiles.ts index b8a1367f30..a72fd7333d 100644 --- a/packages/typespec-ts/src/modular/buildPagingFiles.ts +++ b/packages/typespec-ts/src/modular/buildPagingFiles.ts @@ -20,11 +20,11 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { fileContent.addStatements([ ` /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -95,7 +95,7 @@ export function buildPagingTypes(codeModel: ModularCodeModel, client: Client) { /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** @@ -314,12 +314,20 @@ export function buildPagingHelpers( const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - \`Body Property \${nextLinkName} should be a string or undefined\` + \`Body Property \${nextLinkName} should be a string or undefined or null but got \${typeof nextLink}\` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts index bbd96b160a..5ef48f6c4a 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/pagingHelpers.ts @@ -147,12 +147,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts index 038cd377cb..d9253c521d 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/api/pagingHelpers.ts @@ -146,12 +146,20 @@ function getNextLink(body: unknown, nextLinkName?: string): string | undefined { const nextLink = (body as Record)[nextLinkName]; - if (typeof nextLink !== "string" && typeof nextLink !== "undefined") { + if ( + typeof nextLink !== "string" && + typeof nextLink !== "undefined" && + nextLink !== null + ) { throw new RestError( - `Body Property ${nextLinkName} should be a string or undefined` + `Body Property ${nextLinkName} should be a string or undefined or null but got ${typeof nextLink}` ); } + if (nextLink === null) { + return undefined; + } + return nextLink; } diff --git a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts index da561dd0b0..5618769059 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/payload/pageable/src/models/pagingTypes.ts @@ -2,11 +2,11 @@ // Licensed under the MIT license. /** - * An interface that tracks the settings for paged iteration + * Options for the byPage method */ export interface PageSettings { /** - * The token that keeps track of where to continue the iterator + * A reference to a specific page to start iterating from. */ continuationToken?: string; } @@ -77,7 +77,7 @@ export interface PagedResult< /** * A function to extract elements from a page. */ - toElements?: (page: TPage) => unknown[]; + toElements?: (page: TPage) => TElement[]; } /** From 88d3ffd5b5b0cf59da12a004bbba6ee262f93dcb Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 27 Nov 2023 17:24:45 +0800 Subject: [PATCH 59/60] Re-generate the paging modular sdk --- .../generated/azure/core/src/BasicClient.ts | 14 +++--- .../azure/core/src/api/operations.ts | 44 +++++++++++++------ .../generated/azure/core/src/index.ts | 2 + 3 files changed, 38 insertions(+), 22 deletions(-) diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts index e0f2c373cc..16d1bf330f 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/BasicClient.ts @@ -2,13 +2,11 @@ // Licensed under the MIT license. import { Pipeline } from "@azure/core-rest-pipeline"; -import { User } from "./models/models.js"; +import { User, ListItemInputBody, - UserListResults, - PagedUser, - PagedFirstItem, - PagedSecondItem, + FirstItem, + SecondItem, } from "./models/models.js"; import { CreateOrUpdateOptions, @@ -95,7 +93,7 @@ export class BasicClient { listWithParameters( bodyInput: ListItemInputBody, options: ListWithParametersOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listWithParameters(this._client, bodyInput, options); } @@ -126,14 +124,14 @@ export class BasicClient { /** Two operations with two different page item types should be successfully generated. Should generate model for FirstItem. */ listFirstItem( options: ListFirstItemOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listFirstItem(this._client, options); } /** Two operations with two different page item types should be successfully generated. Should generate model for SecondItem. */ listSecondItem( options: ListSecondItemOptions = { requestOptions: {} } - ): Promise { + ): PagedAsyncIterableIterator { return listSecondItem(this._client, options); } } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts index 3d6193b8ae..1c9b00b115 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/api/operations.ts @@ -2,13 +2,17 @@ // Licensed under the MIT license. import { -import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; -import { buildPagedAsyncIterator } from "./pagingHelpers.js"; + User, + ListItemInputBody, UserListResults, PagedUser, PagedFirstItem, + FirstItem, PagedSecondItem, + SecondItem, } from "../models/models.js"; +import { PagedAsyncIterableIterator } from "../models/pagingTypes.js"; +import { buildPagedAsyncIterator } from "./pagingHelpers.js"; import { isUnexpected, BasicContext as Client, @@ -374,13 +378,17 @@ export async function _listWithParametersDeserialize( } /** List with extensible enum parameter Azure.Core.Page<>. */ -export async function listWithParameters( +export function listWithParameters( context: Client, bodyInput: ListItemInputBody, options: ListWithParametersOptions = { requestOptions: {} } -): Promise { - const result = await _listWithParametersSend(context, bodyInput, options); - return _listWithParametersDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listWithParametersSend(context, bodyInput, options), + _listWithParametersDeserialize, + { itemName: "value", nextLinkName: "nextLink" } + ); } export function _listWithCustomPageModelSend( @@ -536,12 +544,16 @@ export async function _listFirstItemDeserialize( } /** Two operations with two different page item types should be successfully generated. Should generate model for FirstItem. */ -export async function listFirstItem( +export function listFirstItem( context: Client, options: ListFirstItemOptions = { requestOptions: {} } -): Promise { - const result = await _listFirstItemSend(context, options); - return _listFirstItemDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listFirstItemSend(context, options), + _listFirstItemDeserialize, + { itemName: "value", nextLinkName: "nextLink" } + ); } export function _listSecondItemSend( @@ -567,10 +579,14 @@ export async function _listSecondItemDeserialize( } /** Two operations with two different page item types should be successfully generated. Should generate model for SecondItem. */ -export async function listSecondItem( +export function listSecondItem( context: Client, options: ListSecondItemOptions = { requestOptions: {} } -): Promise { - const result = await _listSecondItemSend(context, options); - return _listSecondItemDeserialize(result); +): PagedAsyncIterableIterator { + return buildPagedAsyncIterator( + context, + () => _listSecondItemSend(context, options), + _listSecondItemDeserialize, + { itemName: "value", nextLinkName: "nextLink" } + ); } diff --git a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts index 09134ca8f2..b854207261 100644 --- a/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts +++ b/packages/typespec-ts/test/modularIntegration/generated/azure/core/src/index.ts @@ -22,6 +22,8 @@ export { ListWithCustomPageModelOptions, DeleteOperationOptions, ExportOperationOptions, + ListFirstItemOptions, + ListSecondItemOptions, PageSettings, ContinuablePage, PagedAsyncIterableIterator, From 09696c0c36e2a394a0825e0e673bf6f77ba9ba81 Mon Sep 17 00:00:00 2001 From: Mary Gao Date: Mon, 27 Nov 2023 20:15:54 +0800 Subject: [PATCH 60/60] Add paging cases in modular --- .../test/modularIntegration/azureCore.spec.ts | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts index 63a410d2fa..eca29fdcfd 100644 --- a/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts +++ b/packages/typespec-ts/test/modularIntegration/azureCore.spec.ts @@ -122,4 +122,41 @@ describe("BasicClient Classical Client", () => { assert.strictEqual(items[0]?.name, "Madge"); assert.strictEqual(items[0]?.etag, "11bdc430-65e8-45ad-81d9-8ffa60d55b59"); }); + + it("should list with parameters", async () => { + const customPageIter = await client.listWithParameters( + { + inputName: "Madge" + }, + { + another: "Second" + } + ); + const items = []; + for await (const user of customPageIter) { + items.push(user); + } + assert.strictEqual(items.length, 1); + assert.strictEqual(items[0]?.name, "Madge"); + }); + + it("should list first item", async () => { + const customPageIter = await client.listFirstItem(); + const items = []; + for await (const user of customPageIter) { + items.push(user); + } + assert.strictEqual(items.length, 1); + assert.strictEqual(items[0]?.id, 1); + }); + + it("should list second item", async () => { + const customPageIter = await client.listSecondItem(); + const items = []; + for await (const user of customPageIter) { + items.push(user); + } + assert.strictEqual(items.length, 1); + assert.strictEqual(items[0]?.name, "Madge"); + }); });